text:
autoCalibrateAccelerometerOffset() Why does my Z values swing from 0 to 1g in static condition?
I tried to implement the autoCalibrateAccelerometerOffset() function, through the code below on Arduino Genuino 101.
In a static test, without any stress or noise, I read the three axis value.
When I see the data on the serial monitor or on my file created with processing, the Z acceleration values changes from 1~0,99 to 0,00 g.

I think there is an error in my code.
#include "SoftwareSerial.h"
#include "CurieIMU.h"

float sensorVals[] = {0,0,0};

void setup() {

    Serial.begin(9600);
    while (!Serial);

    Serial.println("Inizializzazione del device...");
    CurieIMU.begin();

    CurieIMU.setAccelerometerRange(2);
    CurieIMU.autoCalibrateAccelerometerOffset(X_AXIS,0);
    CurieIMU.autoCalibrateAccelerometerOffset(Y_AXIS,0);
    CurieIMU.autoCalibrateAccelerometerOffset(Z_AXIS,1);
}

void loop() {

    sensorVals[0] = CurieIMU.readAccelerometerScaled(0);
    sensorVals[1] = CurieIMU.readAccelerometerScaled(1);
    sensorVals[2] = CurieIMU.readAccelerometerScaled(2);

    Serial.print(sensorVals[0]);
    Serial.print(",");
    Serial.print(sensorVals[1]);
    Serial.print(",");
    Serial.println(sensorVals[2]);
    delay(100);
}

What happens if you add CurieIMU.autoCalibrateGyroOffset(); right after CurieIMU.begin(); ?

Do you know you have Z oriented as expected?

I'm voting to close this old abandoned question as information to make it answerable has never been provided.  The obvious way to debug this is to print out both the raw and calibrated values.  That would show if it is a reading error, or the more likely case of the calibration "calibrating out" gravity.

If it is calibrating out gravity, why does it flip between values? I would be interested to see it calibrated, then tipped slightly in X/Y to see if the rows with "Z: 0" also have X/Y: 0 (they shouldnt), and if they do, then it's likely an issue with the sensor or reading too quickly from the sensor, or similar. I just dont see how calibrating out the Z would flip between 0 and 1 as per sample

@SDsolar because is a specific function of CURIE IMU library compatible only with Arduino and Genuino 101 only

@ChrisStratton the problem is related in my opinion to the Official Library function not with the sensor reading, because without applying the calibration function  in the same condition and without perturbations the sensors reading doesn't have any swinging values

Assuming you aren't jumping up and down while this is happening then it could be:

A loose wire
A dodgy power supply
A bad earth connection
A fault sensor
A weird magnetic field/flux thing

Check you wiring, make sure all the connections are secure, etc.  I bet you have done that already.
I have no idea how to check a power supply, but if you have a different one you could switch that in.  Also look into smoothing the power supply with decoupling capacitors (?)
A bad earth, all sorts of weird [stuff] happens when you haven't earthed things properly.  Different power supplies need to share earths, but I suspect that doesn't apply here.
A faulty sensor - again, unless you have a duplicate you might not know.
Weird flux.  I think the sensor is a magnetic sensor and so it could be the natural eddies and flows of magnetic flux have conspired against you.  Move the sensor away from power supplies, electrical things and specifically anything you are hacking.  Also rotate the sensor through 90 degrees and see if it still happens (With RF it will polarise the fields in a different way, and school was a long time ago and I can't remember if that works with magnetic fields too)

If i don't use the autoCalibrateAccelerometerOffset(), and i get the raw data  the values are not calibrated but stable, so i think i can exclude: Fault sensor, Power Supply, Loose Wire, Faulty Sensor, a weird magnetic field :) Thanks

An accelerometer has nothing to do with magnetic fields, unless the fields are strong enough to physically move the device.


text:
Arduino Robot won't move
I am building a robot for a school project. I use an Arduino Uno, 2 dc motor's and an Ultra Sonic range measurement module. I want the robot to be autonomous, he has to be able to move around on his own using the Ultra Sonic sensor. Important to mention is that I don't use a MotorShield to control my dc motors. This is my latest version of coding:

#include <Servo.h> //include Servo library
#include <AFMotor.h> //include DC motor Library
#define trigPin 12// define the pins of your sensor
#define echoPin 13
AF_DCMotor motor2(7); // set up motors.
AF_DCMotor motor1(6);

void setup() {
  Serial.begin(9600); // begin serial communitication
  Serial.println("Motor test!");
   pinMode(trigPin, OUTPUT);// set the trig pin to output (Send sound waves)
  pinMode(echoPin, INPUT);// set the echo pin to input (recieve sound waves)
  motor1.setSpeed(105); //set the speed of the motors, between 0-255
    motor2.setSpeed (105);
}

void loop() {

   long duration, distance; // start the scan
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2); // delays are required for a succesful sensor operation.
  digitalWrite(trigPin, HIGH);

  delayMicroseconds(10); //this delay is required as well!
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;// convert the distance to centimeters.
  if (distance < 25)/*if there's an obstacle 25 centimers, ahead, do the following: */ {
   Serial.println ("Close Obstacle detected!" );
Serial.println ("Obstacle Details:");
Serial.print ("Distance From Robot is " );
Serial.print ( distance);
Serial.print ( " CM!");// print out the distance in centimeters.

Serial.println (" The obstacle is declared a threat due to close distance. ");
Serial.println (" Turning !");
    motor1.run(FORWARD);  // Turn as long as there's an obstacle ahead.
      motor2.run (BACKWARD);

}
  else {
   Serial.println ("No obstacle detected. going forward");
   delay (15);
   motor1.run(FORWARD); //if there's no obstacle ahead, Go Forward!
    motor2.run(FORWARD);
  }

}

Now I added an ARDUINO MOTOR SHIELD REV3 to control my dc motors. Now the wheels are actually spinning, but after a few turns they stop. I think it is software related, but I am not 100% sure. Also I think I am connecting my motors correct to my motorshield, but don't adress them properly in my code.
And I don't have any clue how to solve this problem.
Can anybody help me with this?

Break it down into parts. Test each part independently. Then you'll know which one is (or ones are) broken. You already have prints in there to tell you what's going on - so what IS going on? Is it detecting obstacles etc?  Please supply a circuit diagram.  Are you attempting to drive motors directly from the Arduino outputs? This will not work, and I would be surprised if it hadn't already cooked your Arduino.

Include a schematic of how you've connected everything and you'll probably get better answers to your questions.

I think your problem is that you connected the positive wire to the 5v pin when it said 5v and not 9v. Also, I am assuming the 6 double AA is in series creating 9v. The thing is, double AA has a lot of amps. I tested it with my multimeter and it has 7 Amps, way to much. What I would do it connect a 9v battery to the voltage in pin-Vin. That pin can take a 9v but not 7 Amps produced by your 6 AA in series. You have 2 dc motors you said.Each is running I am assuming for each of them I notice draw about 1 Amp. 9v will supply enough and be safe. Try connecting a 9v to the Vin pin. I don't think your issue is software related.

Your understanding of the way current is drawn is flawed. A circuit will draw a current - the battery cannot somehow pump a specific current through a circuit.  The short-circuit current produced by six AA batteries is not a useful or meaningful here.

The battery is not drawing, I never said that. The Vin pin is taking in voltage from the battery. Measure the Amps of a 9v and a double AA battery, you will notice a difference. All I am saying is that the 5v outputs power and not input power. Please read what I said again, I think you're misinterpreting what I am saying.

Sean, I read it the same way Mark did. I'm not sure if this is a language issue or if you need to study a little more about what current and Amps mean.Circuits will always follow Ohms law. From this you would know that voltage and resistance determine how much current a circuit will draw from it's source. If the source can't deliver that much current you'll get unreliable or no results. If the source can deliver more current it doesn't force more current into the circuit.

I do know about amps and voltage. I thought I explained good enough, but looks like I did not. The pin he is using is the 5v, not the Vin pin, the Vin pin takes power into the arduino, the 5v supplies power out to a device connected to the arduino. I was also trying to mention that a double AA battery has 7 Amps, I tested it with my multi meter many times. He has a pack, meaning it is wired in series and not parrel. I am saying his circuit is wrong. & amps is to much for the arduino. A 9v supplies about 2 amps. That is max for arduino, so it will be fine. I am considering volts and amps.

Sean, it seems like I wasn't clear enough myself. I use the Vin port for my battery pack. I use a breadboard to make all the wiring. The breadboard itself is connected to the 5V port on my arduino.

source: Stack Exchange

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

sort: votes


text:
How to set counter for two ultrasonic sensors?
This question has been asked many times in many sites but I am unable to find answer for my problem. I wanted to measure the speed of Vehicle using Ultrasonic sensors. Two sensors are placed along the side of the road and when a vehicle passes in front of first sensor(i.e echo1 is HIGH) then it should start counting until when the vehicle crosses the second sensor(i.e echo2=HIGH). So I will get the time. But I don't know how to set time counter. I searched in Internet a lot and I learnt about millis(). So I wrote code using millis(). But the problem is,it starts counting as the program runs. I also tried using array to save the values and subtract final reading from initial one but I'm unable to do that too. I cannot create large size of arrays. Please help me how do I set timer for it?

Are you asking how to measure the elapsed time between two events?

Yes. Elasped time between the condition when both the echo pins are high.

Just get the time when the first pin goes high, and get it again when the second pin goes high, and subtract them to find the difference.
This is an example of how you could do that. It doesn't contain anything about the ultrasonic sensors, just how to measure an elapsed time between two pins going high.
#define echo1 3 // Set your echo pins here
#define echo2 4

unsigned long startTime = 0;
unsigned long endTime = 0;

void setup() {
}

void loop() {
    // You can do stuff here

    // If the first sensor goes off
    if (digitalRead(echo1) && (0==startTime))
    {
        // Remember the time this happened
        startTime = millis();
    }
    // If the second sensor goes off
    if (digitalRead(echo2) && (0==endTime))
    {
        // Remember the time this happened
        endTime = millis();
    }

    // If we have both start and end times
    if (0 != startTime && 0 != endTime)
    {
        unsigned long duration = endTime - startTime;
        // Do what you want with "duration"
    }

}

It seems to work. But here the problem is the range of ultrasonic sensor. The sensor can detect the object even up to 300-400 cm so here the sensor cannot work in narrow road as it will detect the objects across the road too and the echo pin will never be at LOW state,if I am not wrong.

Well, that's a different question.  Please post one question at a time.  It would be worth reading how to ask a good question and then posting a new question.  Please consider accepting the answer if it answers the question you asked.

I tried coding according to your given code but the above problem arose so I thought commenting here,if you might have any answer for that.

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


text:
Is the DHT.h library compatible with ESP8266 Arduino IDE compiler?
I'm using the following 'compiler' to program my ESP8266-01 direct with Arduino IDE:
https://github.com/esp8266/Arduino
and I'm trying to read the temperature and humidity with the following library:
https://github.com/adafruit/DHT-sensor-library
since the DHT library was developed to be used on an Arduino board, should I be able to run it on the ESP8266?

Yes, it does work. You may have a look at http://esp8266.github.io/Arduino/versions/2.3.0/doc/libraries.html where a list of libraries running with ESP8266 can be found. Furthermore, @anrieff's remarks regarding hardware-specific features are a good hint.

As far as I see, the DHT sensor library does bit-banging, which is kind of expected given the ad-hoc nature of the protocol that DHT type of sensors utilize. It should be compatible, as the library doesn't use any Atmel-specific features of the MCU.


text:
I'm facing a problem with cap sense proximity
I've made use of the cap sense library in Arduino to make a touch less piano. I went according to my design and tried it out. Even after using a 10M ohm resistor, my program is only responding when I'm touching the electrodes. I want it to start detecting my finger from at least a few inches away.
I've posted the schematic and code for Arduino and Processing below.

Code for processing:
import ddf.minim.*;
import processing.serial.*;

Minim minim;
AudioPlayer song40;
AudioPlayer song41;
AudioPlayer song42;
AudioPlayer song43;
AudioPlayer song44;
AudioPlayer song45;
AudioPlayer song46;
AudioPlayer song47;
AudioPlayer song48;
AudioPlayer song49;

Serial myPort;  // Create object from Serial class
String val;     // Data received from the serial port

int r=0;
int m=1;
void setup()
{
  minim = new Minim(this);
  song40 = minim.loadFile("40.wav");
  song41 = minim.loadFile("41.wav");
  song42 = minim.loadFile("42.wav");
  song43 = minim.loadFile("43.wav");
  song44 = minim.loadFile("44.wav");
  song45 = minim.loadFile("45.wav");
  song46 = minim.loadFile("46.wav");
  song47 = minim.loadFile("47.wav");
  song48 = minim.loadFile("48.wav");
  song49 = minim.loadFile("49.wav");

  String portName = "/dev/cu.usbmodem1411";                             //Change COM48 to the port number that your Arduino is connected, you can check the port number from arduino program.
  myPort = new Serial(this, portName, 115200);

  size(160, 160);
  background(0);
}

void draw()
{
  if ( myPort.available() > 0 )
  {  // If data is available,
    val = myPort.readStringUntil('\n');
    if(val!=null)
    {
      print(val);
      if(val.charAt(0)=='a')
      {
        song40.rewind();
        song40.play();
        fill(0, 0, 0);
        rect(0, 0, 160, 160);
        fill(255, 255, 255);
        textAlign(CENTER);
        textSize(50);
        text("DO", 80, 90);
      }
      if(val.charAt(0)=='b')
      {
        song41.rewind();
        song41.play();
        fill(0, 0, 0);
        rect(0, 0, 160, 160);
        fill(255, 255, 255);
        textAlign(CENTER);
        textSize(50);
        text("DO#", 80, 90);
      }
      if(val.charAt(0)=='c')
      {
        song42.rewind();
        song42.play();
        fill(0, 0, 0);
        rect(0, 0, 160, 160);
        fill(255, 255, 255);
        textAlign(CENTER);
        textSize(50);
        text("RE", 80, 90);
      }
      if(val.charAt(0)=='d')
      {
        song43.rewind();
        song43.play();
        fill(0, 0, 0);
        rect(0, 0, 160, 160);
        fill(255, 255, 255);
        textAlign(CENTER);
        textSize(50);
        text("RE#", 80, 90);
      }
      if(val.charAt(0)=='e')
      {
        song44.rewind();
        song44.play();
        fill(0, 0, 0);
        rect(0, 0, 160, 160);
        fill(255, 255, 255);
        textAlign(CENTER);
        textSize(50);
        text("MI", 80, 90);
      }
      if(val.charAt(0)=='f')
      {
        song45.rewind();
        song45.play();
        fill(0, 0, 0);
        rect(0, 0, 160, 160);
        fill(255, 255, 255);
        textAlign(CENTER);
        textSize(50);
        text("FA", 80, 90);
      }
      if(val.charAt(0)=='g')
      {
        song46.rewind();
        song46.play();
        fill(0, 0, 0);
        rect(0, 0, 160, 160);
        fill(255, 255, 255);
        textAlign(CENTER);
        textSize(50);
        text("FA#", 80, 90);
      }
      if(val.charAt(0)=='h')
      {
        song47.rewind();
        song47.play();
        fill(0, 0, 0);
        rect(0, 0, 160, 160);
        fill(255, 255, 255);
        textAlign(CENTER);
        textSize(50);
        text("SOL", 80, 90);
      }
      if(val.charAt(0)=='i')
      {
        song48.rewind();
        song48.play();
        fill(0, 0, 0);
        rect(0, 0, 160, 160);
        fill(255, 255, 255);
        textAlign(CENTER);
        textSize(50);
        text("SOL#", 80, 90);
      }
      if(val.charAt(0)=='j')
      {
        song49.rewind();
        song49.play();
        fill(0, 0, 0);
        rect(0, 0, 160, 160);
        fill(255, 255, 255);
        textAlign(CENTER);
        textSize(50);
        text("LA", 80, 90);
      }
    }
  }

  if (mousePressed == true)
  {
    if(r==1)
    {
      myPort.write(' ');
      background(0);
    }
    r=0;
    m=1;
  }
}

public void stop()
{
  minim.stop();
}

And here's the Arduino Code:
#include <SD.h>
#include <CapacitiveSensor.h>

#define total 30                   //define sensitivity, high value for decreases sensitivity, low value increases
#define sensor 1                  //define number of samples Arduino takes, high value will increase stability while increasing response time
#define replay 40                 //define debouncing, high value will increase stability while increasing response time

int led = 13;
int state = HIGH;

boolean yes12;
boolean previous12 = false;

boolean yes11;
boolean previous11 = false;

boolean yes10;
boolean previous10 = false;

boolean yes9;
boolean previous9 = false;

boolean yes8;
boolean previous8 = false;

boolean yes7;
boolean previous7 = false;

boolean yes6;
boolean previous6 = false;

boolean yes5;
boolean previous5 = false;

boolean yes4;
boolean previous4 = false;

boolean yes3;
boolean previous3 = false;

CapacitiveSensor   cs_2_12 = CapacitiveSensor(2,12);        // 2.2M resistor between pins 2 & 12, pin 2 is send pin, pin 12 is sensor pin
CapacitiveSensor   cs_2_11 = CapacitiveSensor(2,11);        // 2.2M resistor between pins 2 & 11, pin 2 is send pin, pin 11 is sensor pin
CapacitiveSensor   cs_2_10 = CapacitiveSensor(2,10);        // 2.2M resistor between pins 2 & 10, pin 2 is send pin, pin 10 is sensor pin
CapacitiveSensor   cs_2_9 = CapacitiveSensor(2,9);
CapacitiveSensor   cs_2_8 = CapacitiveSensor(2,8);
CapacitiveSensor   cs_2_7 = CapacitiveSensor(2,7);
CapacitiveSensor   cs_2_6 = CapacitiveSensor(2,6);
CapacitiveSensor   cs_2_5 = CapacitiveSensor(2,5);
CapacitiveSensor   cs_2_4 = CapacitiveSensor(2,4);
CapacitiveSensor   cs_2_3 = CapacitiveSensor(2,3);

void setup()
{
  cs_2_12.set_CS_AutocaL_Millis(0xFFFFFFFF);  //Calibrate the sensor...
  cs_2_11.set_CS_AutocaL_Millis(0xFFFFFFFF);
  cs_2_10.set_CS_AutocaL_Millis(0xFFFFFFFF);
  cs_2_9.set_CS_AutocaL_Millis(0xFFFFFFFF);
  cs_2_8.set_CS_AutocaL_Millis(0xFFFFFFFF);
  cs_2_7.set_CS_AutocaL_Millis(0xFFFFFFFF);
  cs_2_6.set_CS_AutocaL_Millis(0xFFFFFFFF);
  cs_2_5.set_CS_AutocaL_Millis(0xFFFFFFFF);
  cs_2_4.set_CS_AutocaL_Millis(0xFFFFFFFF);
  cs_2_3.set_CS_AutocaL_Millis(0xFFFFFFFF);
  pinMode(led, OUTPUT);
  Serial.begin(115200);
}

short int a=1,a1=0,b=1,b1=0,c=1,c1=0,d=1,d1=0,e=1,e1=0,f=1,f1=0,g=1,g1=0,h=1,h1=0,i=1,i1=0,j=1,j1=0;  //for debounce purpose

void loop()
{
  long total112 =  cs_2_12.capacitiveSensor(sensor);
  long total111 =  cs_2_11.capacitiveSensor(sensor);
  long total110 =  cs_2_10.capacitiveSensor(sensor);
  long total19 =  cs_2_9.capacitiveSensor(sensor);
  long total18 =  cs_2_8.capacitiveSensor(sensor);
  long total17 =  cs_2_7.capacitiveSensor(sensor);
  long total16 =  cs_2_6.capacitiveSensor(sensor);
  long total15 =  cs_2_5.capacitiveSensor(sensor);
  long total14 =  cs_2_4.capacitiveSensor(sensor);
  long total13 =  cs_2_3.capacitiveSensor(sensor);

  if (total112 > total){yes12 = true;}
  else {yes12 = false;}

  if (total111 > total){yes11 = true;}
  else {yes11 = false;}

  if (total110 > total){yes10 = true;}
  else {yes10 = false;}

  if (total19 > total){yes9 = true;}
  else {yes9 = false;}

  if (total18 > total){yes8 = true;}
  else {yes8 = false;}

  if (total17 > total){yes7 = true;}
  else {yes7 = false;}

  if (total16 > total){yes6 = true;}
  else {yes6 = false;}

  if (total15 > total){yes5 = true;}
  else {yes5 = false;}

  if (total14 > total){yes4 = true;}
  else {yes4 = false;}

  if (total13 > total){yes3 = true;}
  else {yes3 = false;}

  if(yes12 == true && previous12  == false && a)
  {
      if(state == LOW) {
        state = HIGH;
      }
      else
        state = LOW;
      a = 0;
      a1 = 0;
      Serial.println('a');
  }
  if(yes12 == false && previous12  == false)
    a1++;
  else
    a1=0;
  if(a1==replay)
  {
    a=1;
    a1=0;
  }
  if(yes11 == true && previous11  == false && b)
  {
    if(state == LOW) {
      state = HIGH;
    }
    else
      state = LOW;
    b = 0;
    b1 = 0;
    Serial.println('b');
  }
  if(yes11 == false && previous11  == false)
    b1++;
  else
    b1=0;
  if(b1==replay)
  {
    b=1;
    b1=0;
  }
  if(yes10 == true && previous10  == false && c)
  {
    if(state == LOW){
      state = HIGH;
    }
    else
      state = LOW;
    c = 0;
    c1 = 0;
    Serial.println('c');
  }
  if(yes10== false && previous10  == false)
    c1++;
  else
    c1=0;
  if(c1==replay)
  {
    c=1;
    c1=0;
  }
  if(yes9 == true && previous9  == false && d)
  {
    if(state == LOW){
      state = HIGH;
    }
    else
    state = LOW;
    d = 0;
    d1 = 0;
    Serial.println('d');
  }
  if(yes9== false && previous9  == false)
    d1++;
  else
    d1=0;
  if(d1==replay)
  {
    d=1;
    d1=0;
  }
  if(yes8 == true && previous8  == false && e)
  {
    if(state == LOW){
      state = HIGH;
    }
    else
    state = LOW;
    e = 0;
    e1 = 0;
    Serial.println('e');
  }
  if(yes8== false && previous8  == false)
    e1++;
  else
    e1=0;
  if(e1==replay)
  {
    e=1;
    e1=0;
  }
  if(yes7 == true && previous7  == false && f)
  {
    if(state == LOW){
      state = HIGH;
    }
    else
    state = LOW;
    f = 0;
    f1 = 0;
    Serial.println('f');
  }
  if(yes7== false && previous7  == false)
    f1++;
  else
    f1=0;
  if(f1==replay)
  {
    f=1;
    f1=0;
  }
  if(yes6 == true && previous6  == false && g)
  {
    if(state == LOW){
      state = HIGH;
    }
    else
    state = LOW;
    g = 0;
    g1 = 0;
    Serial.println('g');
  }
  if(yes6== false && previous6  == false)
    g1++;
  else
    g1=0;
  if(g1==replay)
  {
    g=1;
    g1=0;
  }
  if(yes5 == true && previous5  == false && h)
  {
    if(state == LOW){
      state = HIGH;
    }
    else
    state = LOW;
    h = 0;
    h1 = 0;
    Serial.println('h');
  }
  if(yes5== false && previous5  == false)
    h1++;
  else
    h1=0;
  if(h1==replay)
  {
    h=1;
    h1=0;
  }
  if(yes4 == true && previous4  == false && i)
  {
    if(state == LOW){
      state = HIGH;
    }
    else
    state = LOW;
    i = 0;
    i1 = 0;
    Serial.println('i');
  }
  if(yes4== false && previous4  == false)
    i1++;
  else
    i1=0;
  if(i1==replay)
  {
    i=1;
    i1=0;
  }
  if(yes3 == true && previous3  == false && j)
  {
    if(state == LOW){
      state = HIGH;
    }
    else
    state = LOW;
    j = 0;
    j1 = 0;
    Serial.println('j');
  }
  if(yes3== false && previous3  == false)
  j1++;
  else
  j1=0;
  if(j1==replay)
  {
    j=1;
    j1=0;
  }

  digitalWrite(led, state);
  previous12 = yes12;
  previous11 = yes11;
  previous10 = yes10;
  previous9 = yes9;
  previous8 = yes8;
  previous7 = yes7;
  previous6 = yes6;
  previous5 = yes5;
  previous4 = yes4;
  previous3 = yes3;

  delay(2);
}

Thank you in Advance. :)

Please create a minimal, complete, verifiable example and edit it into your question in place of the pages of code.

No need to apologise - I'm just trying to help you get help. It's not about the formatting (although it's good that it's properly formatted now) but about allowing people to focus on the problem. If you read the MCVE article I linked, you'll get a better understanding.

Even more reason to break it down to a minimal example ☺ The exercise will help you understand it☺

The diagram looks wrong. Why are there two 10Mohm resistors?

@gerben It was an error with my fritzing app. All the resistors have a value of 10Mohm not just two

About your actual question
You have to realize that you are trying to measure tiny
capacitances, which is not completely trivial. Detecting your finger
“from at least a few inches away” is probably impossible with this
setup, as we are talking about fractions of a picofarad.
There are a few things you can do to increase the sensitivity though:

make sure both you and the Arduino are properly grounded
make the pads as big as practically possible
increase the series resistance
lower the detection threshold (your total constant) until you are at
the verge of seeing spurious detections.

About your Arduino code
This is not directly related to your question, but it addresses the
criticism you received for posting too large a program.
Looking at your code, it appears to be quite simple. It is too big only
because almost every statement is repeated ten times (once per piano
key). The simple thing you could have done is to remove all but one (or
maybe two) keys. This would have made the program easily digestible for
anyone trying to help you. What I strongly recommend is that you learn
about using loops and arrays in C++. This will allow you to avoid
repetition by instead looping through the arrays. Here is for example
how you could rewrite your setup() function based on an array of
sensors:
const size_t SENSOR_COUNT = 10;

CapacitiveSensor sensors[SENSOR_COUNT] = {
    CapacitiveSensor(2, 12),
    CapacitiveSensor(2, 11),
    CapacitiveSensor(2, 10),
    CapacitiveSensor(2, 9),
    CapacitiveSensor(2, 8),
    CapacitiveSensor(2, 7),
    CapacitiveSensor(2, 6),
    CapacitiveSensor(2, 5),
    CapacitiveSensor(2, 4),
    CapacitiveSensor(2, 3)
};

void setup()
{
    for (size_t i = 0; i < SENSOR_COUNT; i++)
        sensors[i].set_CS_AutocaL_Millis(-1);
    pinMode(LED_BUILTIN, OUTPUT);
    Serial.begin(115200);
}

As you can see here, the sensor initialization
(set_CS_AutocaL_Millis()) is only written once, and the Arduino is
instructed by the for loop to repeat the same thing on every sensor,
one after the other. If you then do the same for loop(), you will end
up with a program that is almost ten times shorter, and a whole lot
easier to read, modify and debug. For that, you would need to also
replace your yesXX, previousXX, a, a1, b, b1, c, c1...
variables with arrays.
At this point you have a collection of arrays. The next level in
modularization is to replace the collection of arrays by an array of
collections: you put all the data relevant to one piano key inside an
object, and then you have just one array of such objects.
I tried rewriting your program with this approach, and I am posting the
result here. Beware that I did not test it. I realize this may be a
little bit above your current level, but I hope it will at least give
you an idea of how the language allows you to abstract things: the whole
logic about detecting whether a key was hit lives in the
PianoKey::hit() method, and then the loop() becomes short and
simple.
#include <CapacitiveSensor.h>

class PianoKey : private CapacitiveSensor
{
    public:
        PianoKey(byte sendPin, byte receivePin, char _note)
            : CapacitiveSensor(sendPin, receivePin), note(_note),
              last_state(false), last_toggle(0)
            { set_CS_AutocaL_Millis(-1); }
        bool hit();
        char note;
    private:
        static const byte SAMPLES = 1;     // number of samples to average
        static const long THRESHOLD = 30;  // detection threshold
        static const short DEBOUNCE = 50;  // debounce time (ms)
        bool last_state;
        uint32_t last_toggle;
};

// Returns true once per hit on the key.
bool PianoKey::hit()
{
    uint32_t now = millis();
    if (now - last_toggle < DEBOUNCE)
        return false;
    bool state = capacitiveSensor(SAMPLES) > THRESHOLD;
    bool was_hit = state && !last_state;
    if (state != last_state) {
        last_state = state;
        last_toggle = now;
    }
    return was_hit;
}

const size_t KEY_COUNT = 10;

PianoKey keys[KEY_COUNT] = {
    PianoKey(2, 12, 'a'),
    PianoKey(2, 11, 'b'),
    PianoKey(2, 10, 'c'),
    PianoKey(2,  9, 'd'),
    PianoKey(2,  8, 'e'),
    PianoKey(2,  7, 'f'),
    PianoKey(2,  6, 'g'),
    PianoKey(2,  5, 'h'),
    PianoKey(2,  4, 'i'),
    PianoKey(2,  3, 'j'),
};

void setup()
{
    pinMode(LED_BUILTIN, OUTPUT);
    Serial.begin(115200);
}

void loop()
{
    static int led_state = HIGH;
    for (size_t i = 0; i < KEY_COUNT; i++) {
        if (keys[i].hit()) {
            led_state = !led_state;  // toggle LED
            Serial.println(keys[i].note);
        }
    }
    digitalWrite(LED_BUILTIN, led_state);
}

A couple of final notes:

The line class PianoKey : private CapacitiveSensor says a piano key
is a capacitive sensor with some extra functionality. Another valid
option would be to say that the key has a sensor, i.e. to store a
CapacitiveSensor inside the object.
I do not know whether it's safe to call set_CS_AutocaL_Millis()
before the low-level initialization of the Arduino. That's why it's
done in a begin() method to be called by setup(). I checked
the source code of the CapacitiveSensor library, and it appears that
set_CS_AutocaL_Millis() does nothing but set a private member of the
object. This means it is safe to call it from a global constructor,
before the hardware initialization of the Arduino.
Had this not been the case, one would need to defer this call until
setup(), as done in a previous version of this
answer.
The PianoKey::hit() method uses time-based rather than
loop-count-based debouncing. This should be more consistent if you
change the program in a manner that changes the time it takes to loop.
It does pure debouncing: you may want to change that to an algorithm
that combines debouncing with deglitching.

Cap sensing is quite sensitive to the sense pad design. Generally you want thee pad to sufficiently big. I haven't seen a single wire design as you are using here.
I would play with one wire first and adjust your code to make it work before taking on more pads.


text:
A coding problem or improper interrupt usage?
As I should expect(?), the PIR on pin#2 should trigger the trigsensor state at any time the board is running. However, I may get one trigger then nothing else. I have a GSM shield on top of a UNO. I know that I still have some tweaking to do, but I'm trying to solve one issue at a time. Thanks for any insight. The other functions seem to perform correctly. When I enter an incorrect code, the alarms operates properly. When the interrupt is triggered, the alarm response should be the same.
///////////////////////// initialize & includes //////////////////////////
#include "SIM900.h"
#include "sms.h"
#include "Keypad.h"
#include <GSM.h>
SMSGSM sms;

boolean started = true;
int PIR_SensorPin = 2;
int Alarm_OutPin = 11; //green
int Light_OutPin = 12; //red
int alarm_count;
boolean volatile trigsensor = false;
const byte interruptPin = 2;
int z = 0;
int i = 0;

//////////////////////////// setup keyPad //////////////////////////
const byte ROWS = 4; // four rows
const byte COLS = 4; // four columns
char keys[ROWS][COLS] =
{
  {
    '1', '2', '3', 'A'
  }
  ,
  {
    '4', '5', '6', 'B'
  }
  ,
  {
    '7', '8', '9', 'C'
  }
  ,
  {
    '*', '0', '#', 'D'
  }
};
byte rowPins[ROWS] = {
  6, 7, A2, A3 // row pin# on keypad to Arduino pin#, ie Row Pin #1 goes to Arduino Pin #6, etc.
}; // connect to the row pinouts of the keypad
byte colPins[COLS] = {
  3, A0, A1, A4
}; // connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS );
const char PIN[5] = {
  '9', '6', '7', '9', '#'
}; // PIN number
char key_input[5] = {
  0, 0, 0, 0, 0
}; // used for comparison

//////////////////////////////// setup ///////////////////////////////////
void setup() {
  Serial.begin (9600);  // Establish Serial connection.
  pinMode (Alarm_OutPin, OUTPUT);   // Set pinMode.
  pinMode (Light_OutPin, OUTPUT);   // Set pinMode.
  pinMode (PIR_SensorPin, INPUT);   // Set pinMode.
  digitalWrite (Alarm_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (Light_OutPin, LOW); // Set output pins to LOW for start.
  digitalWrite (PIR_SensorPin, LOW);
  Serial.println ("GSM Shield testing."); // Serial message that GSM shield is starting up
  if (gsm.begin(4800)) {    // Set GSM shield to recommended 4800 baud rate.
    Serial.println ("Status = READY");
    digitalWrite (Alarm_OutPin, HIGH);
    // PIR as interrupt
    attachInterrupt (digitalPinToInterrupt (2), trigger, RISING);
    //attachInterrupt ((0), trigger, RISING);
  }
  //  started = false; //////////////////////////////////////////////////////////////
  Serial.println ("System Ready, at the keypad loop!");
}

//////////////////////////////// void loop ///////////////////////////////////
void loop() {
  readKeypad();
}

////////////////////////////// void trigger ///////////////////////////////////
void trigger() {
  trigsensor = true;
  started = true;
}

//////////////////////////////// void alarm ///////////////////////////////////
void alarm() {
  Serial.println (started); Serial.println (trigsensor);
  //  digitalWrite (trigsensor, LOW);
  Serial.println("at Alarm");
  // while ((timedelay - time) > 0); Serial.println (time);  time++;
  if ((started == true) && (trigsensor == true)) {
    // (sms.SendSMS("**********", "***Motion Detected in Studio!***"));
    Serial.println ("MOTION detected: SMS Sent");
    for (alarm_count = 0; alarm_count < 5; alarm_count++) { // Cycle outputs if triggered
      digitalWrite (Alarm_OutPin, HIGH); delay (2000); // On/Off/On/Off/Off
      digitalWrite (Alarm_OutPin, LOW);
      digitalWrite (Light_OutPin, HIGH); delay (2000);
      digitalWrite (Light_OutPin, LOW); // End by turning off light
    }
    digitalWrite (Alarm_OutPin, HIGH);
  }
  else { }
  readKeypad();
}

//////////////////////////////// read Keypad ///////////////////////////////////
void readKeypad() {
  char key = keypad.getKey();
  if (key != NO_KEY) { // if a keypad input
    key_input[z] = key;
    Serial.print("Key_input["); Serial.print(z); Serial.print("] = "); Serial.println(key);
    z++;
    if (z >= sizeof(key_input)) {
      z = 0;
    }
    switch (key) {
      case '*': // resets key_inputs to "0"
        z = 0;
        break;
      case '#': // pressed to "enter"
        z = 0;
        for ( i = 0;   i < 4 ;  i++ ) {
          Serial.print(key_input[i]);
        }
        Serial.println ("-------");
        delay(100); // for extra de-bounce
        checkPIN();
        break;
    }
  }
}

//////////////////////////////// check PIN ///////////////////////////////////
void checkPIN() {
  Serial.println ("@ checkPIN ");
  int correct = 0;
  int i;
  for ( i = 0;   i < (sizeof(PIN) - 1) ;  i++ ) {
    if (key_input[i] == PIN[i]) {
      correct++;
    }
  }
  if (correct >= sizeof(PIN) - 1) {
    Serial.print ("# correct = "); Serial.println (correct); Serial.println (sizeof(PIN) - 1);
    correctPIN();
  }
  else {
    incorrectPIN();
  }
}

//////////////////////////////// correct PIN ///////////////////////////////////
void correctPIN() {              // do this if correct PIN entered
  Serial.println ("@ correct PIN ");
  started = false;
  digitalWrite (Alarm_OutPin, HIGH);
  readKeypad();
}

///////////////////////////// incorrect PIN ///////////////////////////////////
void incorrectPIN() {           // do this if incorrect PIN entered
  Serial.println ("@ incorrect PIN ");
  started = true;
  // add time delay before alarm, via keypad??
  alarm();
}

None of the code you posted ever sets trigsensor to false, besides the initial value.

Thanks, you are right. But I'm not sure where it should be placed, and why??

You are correctly doing little in the ISR: set a flag telling the main program to handle something. You should unset that flag when you are done doing handling the something you needed to handle.  Guessing from your code: in the alarm() function.

It seems as if the interrupt on pin 2 is not triggering the function. Not sure what is wrong.

I did make the change in the alarm function, but still not getting the interrupt to trigger.
}
trigsensor = false;
readKeypad();
}

What does the signal on the interrupt pin look like? You initialize it to trigger on a rising edge -- is that what is happening with the actual signal?

I have actually tried RISING and CHANGE, with no difference. The PIR is the sensor, and it is working OK. I don't have a scope to see the signal, but it reads 5vdc on a meter. And I can get the a Serial.print to show that it is "true". The problem that I am having, referring to the original sketch posted, is that the trigger is not being seen by the "alarm" function. I am still playing around with it and may find the problem. Thanks.

You never call the alarm() function in your code. Your loop() is only calling readKeypad() and readKeypad() never looks at trigsensor. Your ISR is only changing trigsensor and started. You need to add code in your loop() function to check trigsensor and if true, call alarm() or something.

THANKS! You nailed it! Not sure how I overlooked that, but thanks for your pair of eyes. On to debugging the rest.

Mark the question as answered so that it can be useful to others!

Maybe another problem for your eyes. I seem to get the alarm to cycle regardless of the state of trig sensor and away (they should both need to be true in order for the alarm to run after an incorrect code is entered):


text:
white screen : 2.8" TFT LCD Screen Module: HY-280TFT
i have a problem with my new  2.8" TFT LCD Screen Module HY-280TFT.i connect it with an Arduino Uno board like this way:
 Connect HY-TFT280 to Arduino UNO

LEDA -> 5V
LEDK -> GND
VCC -> 5V
RD -> 3.3V
GND -> GND
DB0->DB5 to D8->D13
DB6->A0
DB7->A1
DB10->DB17 to D0->D7
RSET->A2
CS->A3
WR->A4
RS->A5

i downloaded and installed the new UTFT library. then i tested the example : Arduino(AVR)->UTF_Demo_320x240 , but i always have a white screen.
In the code, i change
UTFT myGLCD(ITDB32WD,38,39,40,41); by UTFT myGLCD(ITDB32WD,A5,A4,A3,A2);

but i still have the white screen
please what can be the problem? thank you

Maybe the fact that the screen is an ILI9331 and not an ITDB32WD might have something to do with it. Looks like UTFT doesn't support that chip anyway. Maybe you should use the library they specifically link to on that Wiki page...?

thank you to reply me...the wiki page send me link . and there, they show us UTFT library


text:
LCD Display Issue
Hi I am a newbie I am trying to test LCD but it always show me a fading boxes It was working before .
connection
LCD p1 - gnd
Lcd p2 - VCC
Lcd p3 - potentiometer middle (10k)
lcd p4 - pin 7 microcon
lcd pin 5 - gnd
lcd pin 6 - pin8 microcon
4 vacant lcd spaces
lcd pin 11- pin9 microcon
lcd pin 12 - pin10 mocrocon
lcd pin 13- pin 11 microcon
lcd pin14- pin 12 microcon
lcd pin 15- 5v
lcd pin 16- gnd

Try pressing down on the metal surrounding the display, and see if that changes the display. If so you'll have to reseat the display. Probably something wrong with the zebra-strip not making proper contact.

it keeps blinking and showing boxes when I pressed it thank you very kuch for your response

Your pin arrangement makes no sense. You have one pin connecting to the potentiometer, yet the potentiometer doesn't seem to be connected to anywhere else. Check your wiring against one of the many tutorials out there.

potentiometer connected to gnd and vcc


text:
Controlling 4 LED strips
I have 4 single color LED strips which I would like to control individually with one remote controller - turn them on/off an dim them. So far I only have my LED strips (They are about 3.5 meters of length combined), an 80W power supply and an Arduino Uno. I'm new to this kind of stuff. Could you help me with the setup. What parts do I need?
EDIT:
So I decided to go with an Arduino Nano. First, I'll try to power up only one strip. My question now is, how to power up the Nano. All the setups I found, have an USB cable connected to the nano to power it up. Can I connect my 12V+ to the VIN?
EDIT2:
Take a look at my setup. Is that OK?

Thanks

Are the LEDs 12 or 5V?

The LEDs are 5050 12V 60leds/m

So far your question is hard to answer because there are so many varieties of LED strip out there. Could you please provide details on what LED strip you are using (a link to a online electronics shop is ok). If you know any details on how to drive these LED strips (eg on/off, I2C, SPI etc).

Its this strip:
http://www.dx.com/p/72w-6000lm-3500k-300-5050-smd-led-warm-white-light-strip-white-yellow-5m-12v-305265#.WKWy7aptn0M
and my power supply is 12V 7A

The product page of the Arduino Nano states “Input Voltage: 7-12 V”. So, yes, you can power it with 12 V at Vin.

You will need several things.
First I assume that the power supply is a 12V power supply. If it isn't, better to get one (3.5m of leds can be 4.2A, so even a 12V 5A supply is fine). Note: you didn't specify the led size, so the current can vary a lot. But a standard one is a 60 leds/m 5050 leds, which means 60mA/5cm, or 4.2A for a 3.5m strip.
Anyway you will need a 12V power supply to power both the strips and the arduino (through the Vin pin).
You will then need a way to control the leds from the arduino. Since the required current is too high for the arduino, you will need to put a transistor. I tend to prefer nMOS over NPN, but just because of the way I learned them. Anyway just get a low-side transistor (either an nMOS or an NPN) capable of handling the required amount of current (at least a couple amperes, better if they are >5A) and the proper circuit to turn them on. Usually you will just need one or two resistors. You will need to connect the +12V to the plus terminal of the leds, the drain (or collector) of the transistor to the ground pin of the led you want to control, the source (or emitter) of the transistor to ground and the gate (or base) of the transistor to the arduino through the proper circuit.
Then the remote controller. You did not specify what kind of remote controller you want to use, but usually you can cope with a IR receiver (e.g. the TSOP382 or any other) and the proper decoding. A lot of remote controllers are already mapped in the library IRremote; you just have to read the value it provides; inside the arduino you will need to save the codes for the commands (you will have to train it first) and then simply compare.
This is a generic answer, because you did not provide any details. If, implementing this, you encounter any problem open a specific question with what you did up to that point.

authors: شعبان بِن صلاح


text:
Insert Variables In AT commandes
I'am trying to apply USSD operation with variable codes, for example this piece of code return my account balance:
             gsm.SimpleWriteln("AT+CUSD=1,\"*100#\"");

i want to change "*100#" to variable so gsm.SimpleWrite uses what the variable contains. I want to find how to make it work like this:
             gsm.SimpleWriteln("AT+CUSD=1,\"Variable\"");

EDIT: here is my code to give you a better view. it return balance in serial monitor.
#include "SIM900.h"

  void setup()
    {
   Serial.begin(9600);
    Serial.println("GSM Shield testing.");
       if (gsm.begin(9600))
            Serial.println("\nstatus=READY");
      else Serial.println("\nstatus=IDLE");

         gsm.SimpleWriteln("AT+CUSD=1,\"*100#\"");
      delay(10000);
             char msg[200];
             gsm.read(msg, 200);
            Serial.print("resp: ");
            Serial.println(msg);
 }
    void loop()
     {

    }

What kind of variable? And what library has the SimpleWriteln method?

im using SIM900.h. for example var1 = *100# and var2 = *122# i want to applied it like that.

gsm.SimpleWriteln is different from serial.print in many ways, including syntax.

I cannot find which "SIM900.h" library you are using - none of the ones I found have "SimpleWriteln" in them, so this is pure assumption about what functions and overloads may be available.
Just split your string into chunks, like you would with any serial device:
gsm.SimpleWrite("AT+CUSD=1,\"");
gsm.SimpleWrite(command);
gsm.SimpleWriteln("\"");

Where command is a suitable container for your data - say const char *.

check the post i added the code, and i tried what u said, it returns error. Sim900.h lib located at: Arduino\libraries\SIM908IDE100. i think its with th  default libs.

You must have installed that library. That means you must have downloaded it from somewhere. That means you must surely know where you downloaded it from. Unless you can tell us that we can't help you further.

I think I have found a copy online, though I can't be sure. It looks like the library hasn't been well written - it doesn't support the F() macro (which is kind of stupid really). I shall remove those from my code example.

any other suggestions to make a USSD operation?

Does my example not do what you want?

it returns Error. which means wrong syntax in AT manuel

Did you mistakenly use SimpleWriteln instead of SimpleWrite ?

it worked! thank you. i just define command as char* , like this.  char *command

authors: Дмитро Жигалкін


text:
Battery level indicator
In this arduino project we have 3 Leds that lights up according to the voltage of a battery but when we the voltage read is very close, it results into an uncontrolled switching between  Leds  can any one help me ?
int Batpin = A0;
int Led1  = 12;
int Led2  = 11;
int Led3 = 10;

void setup() {
  // put your setup code here, to run once:
  Serial.begin (9600);
  pinMode(Led1,OUTPUT);
  pinMode(Led2,OUTPUT);
  pinMode(Led3,OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  volt ();
}

void volt(){
int sensorVal = analogRead(Batpin);
float voltage = sensorVal * (5.0/1023.0);

 Serial.print(" volt: ");
 Serial.println(voltage);
 if (voltage < 3.80){
     digitalWrite(Led1,HIGH);
  }

   if (voltage > 3.80 && voltage <= 4)
   {
      digitalWrite(Led1,LOW);
      digitalWrite(Led2,HIGH);
   }

   if (voltage > 4)
   {
      digitalWrite(Led1,LOW);
      digitalWrite(Led2,LOW);
      digitalWrite(Led3,HIGH);
   }
   delay (1000);
}

This is an interesting project.  But why stop at adding hysteresis?  After all, you have the flexibility of a micro processor.  Start thinking "out of the box" and make a more useful tool.  What about the battery's internal resistance, its elasticity and how that effects its performance?

You can reduce this effect a bit by using the average of multiple reads. This will give you a more stable value and less hysteresis. You could for example use a rolling average. To absolutely eliminate this proble use majenko's solution.

What you could do with for this is hysteresis.
Instead of simple threshold ranges (0 < A < B < C < 5) you instead need to watch the voltage over time and decide what it is doing compared with what it has done in the past.
You need to keep a record of what state the voltage is in at any one time - That is, is it in band A, B or C in the thresholds above. You then need a second set of thresholds, A1, B1 and C1.
The two thresholds overlap:

If, for example, the voltage rises from between A and B to between B1 and C1 then you switch states to the BC state.
If it falls from between B1 and C1 to between A and B then you switch to the AB state.
Basically, if the voltage rises, it needs to transition between the lower set of thresholds to the upper set of thresholds to register as a change. If it drops it has to transition between the upper set of thresholds and the lower set of thresholds to register as a change.
So, in pseudocode,
if (State == 0A && Voltage > A1 && Voltage < B1)
    State = AB
    Turn on LED 1

if (State == AB && Voltage > B1 && Voltage < C1)
    State = BC
    Turn on LED 2

if (State == BC && Voltage > C1)
    State = C5
    Turn on LED 3

if (State == BC && Voltage < B && Voltage > A)
    State = AB
    Turn on LED 2

if (State == AB && Voltage < A)
    State = 0A
    Turn on LED 1

if (State == C5 && Voltage < C && Voltage > B)
    State = BC
    Turn off all LEDs

It's up to you to decide what a good level of separation is suitable for your system.


text:
Simple example multiplexer usage
I'm new at multiplexing with arduino (I use arduino from some years), and -as title says- I'd like to learn. I'm trying to build an expandible system with 3 sensors, and I'd like to use a 74hc595b1 to link them, leaving some pins free. My first question is: is It possible? And second, can you kindly link me a simple -but very simple- example about multiplexers in arduino? Thankyou!

What kind of sensors? Also, the 74hc595b1 is a shift register, not a multiplexer.

I have a hc-sr04 sensor and a temperature sensor (I think a P-MOS)

Neither of those are suitable for using with a shift register

So, how can I do with more sensors?

Get a board with more pins, or use two boards and make them communicate with each other.

And so -and sorry for the many questions- i can use a multiplexer just for output? i.e. a 7segments display?

You can use a shift register for that, yes. A multiplexer is a very different thing and is not what you have there.

i just bought an 8-IO adding PCF8574T for less than $1.50USD, look into it. If you want good analog IO, a 16-bit ADS1115 adds 4 hi-res input for about $2.50....

There's a detailed explanation of multiplexer use in this answer.

For connecting 8 analog devices to an Arduino, using only 3 Arduino pins, look at say a 4051 multiplexer IC: 4051 example


text:
How compact, small and smart a fluid detector need to be communicate with external systems?
I like to build a fluid(liquid) level detector using Arduino that can send 2 types of information:

Status of the Fluid Container (Empty,Full or Below Required Level)
Location of Fluid Container

Now I like to know how small and compact such a fluid detector can be so that it can be placed in vessels, containers, tanks, etc. without causing any contamination to the fluid.
In addition, how can I interface this fluid detector with external systems like a smartphone app or cloud based app, etc.
What Arduino would i be using for the said purpose and why?

Size is inversely proportional to budget.

@Majenko Right... can you further elaborate with examples. Nowadays, there are so many ICs and compact nano-sized gadgets that are used even in human bodies as well. I agree what you said. But what feasibility is there for common commercial use? Thanks

The question you should be asking is not "how small can it be?" but "how small does it need to be?"

If you want small, you wouldn't use an Arduino, especially not an Uno.  You might use a QFN ATmega, but you'd be better off using an MCU integrated with your chosen radio transceiver.  Also, size has little to do with contamination, beyond the degree to which an admitted issue is a problem; you really should be looking for something made or encased in suitable materials.

Your question should be broken into a minimum of two parts.
The first, regarding the sensor, can be addressed with at least one specific product, although there may be others of this nature. It is a teflon coated pressure sensitive strip placed into the holding container or tank. Teflon is a non-reactive plastic and will not contaminate the substance in the tank, unless you are measuring extraordinarily reactive chemical liquids. One example is
Chemical eTape which is available in lengths from 130mm to 800mm.

This particular product is offered in three different interface types, all of which are acceptable to a properly configured Arduino.
The second portion of your question regarding the smartphone and type of Arduino is going to depend on how you plan to use the data you'll collect with the sensor. This aspect of the question is also extremely broad, as there are many solutions, including Blynk, SMS, WiFi and others.
You will want to "start small," and create a local Arduino-only interface, to ensure that you can properly code the sensor to present the results you require.
Once you have the data, you would then explore the many options available for distribution and dissemination.

Wonderful... I appreciate for the valuable detail you have added in your reply here. Now can you tell me what options would I use if I like to transfer the data (liquid level) to remote locations? As you mentioned about Bylink, SMS, WiFi, etc. What option would I go for if the liquid container is in New York and I am in Chicago? Moreover, the Chemical eTape does not detect the location (long. lat.) of the liquid container. How would I be able to detect the location of a certain liquid container, vessel or tank? Thanks

It would be more practical to consider to break off this question into other independent posts regarding both the communications and location aspects of your project. Prior to making a new set of posts, I would suggest to search here and the internet for "GPS Arduino" and "Arduino data over internet." Too many results to list in one comment, or even one answer. Please also check my answer if you feel it qualifies.


text:
Understanding writing to input pins and pull up resistors
I am new to Arduino, and am trying to understand the following code.  The question is: Is my understanding correct, or if not, what is happening here?
I have to reverse engineer an existing undocumented project, based on Marlin firmware for 3D Printers.  The relevant lines from the source are:
#define DIO87_PIN               PINE2
#define DIO87_RPORT             PINE
#define DIO87_WPORT             PORTE
#define DIO87_DDR               DDRE
#define DIO87_PWM               NULL

#define MASK(PIN)  (1 << PIN)
#define _TOGGLE(IO)  do {DIO ##  IO ## _RPORT = MASK(DIO ## IO ## _PIN); } while (0)
#define TOGGLE(IO)  _TOGGLE(IO)

TOGGLE(87);

1) Reducing this code gives me:
DI087_RPORT = 1 << DI087_PIN
2) Which reduces further to:
PINE = 1 << PINE2
3) Which reduces further to:
PINE = 00000100
4) I understand this to mean that we are setting Pin 2 of the Inputs Register (of Port E) to "High". (and are setting the other 7 pins to low)
5) I understand this to mean, as we are writing to an "Input", that we are enabling the internal pull-up resistor on Port E Pin 2.
(EDIT: I have made a mistake here in point 5: to enable a pull-up resister, you write to a pins OUTPUT register, not it's INPUT register. (but you must write to it's output register when it is in "input mode")
Questions:

Is my understanding and work-through above correct?
If yes, does this also mean that we are also disabling the pull-up resistors to the other 7 Input Pins at the same time?

I am confused by the "TOGGLE" code given above - it seems that it is "destructive" in the sense that by "toggling" the input resistor on one pin, you also disable the resistors on all other pins?  Would it not make more sense to just toggle the one pin with a bitwise or.
e.g:
PINE = PINE | 1 << PINE2

Ah, now I understand a little more: IF DDRx is set so pin(x) is OUTPUT, then writing a 1 to a PINx will toggle the corresponding PORTx value. (i.e will indeed toggle the "output" of that pin)
However, IF any pins are set to INPUT in the DDR, (and have pull up-resistor enabled), then wouldn't this TOGGLE macro still inadvertently turn off those pullup resistors?

Maybe it's not completely obvious from the datasheet, but it can be seen in the figure of an I/O pin: writing a logic zero to PINxn has no effect whatsoever. Writing to a PINx register affects only those pins where you write a logic one.

Thanks. I understand that, when DDRx=1, that writing a logic zero to PINx has no effect.  Does the same hold true when DDRx=0? (input mode)?  If this also does nothing, then how does one turn off the pull-up resistor?

I believe I have a mistake in my reasoning, point (5). To enable a pull up resistor, one writes a 1 to PORTxn not PINxn.  And to disable a pull-up, one writes a 0 to PORTxn.

As noted in the I/O-Ports – Introduction section of the ATmega2560 datasheet,

... writing a logic one to a bit in the PINx Register, will result in a toggle in the corresponding bit in the Data Register.  In addition, the Pull-up Disable –  PUD bit in MCUCR disables the pull-up function for all pins in all ports when set.

Bits masked with a zero won't be affected.  You can toggle several bits at once if the byte written to the PINx register has several 1's in it.
Pullups are on for an input bit when the data bit is high and the PUD bit in  MCUCR is low.  So as suggested in your comment, pullups for toggled bits would toggle too, if PUD is low.
Regarding the macro code, your reduction looks right.  But note that use of _TOGGLE as an identifier in that code violates section 17.4.3.1.2 of the C++ Standard.  Names beginning with an underscore followed by an uppercase letter are reserved for use by language-implementation software.  They are off-limits for user code.  See What are the rules about using an underscore in a C++ identifier? for discussion.

The feature is well documented in the datasheetss.
Just be aware that it is not available on all across chips.
Atmega8 for example is a notable exception.

Now that I have improved my understanding, I provide a full answer here for completeness.

To enable (or disable) a pull up resister, you write a 1 (or 0) to
the PORTxn (data) register.
Writing a 1 to a PINxn (input)register, toggles (bitflips) whatever value is in the PORTxn data register.
Writing a 0 to PINxn does nothing, ever.
The structure of the Macro means it is hardcoded to only write to a PINxn register - it is impossible (with this code structure) to call "TOGGLE" on a PORTxn (Data) register.
Thus, this TOGGLE macro will never cause any issues, as writing zero's to PINx causes no action.

Specifically the answer is in the following two lines of code:
#define DIO87_RPORT             PINE
#define _TOGGLE(IO)  do {DIO ##  IO ## _RPORT = MASK(DIO ## IO ## _PIN); } while (0)

(TOGGLE is hardcoded to use "DIO_XX_RPORT" which is PINx)


text:
Servo motor with 9V battery
I'm using servo motor in my Arduino based project, I've tried to provide servo with external power supply, So I've used 9v battery with IC7805 to step down to 5v,  but the motor is not working, so what should I do? FYI: I used the same battery with IC7805 to power IR proximity sensor which works fine.

A 9v "transistor" battery is unsuited to powering servos - at best it might work very briefly.
Use 4 alkaline (or depending on the servo ratings, perhaps 5 rechargeable) AA or AAA cells to power the servo.
Either power your Arduino from something else, or get a 3.3V version that you can operate from a low dropout regulator on the 4 or 5 cell pack.
A 7805 has a high dropout voltage and is out of place in a battery powered system.

What do you use instead of 7805 when power is needed ? Do you have a link ?


text:
ESP01 flashing error
I am trying to program an ESP8266-01 WiFi module using an Arduino Uno as a USB to TTL programmer.
I have removed the ATmega and grounded the RESET pin (quite useless without the uC though).
Then, using esptool.py I tried to upload a Bare minimum sketch with the Arduino IDE and later using the following:
python esptool.py -b 57600 -p /dev/cu.usbport write_flash 0x000000 "nodemcu.bin"

However, both ways give me the same output:
A fatal error occurred: Failed to connect to ESP8266: Invalid head of packet ('\x08')

I have tried sending AT commands to the ESP01 like "AT" or "AT+GMR" and everything works fine, but I cannot upload any sketch because of that error.
I also followed esp8266 official forum advice to edit the Python script according to the following, but without success.
Line 43 ESP RAM BLOCK = 0x1800 //change this to 180
Line 44 ESP RAM BLOCK = 0x400 //change this to 40

The level conversion from 5v TTL to 3.3v is done through simple resistor node (2k and 1k), while RST is kept at Vcc through 10k pull-up resistor and a push button to ground it.

Are you sure 57600 is the correct baud rate? Wasn't it 115200?

I have tried both, nothing changes

Your wiring sounds wrong.
Tie CHPD to Vcc (3.3v) to enable the device.
Tie GPIO0 to ground as you power up, to put it into programming mode.
RST can be left floating, or PULL (not tie!) up to Vcc through a resistor, say 10k.
That diode level shifter arrangement is unusual. A potential divider on the ESP's RxD is all you need - say 1k and 2k.

I tried and I still get the same error

Could you post a circuit diagram of what you tried, please?

Sure, check it out now

According to your new schematic, RST is tied to GND. Is that just a mistake in the drawing?

Yes it was a mistake, RST goes to Vcc through a 10k resistor as you suggested and to GND via push button

An addition to Mark's answer, from Uploading sketch to ESP8266

Before download, pull both GPIO0 and RST to ground. Release the pull
  down on RST, but keep GPIO0 low. When the IDE has finished uploading,
  release GPIO0 from low.


text:
Can I safely power my UNO and DC motors with the 5v1A and 5v2.1A ports on a USB charger?
I have USB charger battery pack with two output ports (Fremo C510).  One is marked as 5 volts 1 amp, and the other as 5 volts 2 amps.
I'm building a toy robot and would like to run the UNO off of one of those ports, and the motors off of the other.
Can I safely do that?  I have two main concerns:

Can I safely power the arduino with that current?
If I power both the motors and the arduino from that source (two usb ports connected to the same battery), will I still have to worry about spikes from switching the motors on and off?  I don't know how those ports are wired to the actual battery inside.

I don't know how those ports are wired to the actual battery inside. -- Neither do we.

You can power the Arduino from either side, since it will only draw what it needs, and most arduinos are powered from a .5 amp USB port. But you'll want to reserve the higher current side for the motors.
Make sure your motors' total draw (including starting current) doesn't exceed the 2 amps available.
Unless you can find out for sure that the two power ports are isolated from one another, you're better off to assume they are not and provide motor spike damping yourself.

Sometimes the small-print in these chargers says that they can supply a max of 2.1A in total - you might want to  check that.

Even if that is the case with this charger, the Arduino very likely won't draw even half an amp, leaving well over 1 amp out of the of the total for the motors. They would require the 2 amp port to take full advantage of it. In that case the motors will have to use less than the full capacity by however much the Arduino needs to function.


text:
Problem sending data from arduino with ESP8266 to a local mysql database
i'm currently trying to send a randomly generated number from Arduino via ESP8266 wifi module to a local mysql database estabilished with xampp, but having a problem with it. Here is my arduino and php receiving code. I should mention that i'm extremely unfamiliar with mysql, php, and the whole server & database things, so any help would be greatly appreciated.
Arduino Code:
#include <ESP8266WiFi.h>

const char* server = "192.168.1.106";
const char* ssid = "DARUSALAM C8";
const char* password = "asro4520";
const char* SensorID = "ESP001";

WiFiClient client;

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

  pinMode(BUILTIN_LED, OUTPUT);
  digitalWrite(BUILTIN_LED, HIGH);

  WiFi.begin(ssid, password);
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.print(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi Connected");
}

void loop() {
float n = random(300);

Serial.print("Random Number: ");
Serial.println(n);

  if (client.connect(server,80)) {
    Serial.print("Posting data...");
    digitalWrite(BUILTIN_LED, LOW);
    Serial.println("Random Number: " + String(n));
    client.println("GET /log.php?n=" + String(n));
    client.println("HOST: ");
    client.println(server);
    client.println("Connection: close");
    client.println();

    client.stop();
    Serial.println();

    digitalWrite(BUILTIN_LED, HIGH);
  }

  delay(5000);
}

PHP code:
<?php

$db_amb = mysqli_connect("127.0.0.1", "root", "", "wemos");
if (!$db_amb) die("Gagal terkoneksi ke DB Utama. Error : " . mysqli_connect_error());

$n = $_REQUEST['n'];
if (!empty($n) &&)
{
  $s = "insert into data_random set value1='$n'";
  $r = mysqli_query($db_amb, $s);
  echo "OK";
}
else echo "ERR";
?>;

The database is named 'wemos', and the table where i intend to store the data is named 'data_random' with 4 columns named value1-value4. My intentions is to store the random number to the 'value1' field.
EDIT the problem i encountered is whenever i checked http://localhost/log.php this appears:
Parse error: syntax error, unexpected ';' in C:\xampp\htdocs\log.php on line 7

i have tried modifying the syntax in numerous ways but the problem presist. I suspect my code may have some underlying fundamental problem that is not syntax related, but i can't tell due to my lack of experience. Again, any help/clue is greatly appreciated. Thank you very much

What sort of a problem? (Please edit the answer into the question.)

The HOST should not have a newline after it, so you should have
client.print("HOST: ");
client.println(server);

In addition your PHP looks dodgy to me.  I'm not very familiar with PHP at all, but I think the &s here are left over from something you have removed, and causing syntax errors - just remove them
if (!empty($n) &&)

I believe your n parameter is going to be in _GET (not _REQUEST).  Also, you should check whether it's there, not just assume it is, so:
if isset ( $_GET["n"] )
{
    $n = $_GET["n"];
    // Do your database stuff here
}

(You should find the PHP log (where depends on what OS your server is running on) and I think it would point you straight to this problem.  No point trying to debug it blind.)

First of all thank you for cleaning up my mess. Due to your suggestion i have removed the newline after  HOST. Yes, i also suspect that the &s is what causing the syntax error because you are also correct in that i only edited someone else's program i found from browsing the internet. but now when i checked the local host i got Notice: Undefined index: n in C:\xampp\htdocs\log.php on line 6 ERR;. I installed xampp in windows 10, can you point out the PHP log location? thank you very much

I don't understand what you mean by "checked the local host". I don't know the location of the PHP log in Windows, sorry, but I think I've seen another the mistake in your code - answer ammended.

The $_REQUEST super global should work just fine. It contains the contents _GET, _POST, and _COOKIE. http://php.net/manual/en/reserved.variables.request.php.

You will get the index not defined error if you load the page in your browsers with out the "?n=" part. So to test the script in your browser use: http://localhost/log.php?n=123

Change this:
client.println("GET /log.php?n=" + String(n));
client.println("HOST: ");
client.println(server);

To this:
client.print("GET /log.php?n=" + String(n));
client.println( " HTTP/1.0" );
client.print("Host: ");
client.println(server);

This means you're sending the Host: header + value on one line, and you're correctly appending the HTTP/1.0\n after your URL-request.


text:
I2C Arduino ESP8266 Bad Reading
I have a NodeMCU, which I program with the Arduino IDE. I have connected a VOC sensor to pins D1, D2, which are the SLC/SDA pins for NodeMCU. They have pull-up resistor at 4,3kohm to 3.3V.
First I used I2C scanner code, provided by Arduino, and got a response that I have the sensor connected at address 0x70, which is the correct address, indicated on the datasheet for the sensor.
After I tried to read values from the sensor with command 0b00001001 (provided in the datasheet also), I only get 0s as output! Probably something weird in the coding, perhaps someone could assist me in what I am doing wrong here?
In the code, I request 100 bytes just to make sure to get everything, but I receive only 32 back. The datasheet says it should be 6 bytes on address 0x9. And I have tried hex and dec form but that doesn't work. Binary is the proper way I assume.
My Output:
Start
Bytes Available: 32
Data read: 00000000000000000000000000000000

Code:
#include <Wire.h>

int miscadr = 0b1110000;

void setup() {
  Serial.begin(115200);
  Wire.begin();
  delay(100);
}

void loop() {
  Serial.println();
  Serial.print("Start");
  Serial.println();
  Wire.beginTransmission(miscadr); //Start bit
  Wire.write(0b00001001); //Asking for registry 9
  Wire.endTransmission();
  Wire.requestFrom(miscadr, 100);
  Serial.print("Bytes Available: ");
  while(Wire.available()==0);
  Serial.print(Wire.available());
  Serial.println();
  Serial.print("Data read: ");
  while(Wire.available()!=0) {
    Serial.print(Wire.read());
  }
  Serial.println();
  delay(2000);
}

I'm not familiar with NodeMCU, but normally, you'll need to send I2C addr with r/w bit, so something like 0b00010010 or 0b00010011 (for read or write). You should print any statuses available (no ACK from slave etc.) to help you debug.

Thank you domen for the reply. You are correct about that, I read the datasheet once again. The last bit sent in 0b0000100_1_ is there for stating it is a read command. So what I said about this being 0x9 isnt correct, but the command sent is according to what the datasheet says.
Let me know if you have other suggestions, appreciated!

Have you got an oscilloscope/logic analyser/voltmeter? It would be good to have some idea what's happening on clock and data lines. Also have you got a very simple I2C device just to see your HW setup is fine? Temperature sensors are usually simple and work with no config. (Although the sensor you're using looks simple as well)

I just ordered an oscilloscope! Seems as if it can be useful.. Anyhow, I tried a Bosch Pressure Sensor, BP280, and it gave me perfect readings. So HW seems to be correct.

"I request 100 bytes just to make sure to get everything, but I receive only 32 back". Wire buffer is 32 bytes long. Wire.available() > 0 doesn't means you have 100 bytes to read; you have to read-accumulate bytes until you read all 100.

Check your sensor is operating and responding OK,some basic code here for an UNO,a little simpler than HGrabas Library. https://github.com/AmphenolAdvancedSensors/Telaire/tree/VOC-Sensor-VX89-TE

If your ESP8266 device NodeMCU is not using the Arduino ESP8266 Library standard pins for I2C ( SDA=2, SCL=14) then you must change the Wire.begin() statement to Wire.begin(SDA, SCL) inserting your values for the SDA and SCL pins. See this note for another ESP breakout (Sparkfun) Arduino ESP8266 Wire

Thank you for the reply! It didnt do any difference though. I did get a respons from the sensor on what adress it is on, and other sensors works good. So the pin output should be properly configured for the i2c.
Let me know if you have other suggestions! Thank you.

Which VOC sensor is it ? I like to see the datasheet myself. My crystal ball tells me it is a MiCS-VZ-86/89. When the i2c scanner finds address 0x7, then you should use 0x7. In your sketch the miscadr is now 0x70.
The read and write bit is taken care of by the Wire library. You could print the return value of Wire.endTransmission and Wire.requestFrom. The Wire.endTransmission  returns an error and the Wire.requestFrom returns the number of read bytes. Those return values can tell if the I2C transaction was wrong.
There is no need for a while-loop to wait for data after the Wire.requestFrom. You can remove that first while statement.
You can not request 100 bytes. The Wire library has a buffer of 32 bytes.
When you use the term "address", please use "i2c address" or "register address".
The Wire.requestFrom reads bytes from the Slave (the VOC sensor), but the sensor can not stop the I2C transaction after 6 bytes. The Master (the ESP8266) should set the number of bytes to read. If you need only 6 bytes, then you should read only 6 bytes.

Thank you very much for the reply! The i2c adress of the MiCS-VZ-89TE(great crystal ball you have btw!) is 0x70, not 0x7 as I wrote. So the code was right on that part.
Serial.print for endTransmission returns 0, and for requestFrom returns 7.
Still, all I get is a bunch of 0s in return from the sensor! Cannot figure out the reason for this. I have changed the pullup resistors to 4.7kohm also, without any difference.. Any more suggestions what I can try? Thank you!

Zero errors from Wire.endTransmission means you are communicating with the sensor. Request 6 bytes and see what happens.

I only receive 0s, 32bytes or 6bytes requested.. Scratching my head here!

On this page http://www.sgxsensortech.com/sensor-selector/#prod_4569 under the tab "Application notes" I selected the I2C application note. It says that you need to send 6 bytes, and you will receive 7 bytes. Older versions of that sensor require only the command 0x09, but according to the datasheets the MiCS-VZ-89TE always requires those 6 bytes. The Upgrade Guide appliction note shows a short CRC calculation function.

@Martik I am late to the party and you might have fixed your issue by now. If it helps I wrote a lib for the  MiCS-VZ-89TE, I have it working on the EPS8266-01  https://github.com/HGrabas/MICS-VZ-89TE


text:
Is my arduino board broken?
Last night I had my arduino connected to pc and mc connected to 9 volts in the same time then today I tried to connect my arduino to pc and i removed any connection i just wanted to display a string it i used this code
 void setup() {
  Serial.begin(9600) ;
  }

   void loop() {

    Serial.print("NO FORMAT");
     }

its not showing anything in serial montor I tried to blink led no output still
And  i have another arduino i used the same code it showing the message in serial monitor is my previous board broken ? thank you for help when i tried to click the reset button in arduino the orang led built in is not blinking

I assume that PWR LED is turned on?
If on USB connection PWR LED is off and on 9V connection it turns on you should check fuse. It is on the right side of USB connector and is protection only from USB voltage source.
If it works you should check level of voltages or try connect usbasp and then using avrdude check if it is connecting normally.
Few ideas for voltage levels:

Voltage on "main" ATMega328 (You can check it through ISP header)
Voltage on Arduino's chip which is ATmega16, or CH340 if you have chinese one (or something like that). It should be the same as on main Arduino, but to be sure...
Voltage on reset

You need around 5 volts to be sure that it works properly because of construction of arduino's board.
If you still have no answers, no voltages you should check Arduino's schematic for more information: https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf
If there is electrically everything all right and you did not check with usbasp (or other AVR-compatible programmer) I believe that next step is to check bootloader on your board.


text:
esp8266-12e Nodemcu 1.0 board not starting uploaded data sketch from Arduino IDE
I've uploaded a sketch from the Arduino IDE to my (Amica) esp8266-12e board with the sketch data upload tool (ESP8266FS). This goes without any errors or problems. However, the code is never executed, it's like that the code isn't even on the board, it does nothing. I've tried flashing the firmware several times but this does not help. Depending on the installed firmware I get different messages on the serial monitor such as
NodeMCU 0.9.5 build 20150318  powered by Lua 5.1.4
lua: cannot open init.lua

or
Ai-Thinker Technology Co.,Ltd.
invalid

So installing different kinds of firmware is not the problem here. What did I do wrong which causes the board to 'ignore' the uploaded data sketch?

It appears that you have not uploaded the Arduino Core Software to your ESP8266 device because you are getting messages from the LUA interpreter which is overwritten when you install the Arduino Core Software.
The pre-requisites for using ESP8266FS to load sketches are here: ESP8266FS


text:
Making the speaker play a certain frequency of sound
I'm trying to make the piezo speaker play a sound of certain frequency. However, although I think the code is fine, the sound plays with a frequency between 130 ~160 only, and the frequency actually drops when it should be going up.
The code is as below:
digitalWrite(buzzer, LOW);
delayMicroseconds(1000000 / frequency);
digitalWrite(buzzer, HIGH);
delayMicroseconds(1);

What could be the problem?

Have you looked at the Tone library?  That does what you want, with some other niceties besides.
Anyway, the (or at least "a") problem with your code is that you are leaving the signal LOW almost all the time. You want it to spend half the time high, half the time low:
digitalWrite(buzzer, LOW);
delayMicroseconds(500000 / frequency);
digitalWrite(buzzer, HIGH);
delayMicroseconds(500000 / frequency);


text:
Two-way communication on multimaster I2C bus
I'm trying to send data both ways between an Arduino Mega 2560 slave and 2  Arduino Nano Zero (ATSAMD21G).
This example is a simplified setup and code. There will be more masters along with passive slaves on the bus (LCD, EEPROM).
Code and results (txt files)
My code is working fine with one master only and the slave active on the bus (data is sent both ways every 2s). I however notice missing transfers to the masters when more than one master is active. The 2 masters to slave transfers are working properly (once the 2 masters are on, the data is received by the slave every 2s from each master).
Is this problem due to collision? How can I handle it?

Unless this is class work or just you exploring how I2C works, I would suggest you stick with 1 master and poll the other I2C slave devices.  Otherwise read up on I2C.  I think you can only have one master at a time and the method to switch who is the master is part of the I2C protocol.  BTW, I know SPI requires more wires, but people generally have less problems getting SPI to work.

The chip itself can detect collisions. I'm not sure if the Wire library fully implemented that. You would need to check the return value of every Wire.endTransmission and every Wire.requestFrom. I agree with st2000, it is better to stay out of trouble and have only one Master. Sometimes an extra interrupt signal is added to the I2C bus, to make it possible that a Slave can notifiy the Master that data is ready and waiting.

I saw quite a lot of people hit a wall with this on Arduinos. It would be great to have a solution to address it that's not a workaround with loss of functionality or extra wires. Having multiple masters that can communicate when they need to, with multiple slaves allows a lot of fun developments!
The protocol and chips are supposed to handle collision but I read the wire library doesn't implement it.
I'll check what I can do with Wire.endTransmission and Wire.requestFrom return values.

Wire.requestFrom returns "byte : the number of bytes returned from the slave device". I guess these bytes can contain the real data or something random due to collision...
Wire.endTransmission returns success or errors, so that should work (Master to slave was already working in my code without this check)
Is there an improved version of the Wire library that handles this better?
Otherwise I'm thinking of polling at a faster rate and add a CRC check, but that would add back and forth communications between masters and slave.

The code had several issues leading to a constant flow of wrong data (with correct data in the middle) between the master that won the bus arbitration. This made it keep the bus too long and eventually give it away to the second master at a random time, with missed transfers from the second master in between. The second master was then behaving the same and so on.
receiveEvent, on the slave side, contained a millis if condition timer that made it time out. I moved the timer to the master side before calling Wire.requestFrom. Avoid slow code in receiveEvent!
receiveEvent, on the slave side, was also confusing real data with incoming requestEvent. I added an if statement to compare the receiveEvent data size with the expected size. Half of the data was wrong without this filter (this should ideally be handled in the Wire library)
These fixes solved the busy bus problem. I figured these out after asking question #35092
The bus speed also had to be reduced because 800 kHz was too fast for the Mega 2560 (but worked between 3 Nano).
The slave has to send the data destined to both masters to each of them because requestEvent can't tell which master is asking for data. The data is then filtered on each master to only keep the relevant information.
The data is now being transferred both ways between the 2 Nano masters and the Mega slave at the correct interval, without corrupt data.
fixed Slave code
fixed Master 1 code
fixed Master 2 code in the same repo (I'm limited to 2 links post)

notice missing transfers to the masters when more than one master is active.

Because you didn't provide a way for the master's to know of a transmission ISS in progress. Lack of conflict resolution. A problem with all multimeter transmission.
A simpler approach is for the slave to signal a transmission from the master. That can be done via a slave requestion pin from the slave to the master.

The I2C protocol handles multimaster, without this kind of workarounds. The communication library should do that too. I could add wires, but who has spare pins?


text:
If the USB gives 5v, how can the Arduino supply 5v to the 5v pin? (And another question)
I must not of understood something. Online, I've heard that the Arduino uses 9v typically (average), and that USB's in general supply 5v@500mA. If this is true:

How can the Arduino even POWER ITSELF with the 5v USB? I've heard the minimum is 7v.
How can there be a 5v pin if the USB supplies 5v... that leaves no room for the Arduino!

My understanding is very bad currently, any explanation would be great. Thanks!

it's not a 5v pin, it's simply just to the V+ of the usb. if you send 6v  over the usb, the pin will also have 6v.

I guess what I need to ask is what is the Forward Voltage of the Arduino without any extra pins connected to any other components?

parallel loads all get the same voltage. using a ballpark of 40ma for the uno's consumption, @5v that's 125 ohms. if you want other loads to share in series with the uno, then calc the "forward" as a voltage divider with rLoad, 5v and 125Ω as inputs

Forgive my noobiness, but is it possible to drive a 12v linear actuator AND the arduino using the same power supply?

Actually, Arduino is powered at 5V (the 5V pin and the ATmega328p are connected to the +5V rail in the board). The point here is where do those 5V come from. Basically, from 2 possible sources:

USB. The 5V line from USB is (or should be) already regulated, so it's feed directly (in fact it goes through a polyfuse) into the +5V rail of the board. The maximum current draw operating this way is 500 mA, limited by the polyfuse so you don't blow up your PC.
Barrel connector (wall adapter). It accepts 7-12V and brings it down to 5V using a linear regulator whose output goes to the +5V rail of the board. The maximum current draw operating this way is 1,000 mA, limited by the regulator capability.

If both sources are present at the same time, preference is given to the wall adapter. The UNO board has circuitry that detects voltage from the adapter and disconnects (using a MOSFET switch) the USB 5V line from the +5V rail of the board.
This is done not only for convenience purposes (so you have more current available), but also for protection. Otherwise, you'd be connecting two power sources (+5V from the regulator and +5V from USB) which is a dangerous situation.
I have commented the UNO R3 schematics so you can see for yourself how it's done (both input sources, adapter voltage detection circuitry, etc.), see below.

You might be mixing up voltage and ampereage. The Arduino takes in from 5volts up to 12, and uses a regulator to bring higher voltages down to 5V. Milliamps (mA) is the measure of what is drawn per circuit part. The Arduino itself only draws around 25 of these, which if running off of USB, leaves around 475mA that other things can draw.

On a basic level, the 5v of the USB port is regulated by the power supply of the external device, be it a computer USB port or a USB type charging module. When you are using the power jack on the Arduino, you can provide a range of voltage, from 7v (recommended minimum) to as much as 20v. This input power passes through a voltage regulator to provide the regulated 5v necessary to operate the Arduino.
Voltage is not "used up" by the Arduino, but you may have little reserve power for additional devices which are tied into the 5v bus.
Consider that voltage can be viewed in a manner similar to water pressure, while current can be compared to the volume of water flowing. If you have a 1000 mA power supply and the Arduino uses 500 mA, you have still available 500mA at 5v for other uses.
You can experience voltage drop in a circuit, depending on the way components are connected. That's more advanced than necessary for this discussion.
This is a very basic overview and details will vary from one model Arduino to another.
Also note that one should not apply 5v to other pins marked 5v as it bypasses the regulator and can damage the board or other devices attached.

@enric blanco made a good description. I just point out the strange difference between USB (5V) and barrel connector (7-12V).
The barrel connector has to accept different power supplies (with different voltages), moreover they may need voltage regulation; thus arduino needs a "regulator" after the barrel connector. There are different composants that can do it. This simple one will provoke a minimal loss of voltage. That is why you have to input more than 5V.
There are other components (buck/boost) that could accept input voltage from 3V to 12V and always provide 5V as output, but they are more expensive (5$).

You can supply five 5V directly to the 5V pin, which is effectively what the USB interface does. The quoted 7 to 12V is only if you are using the power jack. That converts it down to 5V which is what the processor needs.

No, you don't have to input more than 5V at the raw pin while exactly 5V is output at the VCC pin (at least with the Pro Mini).
How this is done I have no idea.


text:
Hacking old car dvd monitors with arduino
I got this old junk LCD from my car. The DVD function stopped and the LCD holder on the top of the car broke, so I took it.
Is there any documentation or advice I could use to get this working with an Arduino mega or clone of similar power? I couldn't find anything after looking through Google.
I.e. I'm looking for a way to get a pinout or idea of what those wires on the jack are so that I might be able to get text and/or basic graphics on the screen. Maybe to make an Arduino PC or something idk.
Any advice on either figuring out the connections by hand and how to get a simple connection to the Arduino to get bsic stuff working or a place I can find pinout and such or where someone else has done something similar would be helpful.

Update 2
A quick Google search reveals that it's made by sharp I believe. I'm looking into it.
Update
Here's is the back. It's got quite a few numbers on it. Maybe one of those can help?
Top Numbers:
D 09399847
LQ070T5CRQ2 46009355
And the one on the bottom:
K4013TP

Most bare monitors use an LVDS interface (some use a TTL like digital interface).  Such an interface requires very high data rates.  An Arduino is usually based on a low power Atmel processor.  There is no way an Arduino Uno, for example, can support the necessary data rates.  LCDs designed for under powered processors such as an Arduino Uno actually contain a much more powerful processor to go between the slow Arduino Uno and the LCD screen.

@st2000 What about a teensy 3.6? It has a 32 bit CPU running at 180MHz, 1M Flash Memory, 256K RAM, 4K EEPROM, and can be programmed in "real" C or Arduino. It's also very small in case you didn't get that from its name :)

These are opinions.  So I'll keep them in the comments.  The only recent "bare bones" attempt widely done was to interface a RaspberryPi GPIO port to a TTL level bare color LCD screen.  Even then, the color depth suffered.  LVDS would add the complexity of balanced pair HW.  Maybe, if you worked hard at it, you could get an ARM core Arduino to work.  But it may be much easier to take @Tri 's advice and find the OEM of the LCD and work backwards from there.

I realize this is an ancient question, but just in case someone else has one of these things, I'll share what I know. I have one of these Sharp LCDs that I typically use as a monitor for a Commodore 64. I believe mine was originally from a rear seat DVD player in a Ford Explorer.
Looking at the rear of the unit, with the two connectors on the bottom, the leftmost connector is CN2 and the rightmost is CN1. I know nothing of CN2, but here's what I know about CN1:
Pins 1 through 15, from left to right:

NTSC composite video in
ground
ground
?
+12VDC in
?
?
?
?
?
?
+12VDC in
+12VDC in
ground
ground

I'm sure the other pins have additional functionality, but I'm not aware of it. Hopefully this helps someone.
EDIT: I found the datasheet in my files: https://byteshiftmusic.com/media/Sharp_LQ070T5CRQ2.pdf

I don't even remember asking this question haha.
Might still have it somewhere though, so thanks!

Your best bet is to try to take the casing off until you find a company name so that you can get a lead on where to look for documentation. Because until you find out more about how that screen works, it's a black box to you and you don't know what to put in it. No one else will be able to help you until you provide more information to this extent because no one else can hold it in their hands, and the photo of the socket that you showed us doesn't look like a common display format either.
Also, you're very unlikely to make a PC-type thing out of this. That depends on the power of the computer behind the display and an arduino isn't that powerful. You want a Pi. Or maybe I'm misunderstanding what you want. You could easily get a scrolling text type thing going or maybe even a game (if you figure out how to make it work).
Edit: I just looked up a sample LCD screen and it has 6 signal pins and power and ground. Yours looks like it has a lot more. So you definitely have some digging to do.

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


text:
Problem with transmitting 2 byte data in correct way
I'm using Atmel Studio with Atmega328P.
I'm trying to send the decimal number 876 continuously from the micro-controller. This was just to learn.
To send 876 I need two bytes which is:
0x036C = 00000011 01101100
So I manipulated a code and here is what I use now:
#include <avr/io.h>
#define F_CPU 16000000
#define USART_BAUDRATE 9600
#define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)

void USART0Init(void)
{
    // Set baud rate
    UBRR0H = (uint8_t)(UBRR_VALUE>>8);
    UBRR0L = (uint8_t)UBRR_VALUE;
    // Set frame format to 8 data bits, no parity, 1 stop bit
    UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
    //enable transmission and reception
    UCSR0B |= (1<<TXEN0);
}

int main (void)
{
    //Initialize USART0
    USART0Init();

    while(1)
    {

        UDR0 = 0b00000011;
        UDR0 = 0b01101100;

    }

}

The problem is at the receiving side the data comes as:
01101100
00000011
00000011
.
.
.
Here is the screen shot of the binary data at the receiving end:

However it should be received correctly as two byte chunks 00000011 01101100.
And here you can see the problem of the data being received as uint16(not only 876 as desired):

How can I fix this and receive the data properly as two bytes with correct order as 876?

you should wait until previous value was successfully transmitter and UDR0 is ready for next byte

The data sheet for the 328P - section 24.7.1 - contains an example of waiting for the transmission to complete before sending another byte.
When sending serial data, you determine the order of bytes and will need to reassembly in the correct order on receipt.  You can use bit shift operators to move the bytes back into the correct location.  If you send the most significant byte first (MSB) and then the least significant byte (LSB), putting them back into a 16 bit integer would look something like:
uint16_t result = (MSB << 8) | LSB;

i tried this works so far: UDR0 = 0b00000011; while(!(UCSR0A&(1<<UDRE0))){}; UDR0 = 0b01101100; while(!(UCSR0A&(1<<UDRE0))){};

Your code has a fundamental error: when you write "UDR0 = 0b00000011;", the CPU does not wait until the transmission is complete - that would be terribly wasteful, in terms of time. It just write to the transmit data buffer. Furthermore, if the transmission was not ongoing yet, that instruction also starts transmission (assuming the USART is properly initialized, as it is in your case). However, if a transmission is ongoing, and the data buffer is not empty, this write instruction might be either ignored or it might overwrite the data on the buffer.
Therefore, with your code, you're continuously writing two bytes (at a very high speed, because that loop would result in very few asm instructions), without checking if actually you can write to the transmit data buffer register. This will result in most of the bytes being "randomly" ignored, with some other being randomly picked and trasmitted.
Before sending any data, you must check if the data register is empty:
while ( !(UCSR0A & (1 << UDRE0)));
UDR0 = firstByte;
while ( !(UCSR0A & (1 << UDRE0)));
UDR0 = secondByte;

Where firstByte and secondByte are either the numeric values or two 8-bit variables.
Instead of the two "while" statements, you can use the built-in macro:
loop_until_bit_is_set(UCSR0A, UDRE0);

First, you want to determine what you are trying to send. Send data in binary form is rare.
Secondly, you want to wait for each transmission to send before starting the next one.

My goal is to learn to send 16bit unsigned data very fast way. I heard sending as bytes instead of strings is better for fast communication. What can I do for waiting between transmissions and how long? I dont know how to do that.

do you mean like this?:   UDR0 = 0b00000011;   while(!(UCSR0A&(1<<UDRE0))){};   UDR0 = 0b01101100;      while(!(UCSR0A&(1<<UDRE0))){};