text:
Understanding values from an MPU6050
I'm trying to understand the values that I'm getting from my MPU6050. I believe that there is a problem with my code. I'm not entirely sure how the code is supposed to look like. There doesn't seem to be very many examples on the MPU6050.
What is wrong?
After taking a look at the system print I found that the numbers that are written out is the time and not the values of the MPU6050. Why am I getting the zeros and nan for?
I also had a library problem thats fixed now.
I got the code from a site and I've modified it because it didn't run for me.
This is my code:
// collect readings
accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

// apply gyro scale from datasheet
gsx = gx/gyroScale;   gsy = gy/gyroScale;   gsz = gz/gyroScale;

// calculate accelerometer angles
ary = -(180/3.141592) * atan(ax / sqrt(square(ay) + square(az)));
arx =  (180/3.141592) * atan(ay / sqrt(square(ax) + square(az)));
arz = (180/3.141592) * atan(sqrt(square(ay) + square(ax)) / az);

// set initial values equal to accel values
if (i == 1) {
grx = arx;
gry = ary;
grz = arz;
}
// integrate to find the gyro angle
else{
grx = grx + (timeStep * gsx);
gry = gry + (timeStep * gsy);
grz = grz + (timeStep * gsz);
}

// apply filter
rx = (0.1 * arx) + (0.9 * grx);
ry = (0.1 * ary) + (0.9 * gry);
rz = (0.1 * arz) + (0.9 * grz);

 Serial.print(ax);   Serial.print("\t");
 Serial.print(ay);   Serial.print("\t");
 Serial.print(az);   Serial.print("\t\t");
 Serial.print(gx);   Serial.print("\t");
 Serial.print(gy);   Serial.print("\t");
 Serial.print(gz);   Serial.print("\t\t");
 Serial.print(arx);   Serial.print("\t");
 Serial.print(ary);   Serial.print("\t");
 Serial.print(arz);   Serial.print("\t\t");
 Serial.print(grx);   Serial.print("\t");
 Serial.print(gry);   Serial.print("\t");
 Serial.print(grz);   Serial.print("\t\t");
 Serial.print(rx);   Serial.print("\t");
 Serial.print(ry);   Serial.print("\t");
 Serial.println(rz);

This is the output im getting
2   1.00    61.00   0.06000     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
3   61.00   139.00  0.07800     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
4   139.00  219.00  0.08000     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
5   219.00  300.00  0.08100     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
6   300.00  380.00  0.08000     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
7   380.00  462.00  0.08200     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
8   462.00  543.00  0.08100     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
9   543.00  624.00  0.08100     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
10  624.00  705.00  0.08100     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
11  705.00  788.00  0.08300     0   0   0       0   0   0       nan nan nan

...
41  3223.00 3307.00 0.08400     0   0   0       0   0   0       nan nan nan nan nan nan     nan nan nan
42  3307.00 3392.00 0.08500     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
43  3392.00 3476.00 0.08400     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
44  3476.00 3560.00 0.08400     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
45  3560.00 3645.00 0.08500     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
46  3645.00 3729.00 0.08400     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
47  3729.00 3813.00 0.08400     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
48  3813.00 3897.00 0.08400     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
49  3897.00 3982.00 0.08500     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
50  3982.00 4066.00 0.08400     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
51  4066.00 4150.00 0.08400     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
52  4150.00 4234.00 0.08400     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
53  4234.00 4319.00 0.08500     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
54  4319.00 4403.00 0.08400     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
55  4403.00 4487.00 0.08400     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
56  4487.00 4571.00 0.08400     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
57  4571.00 4656.00 0.08500     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
58  4656.00 4740.00 0.08400     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan
59  4740.00 4824.00 0.08400     0   0   0       0   0   0       nan nan nan     nan nan nan     nan nan nan

Ever increasing values suggest code which is trying to integrate an acceleration measurement to determine velocity, something that it not realistically workable with a budget sensor.  Your question is insufficiently specified to ask here, as you neglect to include the code generating the output columns, so no one can have any idea beyond guesses as to what they represent.

"After taking a look at the system print i found that the numbers that are written out is the time and not the values of the MPU6050. Why am i getting the zeros and nan for?"

@ChrisStratton I have added the entire output + the print.

@ChrisStratton Chris?

Your data is clearly flawed - look how the values in ax, ay, az turn up in a different position in the next row.  Are you passing the correct type of pointer?  Remove all the rest of the code and just focus on getting valid values for those as a start.  Or maybe you should go back to the original code and figure out why exactly it didn't run.

I think the best choice for you is to read raw data from the sensor using Wire library.

First of all, you have to include the "Wire.h" library:
#include "Wire.h"

Next step is to start the I2C communication by calling the following function in setup()
Wire.begin();

Now that the master joined the I2C bus, all you have to do is to set the power mode of the module by setting the register 0x6B to 0x0. You can use the following function:

int sendCommand(int8_t register_address, int8_t register_value) {
Wire.beginTransmission(mpu_address);
Wire.write(register_address);
Wire.write(register_value);
int statusCommand = Wire.endTransmission(true);
Serial.print("I2C Address: "); Serial.print(mpu_address, HEX);
Serial.print(" Register address: "); Serial.print(register_address, HEX);
Serial.print(" Register value: "); Serial.print(register_value, HEX);
Serial.print(" Status command: "); Serial.println(statusCommand);

return statusCommand;
}

Please note that the default I2C address for the MPU6050 is 0x68. You can use the I2C Scanner to find its address.
To actually set the register 0x6B to 0x0 you have to call the sendCommand like below:
sendCommand(0x6B,0x0);

Request the raw data from the MPU6050. You can check the MPU6050 Register Map for additional information.  Accelerometer can be found from 0x3B to 0x40, temperature from 0x41 and 0x42, and finally, the gyro from 0x43 to 0x48. IMPORTANT!!! Every register's value occupy 1 byte (int8_t), so you have to get the values of two registers (2 bytes) and store them in an int16_t.

Here is the full code to get the angles from the sensor:
#include "Wire.h"

int8_t mpu_address = 0x68;
int sendCommand(int8_t register_address, int8_t register_value) {
  Wire.beginTransmission(mpu_address);
  Wire.write(register_address);
  Wire.write(register_value);
  int statusCommand = Wire.endTransmission(true);
  Serial.print("I2C Address: "); Serial.print(mpu_address, HEX);
  Serial.print(" Register address: "); Serial.print(register_address, HEX);
  Serial.print(" Register value: "); Serial.print(register_value, HEX);
  Serial.print(" Status command: "); Serial.println(statusCommand);

  return statusCommand;
}

void setup() {
  //join the I2C bus
  Wire.begin();
  //start serial communication
  Serial.begin(115200);
  delay(1000);

  /* sendCommand can return 5 possile values:
   * -> 0:success
   * -> 1:data too long to fit in transmit buffer
   * -> 2:received NACK on transmit of address
   * -> 3:received NACK on transmit of data
   * -> 4:other error
   */
  while(sendCommand(0x6B,0x0) != 0){
    delay(1000);
  }

  Serial.println("MPU6050 started");
}

void convertRawDataToAngle(int16_t AcX, int16_t AcY, int16_t AcZ) {
  int minVal = 265; int maxVal = 402;
  int xAng = map(AcX, minVal, maxVal, -90, 90);
  int yAng = map(AcY, minVal, maxVal, -90, 90);
  int zAng = map(AcZ, minVal, maxVal, -90, 90);

  int x = RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);
  int y = RAD_TO_DEG * (atan2(-xAng, -zAng) + PI);
  int z = RAD_TO_DEG * (atan2(-yAng, -xAng)+PI);

  Serial.print("X angle: "); Serial.print(x);
  Serial.print(" Y angle: "); Serial.print(y);
  Serial.print(" Z angle: "); Serial.print(z);
}

void readData(int8_t register_address) {

  int bytesReceived = -1;
  int statusCommand = -1;
  do {
    Wire.beginTransmission(mpu_address);
    Wire.write(register_address);
    statusCommand = Wire.endTransmission(false);
    bytesReceived = Wire.requestFrom(mpu_address, 6, true);
    Serial.print("I2C Address: "); Serial.print(mpu_address, HEX);
    Serial.print(" Register address: "); Serial.print(register_address, HEX);
    Serial.print(" Status command: "); Serial.print(statusCommand);
    Serial.print(" Bytes received: "); Serial.println(bytesReceived);
  } while (statusCommand != 0 && bytesReceived != 6);
  //check if MPU6050 sent all the requested data
  //in total 6 bytes, 2 bytes for each axis
  if (Wire.available() == 6) {
    int16_t AcX = Wire.read() << 8 ;
    AcX |= Wire.read();
    int16_t AcY = Wire.read() << 8 ;
    AcY |= Wire.read();
    int16_t AcZ = Wire.read() << 8 ;
    AcZ |= Wire.read();
    convertRawDataToAngle(AcX, AcY, AcZ);
  }
}
void loop() {
  //put your main code here, to run repeatedly:
  readData(0x3B);
  delay(100);
}

In Wire.read() << 8 | Wire.read(), it is unspecified which Wire.read() is executed first. You may get lucky with a particular version of the compiler, but the only safe way of getting the bytes in the right order is to do the reads in two separate statements.

Well, I did it that way because I request 6 bytes of data, starting from register 0x3B. I expect to receive them in the order I requested. Am I right? If not, can you provide me tips how to replicate what you said, to get the bytes in the wrong order?

I cannot, as I likely use a compiler version not too far from yours. My point is that the fact that it does work with the compiler we are using now does not mean the code is correct. The correct version would be AcX = Wire.read() << 8; AcX |= Wire.read();

Oh, I get now what you mean. Thank you for the suggestion. I will update it soon! If there is anything that might go wrong, I am open to fix them. I still have a lot to learn!

The output MPU 6050 does need filtering/processing before you can get any sense from it.  I have used the library "MPU6050_6Axis_MotionApps20.h" with success, it is located here: MPU6050_6Axis_MotionApps20.h
I have written an example here: MPU 6050 for MicroView.

Does your code also get the values?

The library does its magic, and you can get Euler angles simple and reliable (these are orientation angles).  Other measurements such as acceleration are also easy to obtain.

Im getting a ton of errors from the library. Ive added the errors to the code above. Ive been busy thats why it took so long.


text:
I have two 6 volts DC motors connected to L298N motor Driver. Do I need to use 12 Volts battery?
I have two 6 volts DC motors connected to L298N motor Driver. Do I need to use 12 Volts battery?

No, you need to use a (roughly) 6V battery. They are 6V motors, so they need a 6V battery.
However, you do need to sum the currents not the voltages. The battery must be able to provide at least the current required by both motors together.

source: Stack Exchange

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

sort: votes


text:
Arduino Temperature sensor with a LED
I want to program a temperature sensor with a LED using Arduino.
the goal is to make a sensor, when the temperature is over than Temperature max, the LED turns off and when the temperature is small than temperature max we turn on the LED.
my problem is when I programed the void setup() as followed, the LED doesn't work, and when I comment Serial.begin (9600) the LED work but I cannot diplay the value of the temperature.
void setup() {
   Serial.begin(9600);
   pinMode(tempPin, INPUT);
   pinMode(led, OUTPUT);
}

here you find my complet code:
    int tempPin = A0;   // the output pin of LM35
float Max_temp = 24.0;
int led = 1;

float  temp, cel;
void setup() {
   Serial.begin(9600);
   pinMode(tempPin, INPUT);
   pinMode(led, OUTPUT);
}
void loop() {
      cel = readTemp();
  if(cel< Max_temp) {        // if temp is higher than tempMax
      digitalWrite(led, HIGH);  // turn on led
      delay(300);
     }
     else {                    // else turn of led
       digitalWrite(led, LOW);  // turn on led
      delay(100);
  }
   Serial.print("TEMP: ");
   Serial.print(cel);      // display the temperature
   Serial.print("C ");
   Serial.println();
   delay(300);
}

float readTemp() {  // get the temperature and convert it to celsius
  temp = analogRead(tempPin);
  return temp * 0.48828125;
}

thank you very much in advance

I think that the others have more than enough covered it, but next time please edit your question (link). If you have any questions please feel free to respond to me with @AnnonomusPenguin. Thanks!

there are 2 excellent answers below.  it is only polite to extend the authors the courtesy of an upvote and/or comment and/or accept it.  ;)

int led = 1;

You do know that pins 0 and 1 are the serial port don't you?
Take your pick.... Either use pin 1 for the LED OR use pin 1 for the serial connection.  You can't do both!
As it says in the manual:

In addition, some pins have specialized functions:

Serial: 0 (RX) and 1 (TX). Used to receive (RX) and transmit (TX) TTL serial data. These pins are connected to the corresponding pins of the ATmega8U2 USB-to-TTL Serial chip.

Your logic is backwards. Your program says if the temp is LESS THAN max then turn on the LED.
But worse than that, you should not use pin 1.  Pick any other pin.

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


text:
Arduino + TMP36 + DC Motor
I made this circuit:

The part with the DC motor is from this tutorial: https://learn.sparkfun.com/tutorials/sik-experiment-guide-for-arduino---v32/experiment-12-driving-a-motor ( I only use another resistor, with 220 OHM)
As you can see, I also have a TMP36 sensor attached. What I would like to do is this:
When the temperature is 25 degrees or more, the motor should turn on.
I have this code:
//TMP36 Pin Variables
int sensorPin = 0; //the analog pin the TMP36's Vout (sense) pin is connected to
                        //the resolution is 10 mV / degree centigrade with a
                        //500 mV offset to allow for negative temperatures

/*
 * setup() - this function runs once when you turn your Arduino on
 * We initialize the serial connection with the computer
 */
void setup()
{
  Serial.begin(9600);  //Start the serial connection with the computer
                       //to view the result open the serial monitor
}

void loop()                     // run over and over again
{
 //getting the voltage reading from the temperature sensor
 int reading = analogRead(sensorPin);

 // converting that reading to voltage, for 3.3v arduino use 3.3
 float voltage = reading * 5.0;
 voltage /= 1024.0;

 // print out the voltage
 Serial.print(voltage); Serial.println(" volts");

 // now print out the temperature
 float temperatureC = (voltage - 0.5) * 100 ;  //converting from 10 mv per degree wit 500 mV offset
                                               //to degrees ((voltage - 500mV) times 100)
 Serial.print(temperatureC); Serial.println(" degrees C");

 if(temperatureC >= 25){
  analogWrite(9, 250);
 }

 delay(1000);                                     //waiting a second
}

But I get this result:
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.74 volts
24.22 degrees C
0.75 volts
25.20 degrees C <------
0.87 volts
36.91 degrees C
0.66 volts
16.41 degrees C
0.78 volts
27.64 degrees C
0.77 volts
26.66 degrees C
0.84 volts
34.47 degrees C

The point where the sensor measures > 25 degrees, the motor turns on but the circuit gets "poluted" and the temp sensor starts to send all kinds of strange values.
How do I solve this?
Thanks in advance!

I got it to work in with the following: http:// i.stack.imgur.com/4GFPH.png

Motors tend to use more current than the arduino can supply, try hooking up the motor to a different power supply than the arduino 5V. What most likely is happening, is that when the motor turns on, it alters the value of the voltage, which the temperature sensor is using to tell the arduino what the temperature is. You need to have the temperature sensor hooked up to the arduino to have the reference at the right voltage, so the motor should be on a different power supply. That should fix things.

Thank you rocketman412. I can't figure out how to add a battery to the circuit. I've removed the red + and black - wires from the bottom and changed the circuit to this:
http://i.imgur.com/2haaNqd.png
But it's not working.

I would think connecting the ground of the arduino to the ground of the battery should help. Other than that, I'm not entirely sure why it wouldn't work.

I've just tried it, but still not working :(

Did you get the motor to work without the temperature sensor? That may be the issue. What transistor are you using as well? 2n2222s aren't as available now, so if you switched it out for a different one, the different properties of that new transistor could cause it to act the way it is.

I did get it to work without the temperature sensor. As the 2n222's are unavailable, I've used the following: BC547B.
The Diode I'm using is 1N4001 50V 1A.

I rechecked everything, it turns out that the solution you provided worked! I didn't propperly connect the ground of the arduino wit the ground of the battery. I'll update the question with a proper drawing. Thanks rocketman412!

You're very welcome! Glad to hear it works now!


text:
Efficiently using a serial inteface
So at my school we are preapering for a competition. They asked me to do the technical side of it. And I accepted... I was thinking of using an arduino as a usb device for the buttons. I am going to use the serial port for this. But I can't think of a way to do it in the way I want. I want to recieve the button presses fair and well. But I also want to control the lights for the buttons, from my computer. I am using Serial.printLn() to send the serial data to the computer. But how can I send serial data to the arduino without delaying other things (What happens when someone presses a button while I am sending a command?)? Thanks in advance!

I was thinking of using an arduino as a usb device for the buttons. - what do you mean here? Later you talk about sending serial data to the PC. These are different things.

So will be also be doing the programming. Since I will be writing the program, I can easily implement the serial communications. All they have to do is plug the arduino in and change the port, if it needs to. That's what I meant.

Serial communication is done using interrupts, and buffers. So unless you do something weird with your program, there shouldn't be much of a problem. It would be helpful to know what it is you are trying to achieve with the buttons. Something like a gameshow, where you need to detect who pressed the button first?

Yes exactly a gameshow. I need buttons for the game. I want to be able to control the lights through the serial inteface. I cannot figure out how I am going to do it. I reckon if I call Serial.readLine() it will halt until it gets an \n

The nastiest part in what you describe is likely to be the debouncing on the button, rather than the serial communication.
One easy way out is to use some form of bounceless implementation, like an optical coupler. Another is to use HW debouncing, like the MAX 6816 family.
Then you can use a loop where you alternate between serial communications and checks for the status of the buttons.
Or you can rely on interrupts for the buttons, but it's more complex and might be overkill.

I can try to debounce the button on the computer. I am also writing the code that will be used for the competition...

The thing is the school is sourcing the parts. I am surprised they even sourced arduinos for the physics lab.


text:
Serial communication between Computer & Arduino via XBee
I configured two XBees using XCTU, connected them to the computer and sent Bytes back and forth. Works.

This is the current, non-working setup:

1 XBee, connected to the Computer using a SparkFun XBee Explorer USB.
1 XBee, connected to an Arduino Mega using SparkFun XBee Explorer Regulated

GND to GND
5V to 5V on the Arduino
DOUT to TX1 on the Arduino
DIN to RX1 on the Arduino

void setup() {
  Serial1.begin(9600);
  pinMode(13, OUTPUT);
  //After 3 seconds the XBee should send out a couple of "A"s coming from the serial port
  delay(3000);
  int i = 0;
  while (i < 10) {
    Serial1.print("A");
    delay(100);
    i++;
  }
}
void loop() {
  //If anything is sent to the XBee it should appear in the Arduino's serial buffer
  //making the LED on pin 13 turn on
  if (Serial1.available() > 0) {
    digitalWrite(13, HIGH);
  }
}

The DOUT LED on the Explorer Regulated flashes as supposed to but nothing is received on the computer where my Terminal application is listening.
Same when I send something from the Terminal, the LED on pin 13 of the Arduino does not indicate any bytes in the buffer, meaning that the XBee probably never received anything.
I already tried swapping TX & RX, resulting in the DIN LED blinking instead of DOUT. Transmission still not working.

Try swapping TX and RX.

Is the terminal configured for 9600 baud? Are both xbees configured to it too?

@EugeneSh. Yes, they're set to 9600 baud. Probably would have noticed already when transmitting data with the Terminal.

Anyway, DOUT is an output of XBee, so it should go to the input of Arduino, which is RX, rather than TX. First fix this. BTW, make sure you don't have any hard/soft flow control

@Dario Swapping TX and RX was the solution? Please share it with is for when we get the same problem :) Output of one device is likely to be input of the other and vice versa. It's not that RX connects to RX and TX to TX, they should be cross-connected.

@FuaZe I got it to work using a different board as well as connecting RX to RX and TX to TX, what seems a little odd but at least it works. I'll post a detailed answer in a few hours.

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


text:
Using / calibrating pH sensor module
I've bought this sensor module board to link to an Arduino nano: http://www.ebay.com/itm/For-Arduino-Liquid-PH-Value-Detection-detect-Sensor-Module-Monitoring-Controller/321764233326
I assumed the two screws were for calibration (low point + slope), but it seems the operation is different and I can't figure out how. I've got two reference liquids for pH of 4.0 and 7.0. When I put the probe in either one, I get readings. Turning one of the two screws seems to offset the reading so for instance I had pH 4 = 900 and pH 7 = 1000 (0 - 1023 range). Turning one of two screws would lower the value a bit, but it never gets below 500 or so.
So what I can do is measure two points (4.0 and 7.0) and their respective measurement values. That way I could calculate points in between, but as far as I know pH is not a linear scale, but logarithmic. If I get this wrong, the reading might seem right but only show 4.0 and 7.0 correct and not the rest of the values (I don't have 10.0 reference fluid at the moment).
Now onto the second screw, that one at first seemed to do nothing. But then I noticed that it sets some kind of threshold value, turning a LED on the board on and off. That LED seems to be linked to the value being read, but it's further purpose? Calibration? No idea.
Ok so best case someone has an equal module and wants to detail how it works. Otherwise maybe some of you have some bright ideas on what I could try in order to get this to work the way I want it to :)
Update 09-11-2015
Got feedback from the seller. She sent me the following ZIP: http://1drv.ms/1MSk1DX. It contains some files in Chinese but one had sourcecode in it. Tried it on my Arduino but unfortunately the values still don't make much sense. Depending on how I turn the knob on the print, I get values between 9 and 17 for a liquid that's in real life 7.0. I didn't try but doubt that doing a -7 offset is sensible.
The code itself is pretty straightforward, taking a 6-center average of ten consecutive measures. The interesting lines are these:
 avgValue = 0;
 for (int i=2;i<8;i++)       // take the average value of 6 center sample
   avgValue+=buf[i];

 float phValue = (float)avgValue*5.0/1024/6; // convert the analog into millivolt
 phValue=3.5*phValue+Offset;

Maybe someone can make sense of this, because I can't. I don't understand the 5.0 multiplication and the 3.5 after that one. Where do these come from?
Anyway, when I dip the probe into the storage liquid, my normal meter plummets to pH 0.5 whilst the software is giving me 17 (which is a higher value than the one I got from reading my 7.0 liquid). So either my board is broken or this sample code is useless.
Schematics can be found in the ZIP file by the way.
Update 11-11-2015
Did some more experimenting. First I found out that the readings from the module increased for more acidic liquid. So I reversed the value by using
buf[i]=1024 - analogRead(SensorPin);

Ok, now the values made more sense. Then I adjusted the pot to be in the middle of the available range. I dipped the probe in the 7.0 liquid, read the value and adjusted the offset. Then dipped in 4.0, adjusted the pot to match with 4.00, here are the results:
pH 7.0 reference --> 6.27
set offset to: 0.73
pH 4.0 reference --> 5.17
adjusted the pot so value read 4.0
pH 7.0 reference --> 5.86

So as I expected, adjusting the pot also messes up the 7.0 reference measurement. I then though it might be because of the slope of the pot (if there would be any), so I went to the lowest value first to have the least difference. Again the readings:
pH 7.0 reference --> 8.70
set offset to: -1.70
pH 4.0 reference --> 5.17
adjusted the pot so value read 4.0
pH 7.0 reference --> 5.70

The interesting thing here is that the 4.0 value reads 5.17 in both cases, even though the pot was in a different position. I cannot explain why though.
To make sure the probe is fine I re-calibrated my normal pH meter, operates as usual. This one also has two pots, one for 7.0 calibration and one for 4.0 slope. Calibration is done by setting 7.0, then measuring 4.0 and ajusting the slope pot. Measure 7.0 again, change 7.0 pot, measure 4.0 again, etc. until the values match their liquids. Usually takes me about 3 - 4 loops to get it right.
Another update
Took the two containers of reference fluids and started mixing. This gave me measurements in the range of pH 4 - 7.5. Also measured the storage liquid which has a pH of 1.00. Results are in an Excel sheet: http://1drv.ms/1lkAO6e. Next question is how to convert this into a suitable formula?
Update 18-11-2015
Working on @slash-dev's solution, here's what I did:
I first turned the pot all the way down to the lowest value. The readings (for pH 7.0) are as follows: low = 540 and high = 1017. Code as follows:
int rawValue = analogRead(SensorPin);
int buf[10];                //buffer for read analog

for(int i=0;i<10;i++)       //Get 10 sample value from the sensor for smooth the value
{
   buf[i] = rawValue;
   delay(10);
}

// sorting left out to reduce the sample length

int avgValue=0;
for(int i=2;i<8;i++)  // take the average value of 6 center samples
   avgValue += (buf[i] - CENTER);

In this stage I'm printing the raw value of course.
The shorting of the BNC connector I don't exactly understand, should I short the inside (where the pin goes) or the outside of the connector? And short it to the GND? I used the reference solution instead.
Now I added the formula to determine the voltage. For the low value that reads 0.10. I now put in the center value of 540 which brings the voltage reading to 0.0, seems good.
Now for step 2 I placed the probe into the 4.0 reference solution. The voltage now reads 0.48, raw value 637. I start adjusting the pot to where the voltage reads 2.25, takes quit some adjusting. Raw now reads 1000.
Now comes the part I don't exactly get. You say we can now calculate the pH/V, but with what variables? I mean, -3 / 2.25 will always result in -1.33 but shouldn't there be a variable here depending on how far I actually adjusted the pot?
When I now put in the formula to calculate the pH as expected it reads 4.0 for the 4.0 reference solution. But it now screws up the 7.0 solution as we adjusted the pot but didn't compensate for it as far as I see? I also tried the adjusted pH formulas but I guess those are meant for the first code we had and not this adjusted one.
So what am I missing between step 2 and 3 that messes up things here? Also, you state that the inverting by subtracting from 1024 is correct, but when I do that the voltage readings become minus.
Another thing I wonder about; if the pot has to be a slope, shouldn't it be a different one than the one next to it (where a linear one makes more sense)? Cause it isn't, they both read "W103 / 143C". In the meantime, the vendor is kindly sending over a replacement one to ensure it's not a hardware defect somewhere.
Next update: :)
So I now reverted to my original code to try the adjusted pH calculations. I used the 7.0 reference solution to calibrate again and then measured the 4.0 solution. It reads 4.1! Ok, not completely spot on but not bad either. It's a small difference which might as well come from the probe, not the most expensive one.
So I wonder whether we should still try to get the other approach working cause it sounds better (more scientific?) for some reason. Anyway, this is at least a whole lot better than nothing :)
USB power vs linked?
Another strange thing seems to happen when I disconnect the Nano from the USB port of my laptop and instead power it via a Raspberry. I want to use I2C to send the value from the Nano to the RPi. This works, but as soon as I power the nano from the RPi (5V connected to vIn), the calculated pH value drops?

I'm interested in this too, because I might use one of those sensors soon. See if the links on this page are helpful: https://www.tindie.com/products/rezahussain/dormant-labs-ph-module-v2/

There seems to be a remarkable lack of information about these modules, from the eBay vendors I skimmed. I am guessing none of them knows what they do. If you could find a datasheet, that might help. Maybe if you post what sort of chips are on the board it might help narrow down what the adjustments might do.

I've mailed the seller with a request for info, will update when I get it (and write a blog post). As for the chip types, will do but I'll have to check tonight when I'm home :)

@Jerry; thanks, but that's a different module which has software calibration instead of hardware knobs. Not the same and thus not much useful info there.

I think i have exactly the same sensor and tried to reproduce the solution, but with no results. Could you share the code which made it working for you? TIA
Thomas

@Thomas I'm afraid that the "working" state only lasted a very short time. I'm back to having only weird values coming out, this board is just crap is my short conclusion. I'm switching to an Atlas board which should be much much better.

The schematic only shows one trim pot (R23), and it does, as you suspect, set a level for the LED to illuminate.  More of a GOOD/BAD indicator, and is available on pin DO.
The other trim pot is not on the schematic.  Is it marked on the board?  R6, R7, R8 or R9 maybe?  It probably controls the gain on p_AOUT.
t_AOUT is an analog temperature voltage, and appears to measure the temperature of the board.
Edit - official but totally bogus: According to my secret source, you are supposed to put the probe in the pH 7.0 reference solution and, with Offset defined to be 0.0, run the program and display the calculated pH value.  You may need to decrease the trim pot gain to get smaller (the smallest?) numbers.  Now take that displayed value and modify the Offset constant in the sketch to be 7.0 minus the displayed value.  If the displayed value is 8.1,
#define Offset (-1.1)

Build and upload the modified sketch.  This time, put the probe in your pH 4.0 reference solution and adjust the gain pot until the displayed value is as close to 4.0 as you can get.  This will calibrate it for mostly acidic solutions.

Edit 1: Iterate?
It's not clear, but I also wondered if this procedure is supposed to be iterated.  Go back to 7 and make sure that adjusting the gain didn't change Offset. Then test the pH 4 solution again; the gain pot may require a small(er) change. If it seems to be diverging, um, don't do that. ;)  I think it would diverge only if the probe had an inverted response, which would probably mean it's bad.
If you are measuring basic solutions, do the same procedure with reference solutions of pH 7.0 (of course) and a basic reference solution.
Voilà!
NB: For the 7.0 test, you could short the probe pins together. It really should look like a short circuit when pH == 7.0.  If switching to using the real probe in the pH 7.0 solution gives wildly different readings, the probe may be bad.  If you're able to calibrate it, it may be "good enough".

Edit 2: Fix the formulas in the provided sketch.
The schematic shows a non-inverting op amp with PH+ on the input, and p_AOUT on the output.  The (adjustable?) gain is
R9/R8 + 1 = 10k/10k + 1 = 2

The slope of an ideal probe response is -59mV/pH.  You were experimentally getting a negative slope, which agrees with the schematic.  I believe it was correct to "invert" the analogRead value by subtracting it from 1024.  There is no way that the provided code could have worked with a positive slope of 3.5.
The reference voltage provided to the the PH- pin is half the zener diode voltage... which is unidentified.  It could be the very-common 5.1V part, which is essentially forcing PH- to be at
5.1V/((R6+R7)/R6) = 5.1V/2 = 2.55V

I say probably, because you usually want the plus or minus probe voltage swing to have as much room as possible.  This would imply (an ideal) analogRead of pH 7.0 to be
2.55V/5.0V * 1024 = 522

This is the "center" of the probe swing about pH 7.0.
Step 1: Determine the reference voltage
At pH 7.0, print out the raw analogRead return value, before inverting it.  (The pot wiper should be at it's limit.  Which way, I don't know.  Changing the gain pot shouldn't change the analogRead very much at the low-gain end.  If it does change it, turn it to the other extreme.)
As stated before, you can run the pH 7.0 test by shorting the BNC connector pin to the shield or by using your reference solution.  I recommend shorting for now, to eliminate any possible interference from the probe.  It will absolutely determine the offset, but only if the gain is as small as possible.  You have to start here.  Once you know the center reading, you can change the code to display the voltage:
#define CENTER 522
int avgValue=0;
for(int i=2;i<8;i++)  // take the average value of 6 center samples
  avgValue += (buf[i] - CENTER);
float voltage = (((float)avgValue) / 6.0) * (5.0 / 1024.0);

Print this out.  You'd better get something close to 0.0... don't make me come over there.  :)
Step 2: Set the gain pot.
This is determining the slope, but you need to maximize the swing for the most extreme pH you want to read, say 4.0.  Using the 4.0 reference solution, adjust the gain pot so that the displayed voltage is close to +2.5V, say +2.25V to make sure it's not pegged at 1024.  (Let's see, slope is negative, 4.0 is < 7.0, so voltage should increase...)  With that reading, you can calculate the pH/V:
-3pH/2.25V  =  -1.33 pH/V

Step 3: Calculate and print pH
Modify the original computation to use the pH/V slope:
float phValue = voltage * (-1.33) + 7.0;

This is not even close to phValue = 3.5*voltage + Offset.  -_-    I have found several source now that echo my original answer.  Totally wrong, and wrong to the point of misleading.  I do think these steps will do it.  It sounds good in my head, anyway.  :D

Edit 3: "Next question is how to convert this into a suitable formula?"
Ok, if you don't want to fix the formula in the code, you can fit a linear or quadratic curve to your data.  Linear is actually recommended as "good enough", and that is effectively the change suggested in Edit 2.  If we just use your data points, though, this would be the linear approximation:
float adjustedPh = phValue * 1.627 - 2.499;

...and the quadratic approximation:
float adjustedPh = (-0.01796 * phValue + 1.8056) * phValue - 2.94;

A secret source heh? Sounds interesting :) Anyway, I will try this approach. My readings are far off from 7, so that means the offset will be something like 5 or 6, seemed a bit too far off. Also, when I adjust the gain pot for the 4.0 solution, won't that also mess up the 7.0 reading? Wil try tonight when I'm at home.

Yes, I also thought about iteration because that is the way it works for my normal meter. The problem is that this set-up now has two offsets; one as the pot on the board, one in the software. Changing either one for 4.0 messes up the 7.0 just as quickly. The only way this would work is when the software would apply a slope, or the pot would. Neither do as far as I can see. I tried your solution, see update.

@Jasper, you haven't posted in several days, although I see you have visited.  Have you tried "Edit 2" or "Edit 3"?

I'm sorry, you're right. I read your response but didn't get to testing it. Now I have, see update above.

Btw the bounty expired but I'm more than willing to grant it to you. Let me know whether you want to try to get the other solution working and otherwise I'll go and do a new one + answer it.

Sigh.  Edit 2 should have worked if the schematic was right.  It must not be right.  It looks like several manufacturers have simply copied it into their websites.  Your board has an extra transistor that is not on the schematic, so I don't think it's worth messing with the "correct" solution until you know the schematic. If Edit 3 is good enough, why bother reverse engineering this board?  As far as awarding the bounty, this seems like something a moderator would do to avoid a duplicate question and answer.  Could you flag this comment to get their attention?

Done (flag). And you're right. What I have is good enough for now, at least the values are somewhat credible. In due time I'm going to upgrade to an atlas module I think, those should be much better (https://www.atlas-scientific.com/product_pages/sensors/ph-sensor.html)

USB power vs linked

Just to add my 2 cents on your latest update about the USB or 5V from the PI.
You say you connect it to the VIN:

as soon as I power the nano from the RPi (5V connected to vIn), the calculated pH value drops?

If you look at the below image you see that Vin goes to a good old 7805, which needs a IN voltage > 7.5V, thus the output when its connected to the 5V of the PI is going to be very low and thus mess up readings.

I recommend you connect your power from the PI to the arduino's VCC as this is a regulated 5v and doesn't need to be regulated again.

I'm not entirely sure I understand. You state that it should need > 7.5V to work properly. But when I connect the power from the Pi to VCC of the Arduino; how many volts are we talking then? I thought that was 5V but maybe I'm wrong there? Which port from my cobbler should I use to connect to VCC?

From what I read on your edit you were say you connected the Pi 5V to the nanos Vin if that is so, you need to connect VCC - VCC

I don't know if this is a complete answer, but I can't comment yet.
The analogRead function in Arduino which is used by your sensor reads values from 0 - 5V. It divides the values between 0 and 5V in 1024 steps. So it returns a value between 0 and 1023. That is why it is multiplied by 5. It is easier to understand if the calculation is done in reverse order. Example:
analogRead returns 512, so that is on 1024 / 512 = 0,5th part of its range. Multiply that by 5.0 to get the actual voltage. 0.5 * 5.0 = 2.5. It is then divided by 6 to get the average.
I would also change the order of the calculation. The comments say that it calculates the average, but it doesn't it just adds the values. It does divide it by 6 eventually so that does not cause the error, but for readability it is generally good practice to let your code do what the comments say.

Thanks, as this doesn't solve the problem I won't mark is as an answer but it is valuable input anyway. The code comes from the sample, I'll improve it and redo the calculation, indeed seems to make more sense.

One other thing. Are you sure the connections are correct? Your results look a lot like when you are measuring a voltage divider at the wrong resistor. So try inverting your measurements, so: measuredValue = 1024 - analogWrite(pin);

Thank you, used the hint about inverting the measurements. Improved the reading but didn't solve the issue.

As a first approach, I'd collect a number of measurements from each of as many knowns as you can find or make, and plot them for a visual clue to the linearity or not (probably not) of the sensor's output vs. pH. You could try to eyeball-fit a curve to the data; interpolate linearly between sample points if you have enough of them; or run a least-squares approximation fit. The key is you'll need enough data - knowns - to make whatever approach you use give results accurate enough for your intended use. (Obviously this will be different if you just need to know if something is acidic or basic, or you're monitoring tropical fish tanks, etc.)
Update:
If your pH meter is good enough for the fish, and if your sensor is reliably repeatable and sensitive enough, why not check your meter against the two standards, then calibrate the sensor to your meter? Once you're happy with the result, lock down the screws with a dab of nail polish (it's not very tamper-proof but it will be tamper-evident). A pH 10.0 standard won't be very useful to you; at that extreme you'll already know the pH is out and you probably won't care about the exact value. You need your precision between the fish-tolerable limits, close to the pH goal.
In fact, if you trust your meter, you don't even need the standards. In that case you need only make up a few samples as you described, covering the pH range of interest, and use them to calibrate your sensor to the meter.

It's a fish tank indeed. I understand the approach, but I don't have many 'knowns', at the moment only 4.0 and 7.0 reference fluids. I could buy an additional 10.0 but wonder whether that will do it. Another thing I could try is to take tap water and a lemon (or some other acid) to increase the acidity step by step. I have a normal pH meter too which I could use to track the values. I guess the measurements would then tell me more. The issue I have with this is that this still doesn't tell me what the resistors are for and how it should work. Maybe it's just a faulty module, who knows.

I can't ask a question but make sure you're giving it enough power for the heating element, its not much but you never know try a separate power source if you are not.
Now you mentioned the nano, are you using a 3.3v nano or 5V nano?  (the regulator would have a 33 or 50 on it after a letter or two)  if 3.3V and assuming by example code they give the analog output is 5V you'll need a level shifter of sorts to map to 3.3V, then change the calculations to use 3.3 instead of 5 value.    if that's not the case and it's not power or connections then it may be broke or the probe etc.... there's a few variables.

Using a 5V nano. I've linked the module to both the 3.3V and 5V outputs, readings are the same.

USB power vs linked

Read it and use current Vcc instead of 5.0 in your code.
I have the same sensor and have the same problem. I'll be glad if you share full working code in this thread.

Please don't just post a link. The link might go down. If it has useful information in it, summarize it, or state it, here.


text:
How to simulate delay() to debounce mechanical button using millis()?
Im trying to use the millis() function as a replacement for the delay() function in order to debounce a mechanical button. This is for an electric drum kit I am building. Im using a teensy Arduino to send MIDI signals from the drum pads to an external music program. The mechanical button needs to be responsible for cycling through five different states which change the MIDI signal sent from each pad, thus changing the sound, as well as lighting up one of five LEDs on my drum pad so I know which state i'm in.  However I cant use delay() to debounce the button because that effects the efficiency of the drum pads, with some hits not being registered, latency etc.
Im trying to debug the code by just getting the LEDs to light up correctly when I press the button. This was the original code I wrote with the delay() function. This worked perfectly to debounce the button, but messed with my drum pads:
int but = 12;
int led0 = 7;
int led1 = 8;
int led2 = 9;
int led3 = 10;
int led4 = 11;

int ledCase = 0;
int butState = 0;
int oldButState = 0;

void setup()   {
pinMode(led0, OUTPUT);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
pinMode(led3, OUTPUT);
pinMode(led4, OUTPUT);
pinMode(but, INPUT_PULLUP);
}

void loop()    {

   oldButState = digitalRead(but);
   delay(10);
   butState = digitalRead(but);

   if (butState != oldButState && butState == LOW) {
     ledCase += 1;
     oldButState = butState;
   }

   if (ledCase > 4) {
    ledCase = 0;
   }

   Serial.println(ledCase);

switch (ledCase) {
case 0:
digitalWrite(led0, HIGH);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
break;
case 1:
digitalWrite(led0, LOW);
digitalWrite(led1, HIGH);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
break;
case 2:
digitalWrite(led0, LOW);
digitalWrite(led1, LOW);
digitalWrite(led2, HIGH);
digitalWrite(led3, LOW);
digitalWrite(led4, LOW);
break;
case 3:
digitalWrite(led0, LOW);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, HIGH);
digitalWrite(led4, LOW);
break;
case 4:
digitalWrite(led0, LOW);
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
digitalWrite(led4, HIGH);
break;
}
}

This is what I tried to use to replace the delay() function, but that hasn't worked. Note I added these lines in and removed the delay section:
unsigned long onTime;
unsigned long delayTime;

void setup() {
delayTime = millis() + 10;
}

void loop()    {
oldButState = digitalRead(but);
onTime = millis();
if (onTime >= delayTime) {
butState = digitalRead(but);
delayTime = millis() + 10;
}
}

Any pointers as to how I can make the millis() function work to debounce this would be would be very much appreciated, thank you :)

To better understand how you can do this it is good to understand first just what goes on when a button bounces.
It is, literally, bouncing - just like a ball when you drop it.  Due to the fact that it's either connected to ground or pulled up to +5V by the pullup resistor it's either going to be LOW or HIGH with very little time between when it's not in either state, so we can pretty much ignore the rise and fall times of the signal.  It's either connected to ground, or it's not connected to ground.  And we're only really interested in when it's connected to ground.
More importantly we're interested in how long it's been connected to ground for.
By remembering the time it transitioned from HIGH to LOW and then comparing that time to the current time you can know how long it has been connected to ground.  By noticing when it's no longer connected to ground and "forgetting" the time you remembered you can start counting afresh with the next transition from HIGH to LOW.
Take the following diagram for instance:

The blue line is the state of the button.  As you can see it starts HIGH, then it gets pressed to be LOW and bounces between HIGH and LOW a number of times before it settles on being LOW.
The red line is the difference between a timestamp that is set to be equal to millis() at the moment the button transitions from HIGH to LOW and the current millis() value, and is ignored when the button is HIGH.  As you can see the difference between that timestamp and the current millis() value steadily increases. Whenever the button bounces to the HIGH state it resets that difference, and it starts again with the next LOW transition.
When the button has finished bouncing there is nothing to change the state of the timestamp, so the difference keeps increasing.  Eventually that difference will pass a trigger point (the yellow line in this diagram) and at that point you can be fairly sure that the button has finished bouncing and you should react to it.
To translate that into some code, you may end up with something like this (untested):
// Two variables to store remembered state information - the time
// of the last HIGH-LOW transition and the previous state of the
//  button.
static uint32_t debounceTime = 0;
static uint8_t buttonState = HIGH;

// Check to see if the button has changed state
if (digitalRead(buttonPin) != buttonState) {
    // Remember the new state
    buttonState = digitalRead(buttonPin);
    // If the new state is LOW ...
    if (buttonState == LOW) {
        // ... then record the time stamp
        debounceTime = millis();
    } else {
        // ... otherwise set the time stamp to 0 for "don't care".
        debounceTime = 0;
    }
}

// If the time stamp is more than 0 and the difference between now and
// then is greater than 10ms ...
if (debounceTime > 0 && (millis() - debounceTime > 10)) {
    // ... set the time stamp to 0 to say we have finished debouncing
    debounceTime = 0;
    // and do whatever it is you need to do.
    digitalWrite(ledPin, HIGH);
}

There are various tweaks and additions that could be made to that method, but that gives you the basic idea of how you split the debouncing away from the reacting, and it's the results of the debouncing that you react to, not the button state itself.

Hey sorry I never got back to this, your advice really helped! I got it working in the end.

Actually, Majenko's diagram assumes the interplay of the pullup resistor forces the line back to a HIGH position (as quickly as the internal transistors can overpower the drop from the switch).  If the switch itself is mechanical with a pullup resistor (external or internal), then the only thing "bouncing" is the switch.  If you use a digital switch, the rise is much sharper without significant bounce.
A cheap and effective debouncing tactic is to add a capacitor in parallel with the switch.  The cap will drop to GND quickly as the switch drains the charge stored in the cap.  But the cap will take a while to recharge since its only source is through the resistor (during which time the mechanicals settle down).  (This looks much better in a diagram, but I haven't figured out how to draw on here yet.) I wish I could recommend values, but it really depends on the mechanicals of the switch and the certainty of the debounce desired--make everything HUGE and you're guaranteed no bounce, use values in between and you go on probabilities.  I usually start out with 0.1uF and vary it up or down until I get a balance between reliability and speed.
The main advantage is, of course, you use absolutely no computing time to debounce any number of switches.
Potential disadvantages:

Added hardware cost for each switch, making this technique less desirable in production scenarios
0/1 thresholds of input pins will vary across the manufacturing process, so one cap / input pin may have a different debounce time than another on an identical circuit.
Software debouncing schemes can note that the switch is pushed on the first drop to GND, where this hardware-only tactic relies on the last actual contact with GND.  As the switch ages, I've seen this delay exceed 50 mSec.
Since the bounce is mechanical at its core, bounce worsens over the life of the mechanical part (in this case the switch).  Typically, software can be fine-tuned easier than hardware. Often, however, swapping out a cap is easier than reflashing firmware.


text:
Using Johnny-five API with RFID Controller Shield
Is it possible to use the Adafruit PN532 NFC/RFID Controller Shield with the Johnny Five API? I've searched the depths of google and I'm unable to find anything so far. If it is possible, how can I go about this?
I'm using an Arduino Uno with this.

Have you tried routing through the serial port as suggested in https://github.com/rwaldron/johnny-five/issues/804 ? I might try this as I'm trying to do the same thing.


text:
Pro Micro Voltage regulator burned
I'm using Arduino Pro Micro (5v version) in one of my project for my car. The car's 12V +ve connected to RAW input of ProMicro and everything seems to work perfectly until I crank the ignition of my car.
Here's what actually happened, my circuit works perfectly fine when car's ignition is in ON state. However, as soon as I started my car the voltage dropped from 12v to between 9-10volt and the LG33 (SMD voltage regulator) burned out. Now, I want a good solution as what should I do now?
I have already LM2596 DC 3A Step-Down regulator. So should I use that to step-down 12v to 5v OR is there anything else I can do which might be a better solution?

What happened was the ignition caused massive spikes on the 12V power. You require an automotive grade regulator that can cope with spikes in excess of around 70V or more.
Your best bet is probably a car USB charger adapter since they are cheap and easy to get hold of.

You are right, I think using a car USB charger should do the trick to maintain a steady 5v current. I will try that over this weekend and let you know how it goes :) Thanks.

I cannot disclose the make, but I've seen a chinese brand send spikes of more than 100V to its car dashboard.


text:
Arduino Mega 2560 multiple slave via SPI
I'm new to Arduino and microcontroller . I want to connect my Arduino Mega to three slaves which Arduino Unos. I know that these slaves will share MISO, MOSI, and SCK lines. However, SS is unique to each slave.
For single slave, the SS is pin 53. So, for three slaves, which other two pins can I use as SS?
Thank you for your help.

Any you like. There's nothing magic about them, as long as you have the main SS pin as an output to ensure the SPI port is in master mode.

You can use any pin for the Slave Select. The SS pin on the Arduino is only used as SS when the arduino is an SPI slave, not (like in your case) when it's the master. The only thing you have to take care of is to not use the SS pin as an Input.
Just make sure the library you are using allows you to specify your own SS output pin.


text:
How to add new pins in the Arduino Due
I want to modify (extend) g_APinDescription array defined in the variant.cpp.
It is necessary for new pin addition. I want to use PB0-PB7 ports as an external interrupts.
I tried the following code:
g_APinDescription = (const PinDescription *) realloc(g_APinDescription, (103 * sizeof(const PinDescription)));

I have a compilation errors:

invalid use of array with unspecified bounds

I'm not C expert and don't know what is wrong here.
I want to use several pins which are unconnected on the DUE.
Usual read and write is simple to implement but if I want to use the interrupts then difficulties arrive.

Are you editing the variant or trying to modify it from within your sketch? How do you realloc a constant...?

I don't want to edit any existing files. I want to do everything from my sketch.

For mega seems it is easier:
ISR(EXT_INT0_vect)
{
}
I didn't find anything similar for due


text:
Arduino sending keystrokes via push-buttons. Proper bouncing and manually setting buttons?
I have a simple set of 8 push buttons wired to a Teensy 3.2 board (which uses Arduino via Teensyduino plugin). The 8 buttons are on pins 1-8 and their common ground line (one line soldered to each of them) is on the GND pin. I have code to get any one button working that works. It's currently set to make pressing the second button type "A."
I'd like to make push buttons 1 through 8 type out A,B,C...etc respectively as you press them. I've been told of two problems with my setup, the first being that copying the code for every button is a bad way to go about it and second that it's subject to bouncing issues (creates a keystroke once every 5 presses or so.) I'd also like to set this up so in the future I can write a 3rd party app that configures the keys based on the user's preference.
Adding those needs up I'm not sure where to go next. I'm beginner enough that I'm not sure how to properly incorporate the bounce class or if that's the right way to go given the needs.
Is a matrix the way to go or is there an elegant way to manual set each button and compensate for bounce? I'd really appreciate a small example if anyone has done this. Thanks~ Current code follows:
#define CHECK_EVERY_MS 20
#define MIN_STABLE_VALS 5

unsigned long previousMillis;
char stableVals;
char buttonPressed;

void setup() {
  // make pin 2 an input and turn on the
  // pullup resistor so it goes high unless
  // connected to ground:
  pinMode(2, INPUT_PULLUP);
  Keyboard.begin();
}

void  loop() {
    if ((millis() - previousMillis) > CHECK_EVERY_MS)
    {
        previousMillis += CHECK_EVERY_MS;
        if (digitalRead(2) != buttonPressed)
        {
            stableVals++;
            if (stableVals >= MIN_STABLE_VALS)
            {
                buttonPressed = !buttonPressed;
                stableVals = 0;

                if (buttonPressed)
                {
                    //Send an ASCII 'A',
                    Keyboard.write(65);
                }
            }
        }
        else
            stableVals = 0;
    }
}

-------
Edit: WORKING CODE FOLLOWS
/*  jw - 3 Nov 2015 - Program for button debounce demo
Ref: http://arduino.stackexchange.com/questions/17453/arduino-sending-keystrokes-via-push-buttons-proper-bouncing-and-manually-settin
*/

//--------------------------------------------------------
enum { sw0=3, sw1=4, sw2=5, sw3=6, sw4=7, sw5=8, sw6=9, sw7=10}; // Switchbutton lines
enum { nSwitches=8, bounceMillis=42}; // # of switches; debounce delay
struct ButtonStruct {
  unsigned long int bounceEnd;  // Debouncing-flag and end-time
  // Switch number, press-action, release-action, and prev reading
  byte swiNum, swiActP, swiActR, swiPrev;
};

struct ButtonStruct buttons[nSwitches] = {
  {0, sw0, 'A'},
  {0, sw1, 'B'},
  {0, sw2, 'C'},
  {0, sw3, 'D'},
  {0, sw4, 'E'},
  {0, sw5, 'F'},
  {0, sw6, 'G'},
  {0, sw7, 'H'}};
//--------------------------------------------------------
void setup() {
  for (int i=0; i<nSwitches; ++i)
    pinMode(buttons[i].swiNum, INPUT_PULLUP);
Keyboard.begin();
}
//--------------------------------------------------------
byte readSwitch (byte swiNum) {
  // Following inverts the pin reading (assumes pulldown = pressed)
  return 1 - digitalRead(swiNum);
}
//--------------------------------------------------------
void doAction(byte swin, char code, char action) {
  Keyboard.write(action);
}
//--------------------------------------------------------
void doButton(byte bn) {
  struct ButtonStruct *b = buttons + bn;
  if (b->bounceEnd) { // Was button changing?
    // It was changing, see if debounce time is done.
      if (b->bounceEnd < millis()) {
    b->bounceEnd = 0;    // Debounce time is done, so clear flag
    // See if the change was real, or a glitch
    if (readSwitch(b->swiNum) == b->swiPrev) {
      // Current reading is same as trigger reading, so do it
      if (b->swiPrev) {
        doAction(b->swiNum, 'P', b->swiActP);
      } else {
        doAction(b->swiNum, 'R', b->swiActR);
      }
    }
      }
  } else {  // It wasn't changing; but see if it's changing now
    if (b->swiPrev != readSwitch(b->swiNum)) {
      b->swiPrev = readSwitch(b->swiNum);
      b->bounceEnd = millis()+bounceMillis; // Set the Debounce flag
    }
  }
}
//--------------------------------------------------------
long int seconds, prevSec=0;
void loop() {
  for (int i=0; i<nSwitches; ++i)
    doButton(i);
}

You already have it working with one button. Just replicate it for all the others. This could be a good time to learn about arrays and loops.

Yes but it suffers from only sending a keystroke once ever 5-10 clicks, one of the things I'm trying to learn to fix.  The other is how to loop this correctly, as I can't find a tutorial online~

I'm not sure what you mean by “Is a matrix the way to go”, so will ignore that question.
Shown below is a way of using an array of structs (one of C's ways of organizing a collection of items) to keep data for several buttons, such that it's straightforward to use one subroutine to process each button the same way, using a for-loop to call the routine for each button.
Each element of the array buttons is a ButtonStruct, and each ButtonStruct contains five items: bounceEnd, swiNum, swiActP, swiActR, swiPrev, which respectively represent a debouncing-flag and end-time; a switch number [ie a pin number]; a code for action to take on a press; a code for action to take on a release; and previous state of button.  (In many special cases, some of these items will be irrelevant and you can leave them out of the ButtonStruct.)  The form b->x that is used in the doButton() routine says to access element x of the struct that b points to.
At the start of each loop() pass, doButton() is called once for each button.  It first tests if debouncing was underway for the button.  If so, it sees if enough time has gone by to suppose button bounce is over.  If so, it reads the button's state, and if different from previous state, does an action for whichever way the button changed.  (If the button state is unchanged after a debounce delay, the program supposes there was a glitch.)  If debouncing was not underway, the program checks if the button state is different from most recent pass.  In that case, it sets up a debounce test for the button.
The buttons are tested and debounced individually, as you can see in the sample output that is shown following the program.  (This program was tested on an Uno, with four independent buttons used in the test. Edit: Made corrections to handle 32-bit overflow, 2016.10.17)
/*  jw - 3 Nov 2015 - Program for button debounce demo
Ref: http://arduino.stackexchange.com/questions/17453/arduino-sending-keystrokes-via-push-buttons-proper-bouncing-and-manually-settin
*/

//--------------------------------------------------------
enum { sw0=8, sw1=9, sw2=10, sw3=11}; // Switchbutton lines
enum { nSwitches=4, bounceMillis=42}; // # of switches; debounce delay
struct ButtonStruct {
  unsigned long int bounceGo;   // Debouncing-flag and end-time
  // Switch number, press-action, release-action, and prev reading
  byte swiNum, swiActP, swiActR, swiPrev;
};

struct ButtonStruct buttons[nSwitches] = {
  {0, sw0, 'A','a', 0}, {0, sw1, 'B','b', 0}, {0, sw2, 'C','c', 0}, {0, sw3, 'D','d', 0}};
//--------------------------------------------------------
void setup() {
  for (int i=0; i<nSwitches; ++i)
    pinMode(buttons[i].swiNum, INPUT_PULLUP);
  Serial.begin(115200);
  Serial.println("Starting");
}
//--------------------------------------------------------
byte readSwitch (byte swiNum) {
  // Following inverts the pin reading (assumes pulldown = pressed)
  return 1 - digitalRead(swiNum);
}
//--------------------------------------------------------
void doAction(byte swin, char code, char action) {
  Serial.print("Switch ");
  Serial.print(swin);
  Serial.print(code);
  Serial.print(' ');
  Serial.print(action);
  Serial.print(" at t=");
  Serial.print(millis());
  Serial.println();
}
//--------------------------------------------------------
void doButton(byte bn) {
  struct ButtonStruct *b = buttons + bn;
  if (b->bounceGo) { // Was button changing?
    // It was changing, see if debounce time is done.
      if (millis() - b->bounceGo > bounceMillis) {
    b->bounceGo = 0;    // Debounce time is done, so clear flag
    // See if the change was real, or a glitch
    if (readSwitch(b->swiNum) == b->swiPrev) {
      // Current reading is same as trigger reading, so do it
      if (b->swiPrev) {
        doAction(b->swiNum, 'P', b->swiActP);
      } else {
        doAction(b->swiNum, 'R', b->swiActR);
      }
    }
      }
  } else {  // It wasn't changing; but see if it's changing now
    if (b->swiPrev != readSwitch(b->swiNum)) {
      b->swiPrev = readSwitch(b->swiNum);
      b->bounceGo = millis();   // Set the Debounce flag
    }
  }
}
//--------------------------------------------------------
long int seconds, prevSec=0;
void loop() {
  for (int i=0; i<nSwitches; ++i)
    doButton(i);
}

In the sample output below, a P line indicates a button press, detected at given millis() time, and an R line indicates a button release.   Observe, near the end, overlaps among separate button presses and releases.
Starting
Switch 8P A at t=2170
Switch 8R a at t=2322
Switch 9P B at t=2789
Switch 9R b at t=2969
Switch 10P C at t=3395
Switch 10R c at t=3562
Switch 11P D at t=4087
Switch 11R d at t=4260
Switch 11P D at t=6518
Switch 10P C at t=6961
Switch 8P A at t=7070
Switch 10R c at t=7112
Switch 11R d at t=7427
Switch 8R a at t=7598
Switch 10P C at t=8502
Switch 9P B at t=8642
Switch 10R c at t=8961
Switch 9R b at t=9054
Switch 9P B at t=9954
Switch 11P D at t=10073
Switch 8P A at t=10164
Switch 8R a at t=10215
Switch 9R b at t=10315
Switch 11R d at t=10354

This is great information...I'm just confused as using it exactly as shown displays nothing when I press any of my buttons...

For the moment, adjust the pin numbers in the enum { sw0=8, sw1=9, sw2=10, sw3=11} line, eg change to sw0=3, sw1=4, sw2=5, sw3=6 to test the buttons on pins 3, 4, 5, 6.  I don't have a teensy.  For the longer run, if your buttons are on  "pins 1-8" make 8 entries in buttons with the swiNum values from 1 to 8, and set nSwitch to 8.  Note, since pin 1 is TX1, having a button on it may conflict with Serial.

Aye I've set to try different pins even to get 4 work and nothing shows.  I attached some other switches I know work in case and still nothing.  I'm generally keeping the buttons' common wire on gnd but I've tried changing that around too with no avail

If it helps to see, here's a pic of my current simple wiring to test buttons on 3,4,5,6: http://tinyurl.com/px6rezv and here's the button set I'll eventually use (all have been tested working individually with my first bit of code) http://tinyurl.com/oajbpck

I should have mentioned I'm testing in notepad, not console. An update, I swapped all the serial commands for a simple Keyboard.write(action); which now prints Aa, Bb, etc... I think I follow this now, standby~

You are a marvel! I've posted the final code in an edit above. Please let me know if that is suitable or if I've done something problematic, but it works wonderfully!  Thanks so much for all your help!

Your code adaptation looks ok.  If you don't need to track button releases, for code cleanup you can remove swiActR from the struct, and the else {  doAction(b->swiNum, 'R', b->swiActR); } statement and the first two params to doAction().  (Or delete the def of doAction() and in place of  doAction(b->swiNum, 'P', b->swiActP); just say Keyboard.write(b->swiActP);)

Hey there! I know the question is closed, but I thought I'd ask in case you were still around. How do I pass something like a ctrl-z command into that? (for like a button press = undo).  I tried {0, sw0, KEY_LEFT_CTRL + 'Z'}, but I think that's banking on a mathematical operand and displays nothing.  KEY_LEFT_CTRL's hex value is 0x80. Is there a way to combine that with z inside the array there?

Might as well ask additionally, I'm curious also how to make a press and hold act like a regular keyboard. (Example, you press and hold the button, it delivers one keystroke, waits a moment, then starts repeating the stroke until you let go.

See the four  "Linked" questions in the right sidebar, above.   If they don't answer those two questions, you may need to start a new question.   . . . .


text:
Timer interrupt won't work if the ISR is not set
I am using an Arduino Mega 2560.
I have a code in a c file, that looks like this:
    #include <avr/io.h>             /* for DDRB, PORTB, etc. */
#include <util/delay.h>         /* for _delay_ms () */
#include <arduino.h>

int main(void){
  DDRB    |= ((1 << DDB7)); // Define pin 13 as output

  noInterrupts();

//set timer1 interrupt at 1Hz
  TCCR1A = 0;// set entire TCCR1A register to 0
  TCCR1B = 0;// same for TCCR1B
  TCNT1  = 0;//initialize counter value to 0
  // set compare match register for 1hz increments
  OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS12 and CS10 bits for 1024 prescaler
  TCCR1B |= (1 << CS12) | (1 << CS10);
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);
  interrupts();

  while(1){
        asm("nop");
  }
return 0;
}

  ISR(TIMER1_COMPA_vect)          // timer compare interrupt service routine
{
  PORTB ^= ((1 <<  PB7));   // toggle LED pin
  PINB |= _BV(7);
  PINB = PINB | _BV(7);
}

Which is called from an ino file, like this:
    extern "C"
 {
 void foo ();
 }

void setup ()
  {
  foo ();
  }  // end of setup

void loop ()
  {
  }  // end of loop

However, if I set up another timer interrupt (ex Timer Interrupt 0 or 2, the blink will stop happening, for some reason...
For example:
//set timer0 interrupt at 2kHz
  TCCR0A = 0;// set entire TCCR2A register to 0
  TCCR0B = 0;// same for TCCR2B
  TCNT0  = 0;//initialize counter value to 0
  // set compare match register for 2khz increments
  OCR0A = 124;// = (16*10^6) / (2000*64) - 1 (must be <256)
  // turn on CTC mode
  TCCR0A |= (1 << WGM01);
  // Set CS01 and CS00 bits for 64 prescaler
  TCCR0B |= (1 << CS01) | (1 << CS00);
  // enable timer compare interrupt
  TIMSK0 |= (1 << OCIE0A);

Now, the strangest part happens that if all the three (or just the same two) timer interrupts are set, and with everything defined in the INO file, it works fine...
//this code will enable all three arduino timer interrupts.
//timer0 will interrupt at 2kHz
//timer1 will interrupt at 1Hz
//timer2 will interrupt at 8kHz

//storage variables
boolean toggle0 = 0;
boolean toggle1 = 0;
boolean toggle2 = 0;

void setup(){

  //set pins as outputs
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(13, OUTPUT);

cli();//stop interrupts

//set timer0 interrupt at 2kHz
  TCCR0A = 0;// set entire TCCR2A register to 0
  TCCR0B = 0;// same for TCCR2B
  TCNT0  = 0;//initialize counter value to 0
  // set compare match register for 2khz increments
  OCR0A = 124;// = (16*10^6) / (2000*64) - 1 (must be <256)
  // turn on CTC mode
  TCCR0A |= (1 << WGM01);
  // Set CS01 and CS00 bits for 64 prescaler
  TCCR0B |= (1 << CS01) | (1 << CS00);
  // enable timer compare interrupt
  TIMSK0 |= (1 << OCIE0A);

//set timer1 interrupt at 1Hz
  TCCR1A = 0;// set entire TCCR1A register to 0
  TCCR1B = 0;// same for TCCR1B
  TCNT1  = 0;//initialize counter value to 0
  // set compare match register for 1hz increments
  OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS12 and CS10 bits for 1024 prescaler
  TCCR1B |= (1 << CS12) | (1 << CS10);
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);

//set timer2 interrupt at 8kHz
  TCCR2A = 0;// set entire TCCR2A register to 0
  TCCR2B = 0;// same for TCCR2B
  TCNT2  = 0;//initialize counter value to 0
  // set compare match register for 8khz increments
  OCR2A = 249;// = (16*10^6) / (8000*8) - 1 (must be <256)
  // turn on CTC mode
  TCCR2A |= (1 << WGM21);
  // Set CS21 bit for 8 prescaler
  TCCR2B |= (1 << CS21);
  // enable timer compare interrupt
  TIMSK2 |= (1 << OCIE2A);

sei();//allow interrupts

}//end setup

ISR(TIMER0_COMPA_vect){//timer0 interrupt 2kHz toggles pin 8
//generates pulse wave of frequency 2kHz/2 = 1kHz (takes two cycles for full wave- toggle high then toggle low)
  if (toggle0){
    digitalWrite(8,HIGH);
    toggle0 = 0;
  }
  else{
    digitalWrite(8,LOW);
    toggle0 = 1;
  }
}

ISR(TIMER1_COMPA_vect){//timer1 interrupt 1Hz toggles pin 13 (LED)
//generates pulse wave of frequency 1Hz/2 = 0.5kHz (takes two cycles for full wave- toggle high then toggle low)
  if (toggle1){
    digitalWrite(13,HIGH);
    toggle1 = 0;
  }
  else{
    digitalWrite(13,LOW);
    toggle1 = 1;
  }
}

ISR(TIMER2_COMPA_vect){//timer1 interrupt 8kHz toggles pin 9
//generates pulse wave of frequency 8kHz/2 = 4kHz (takes two cycles for full wave- toggle high then toggle low)
  if (toggle2){
    digitalWrite(9,HIGH);
    toggle2 = 0;
  }
  else{
    digitalWrite(9,LOW);
    toggle2 = 1;
  }
}

void loop(){
  //do other things here
}

Is anybody able to explain why it works in the first case, doesn't work in the second, and in the third, it works as well?

I found out that it's not enough to just define the interrupts, there must also be an ISR method with the compare vector...
  ISR(TIMER0_COMPA_vect)          // timer compare interrupt service routine
{
  PORTB ^= ((1 <<  PB6));   // toggle LED pin
  PINB |= _BV(6);
  PINB = PINB | _BV(6);
}

There was no error at compile, though.

there must also be an ISR method with the compare vector - that's correct - you have told the processor to jump to an ISR vector, and the default vector jumps to the start of your program. There was no error at compile, though. - you have not made any syntactical errors.


text:
Horse racing game
Basically i would like to create a horse racing game, (5 horses starting all to a point A and finishing in a random position to a point B).
I did an animated GIF for you to understand it more clearly :
https://i.stack.imgur.com/oOZvB.jpg
This exactly what i want to do, but in real.
I was thinking of using 5 motors (one for each horse) with a string they pull where the horse is attached on it (like this : https://www.youtube.com/watch?v=NjuoCS9-pCY), and to create randomness at each race, do a random speed for each motors every 1 or two seconds and then stop when each horse hit the finishing line (by pushing a sensor ?). Finally when all horses hit the finishing line, the motors goes backward and get the horses back to the start line.
The horses will be tiny like 1 inch (2.5cm) and the distance from start to finish line will be like 20inch (50cm) and i need the race to last at least 5-10 sec so motors don't need to turn too fast.
I don't know if it is the best way or if it is even possible (and how ? with what components?)
I have been searching for solutions to my project but didn't found anything suitable yet so here i am..
Thank you a lot for you help

What is your question exactly? You want a solution to your project (would that be "assignment") - is that it?

I'd use some simple stepper motors for that. Using those, you will always know where all the horses are precisely, have precise control of speed, and negating the use of buttons at the finish.

Thanks @Gerben this is a start :) and yes nick i'm looking for help to know what component to use

If it is going to be tiny, I would use continuous rotation servos and rubber belts. They are nice because you dont need motor drivers, unlike stepper motors. Also they consume a lot less power than stepper motors, so you may not need to attach them to external power (not just the arduino 5v). However, because you can not control how far they move, you will need buttons at the end of the race. I think you can get them from Adafruit.


text:
Circuit doesn't work when multimeter/current meter is attached
I'm working on a battery-powered data logger, using a bare Atmega 328. I'm using sleep between sensor readings, via the Narcoleptic library. Everything seems to work fine, until I connect my multimeter to check on the current.
The multimeter uses manual range-setting (i.e., not autoranging). If I set the multimeter to the 0-20 mA range, I can see that my idle current is about 0.250 mA, but the upper value is off-scale. If I try to get a reading on the 0-200 mA range, the circuit misbehaves, never goes into sleep, and doesn't record any data. The current stays constant somewhere around 14-20mA.
Do I need to do something special to accurately measure current in the range of 0.25-40+mA? Or do I need a different kind/quality of multimeter?
My multimeter is a $15 digital unit from Circuit Test, model DMR-1100A.

Multimeters have something called a "burden voltage". See this PDF: uCurrent - A professional precision current ... - EEVblog.
Also see Dave Jones' video: µCurrent
Meters measure current by dropping voltage over an internal resistor, and measuring the drop. By definition therefore, there is a voltage drop, which is the "burden voltage".

the circuit misbehaves, never goes into sleep, and doesn't record any data

If you put a voltmeter on the processor side of the ammeter you will probably find that the voltage going into your processor is somewhat less than you think. That would account for the misbehaving.
One possible approach is to crank up the voltage from your power source, checking the voltmeter to see that it reaches the expected voltage on the processor side of the ammeter, however in a circuit which might turn on and off (ie. sleep) this voltage might jump around (depending on the current) so this should be done with caution (to not exceed the maximum processor voltage).

Or do I need a different kind/quality of multimeter?

A higher quality meter may well help - watch that video and look at the PDF to see what I am talking about. My meters (which cost more than $15) don't have this problem to the same extent.

FWIW, I observe similar issues when trying to measure the current of an Arduino Mini Pro 3.3V using a probably cheap multimeter. When I set the range to 20 mA the display alternates between 0.5 and -0.5 mA depending on whether the device is in POWER-DOWN or in a mixture of IDLE/ACTIVE mode. When I set the range to 2000 µA the device shows very non-deterministic behavior. Apparently in that range, the voltage drop is too high then. I understand the voltage drop part, but I'm a bit surprised about the display alternating between positive/negative values.

If your tester has autorange function, you have to disable it, as it can interfere with normal operations by changing the internal shunt resistor.
Did you configure the meter as current meter, DC, connected in series between the power supply/battery and the rest of the circuit?
The tester might give a poor reading at low current values but it shouldn't interfere(much) with the circuit itself.

Yes, I set it to current meter, either the 0-20 or 0-200 range, it doesn't do autoranging. I insert it between the VCC of my USB/FTDI cable and the power bus of the breadboard. In the low range (0-20) the circuit works, so I'm reasonably confident I'm attaching & using it properly.


text:
Arduino UNO with Sparkfun MP3 Trigger
I have a basic mp3 trigger with arduino uno setup:
Trigger - https://www.sparkfun.com/products/11029
Arduino Uno code:
#include <MP3Trigger.h>

//  Script Function:  RobertSonics mp3trigger (v2) paired with an Arduino UNO
//
//  Jumper Connections:   UNO  ------  mp3trigger (v2)
//             (UNO RX)     0  ------  TX
//             (UNO TX)     1  ------  RX
//             (Ground)   GND  ------  GND
//           (+5 volts)    5v  ------  USBVCC

#include <SoftwareSerial.h>
void setup(){
    Serial.begin(38400);    // Standard for mp3trigger
    Serial.print("t");
    Serial.write(1);
    delay(50000);
}

void loop()
{

}

I can't get it to play any tracks. The response in the Serial monitor just says tt

So, from the beginning:

Have you got data on you SD card and is it is FT16 or FAT32 format?
Is the MP3 status light giving any indication of life?
Does the MP3 card detect when you start it up without the SD card in (One long flash).
Do you have a data file named "001SomethingOrOther.MP3"?
Have you tried the command "v" 0x00?
Have you tried the commands "S0" and "S1"?
Have you looked at the sample data on http://robertsonics.com/mp3-trigger-support/?

Hope that helps, an please post your finding, because mine arrives next week :)

Finally I got it working yesterday, and by accident!!!! Sorry it was not sooner, hope you had better luck with it. In any case if anyone wants to know what I did, you can read about it here.
https://forum.sparkfun.com/viewtopic.php?f=14&t=44292


text:
Regulation of the temperature using PID
I'm making a control system for the heating of a plate using a PID control.
the goal is to regulate the temperature of the plate by changing the power dissipated by the resistance. By using a sensor I read the temperature  of the plate and is then used as the input in the PID control.
I programmed also a signal wave square for the PWM.
but the thing I don't understand is what I'm exactly supposed to do with the output signal I receive.
and I cannot connect between the PWM and the PID.
Code of the square signal:
void setup()
{
  pinMode(9, OUTPUT);
}
void loop()
{
   // phase haute
   digitalWrite(9,HIGH);
   delay(30);
   // phase basse
   digitalWrite(9,LOW);
   delay(70);
   //ton+toff = 0.1;
//   ton = 0.1*Output;
}

Code of PID and the sensor
/********************************************************
 * PID Basic Example
 * Reading analog input 0 to control analog PWM output 3
 ********************************************************/

#include <PID_v1.h>

int val;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;

//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint,2,5,1, DIRECT);

void setup()
{
  Serial.begin(9600);
  //initialize the variables we're linked to
  Input = analogRead(1);
  Setpoint = 37; //temperature a reguler

  //turn the PID on
  myPID.SetMode(AUTOMATIC);
}

void loop()
{
  val = analogRead(1);
  float mv = ( val/1024.0)*5000;
  float Input = mv/10;
  myPID.Compute();
  analogWrite(3,Output);
  Serial.print("input temperature is :");
  Serial.println(Input);
  delay (1000);
//  delay(1000);
  Serial.print("output is :");
  Serial.println(Output);
  delay(1000);
}

Thank you in advance

The default output of the PID is bound between 0 and 255, corresponding to the n/255 fraction of the output.  You can push the output directly into a PWM-controlled pin with analogWrite(pin,Output), as in your code, but maybe add an pinMode(3,OUTPUT); or you could use the fraction to control a slower frequency like in your first chunk of code.  delay(Output);...delay(255-Output);

A PID only has one input and one output. In your case, the input will be the temperature. The use of the arduino would be to process the raw data of the temperature sensor and relay the temperature to the PID. Depending on the make and model of the PID, there could be certain transfer protocols you must adhere to. There are most likely open source libraries that will take care of transferring the data properly.
Your PID is the piece of hardware that will "decide" when it is appropriate to turn the heater on and off, therefore it shall be responsible for driving the heater. That is what the output of the PID is responsible for.
Lastly, your PID has a set point. In your case, the set point would be the desired max temperature of the plate. This set point is set and altered manually through user input.
On a side note, if this is a personal project or a non deliverable, I'd recommend not using a PID. Try processing and analyzing all of the data exclusively on the Arduino, as it would be a challenging and rewarding task.


text:
Arduino W5100 AVR
I'm trying to use a W5100 Arduino Ethernet Shield on a ATMega2560 using avr code.
There exists a library written in C, which should work http://www.seanet.com/~karllunt/w5100_webserv.zip from http://www.seanet.com/~karllunt/w5100_library.html
The w5100_webserv.c should be a working example for an ATmega644p. He mentions that the four callback functions should be modified, namely my_select(), my_deselect(), my_xchg() and my_reset()
The w5100_webserv.c also contains the following definitions for SPI_PORT/DDR CS_PORT/DDR/BIT and RESET_PORT/DDR/SPI:
/*
*  Define the SPI port, used to exchange data with a W5100 chip.
*/
#define SPI_PORT     PORTB                /* target-specific port containing the SPI lines */
#define SPI_DDR      DDRB                /* target-specific DDR for the SPI port lines */

#define CS_DDR        DDRD                /* target-specific DDR for chip-select */
#define CS_PORT     PORTD                /* target-specific port used as chip-select */
#define CS_BIT        2                    /* target-specific port line used as chip-select */

#define RESET_DDR   DDRD                /* target-specific DDR for reset */
#define RESET_PORT    PORTD                /* target-specific port used for reset */
#define RESET_BIT    3                    /* target-specific port line used as reset */

I've changed it to the following according to what i think the ATmega2560's datasheet specifies
/*
 *  Define the SPI port, used to exchange data with a W5100 chip.
 */
#define SPI_PORT     PORTB                /* target-specific port containing the SPI lines */
#define SPI_DDR      DDRB                /* target-specific DDR for the SPI port lines */

#define CS_DDR        DDRB                /* target-specific DDR for chip-select */
#define CS_PORT     PORTB                /* target-specific port used as chip-select */
#define CS_BIT        10                  /* target-specific port line used as chip-select */

#define RESET_DDR   DDRB                /* target-specific DDR for reset */
#define RESET_PORT    PORTB                /* target-specific port used for reset */
#define RESET_BIT    20                   /* target-specific port line used as reset */

Furthermore, in the main(), there are also specific code for the AT644p:
/*  * Initialize the ATmega644p SPI subsystem */
CS_PORT |= (1<<CS_BIT);                                    // pull CS pin high
CS_DDR |= (1<<CS_BIT);                                    // now make it an output

SPI_PORT = SPI_PORT | (1<<PORTB4);                        // make sure SS is high
SPI_DDR = (1<<PORTB4)|(1<<PORTB5)|(1<<PORTB7);            // set MOSI, SCK and SS as output, others as input
SPCR = (1<<SPE)|(1<<MSTR);                                // enable SPI, master mode 0
SPSR |= (1<<SPI2X);                                        // set the clock rate fck/2

I've changed it to the following according to what i think the ATmega2560's datasheet specifies
/*
 *  Initialize the ATmega2560 SPI subsystem
 */
CS_PORT |= CS_BIT;                                    // pull CS pin high
CS_DDR |= CS_BIT;                                    // now make it an output

SPI_PORT = SPI_PORT | (1<<PORTB0);                        // make sure SS is high
SPI_DDR = (1<<PORTB0)|(1<<PORTB2)|(1<<PORTB1);            // set MOSI, SCK and SS as output, others as input
SPCR = (1<<SPE)|(1<<MSTR);                                // enable SPI, master mode 0
SPSR |= (1<<SPI2X);                                        // set the clock rate fck/2

Lastly i've changed the my_reset() function:
    void  my_reset(void)
    {
        RESET_PORT |= RESET_BIT;                            // pull reset line high
        RESET_DDR |= RESET_BIT;                            // now make it an output
        RESET_PORT &=~RESET_BIT;                            // pull the line low
        _delay_ms(5);                                            // let the device reset
        RESET_PORT |= RESET_BIT;                            // done with reset, pull the line high
        _delay_ms(10);                                            // let the chip wake up
    }
I am not sure whether my changes are 100 % correct and i don't know what changes needs to be done to my_select() my_deselect and my_xchg. I hope someone can suggest som corrections.
Thanks in advance.

Have you actually tried it? Does it work?

Yes. I've compiled it several times using avr-gcc and afterwards used avrdude to transfer it to the atmega2560.
To ensure that there isn't anything wrong with the board, i've tested with a simpel blinking example.

And what did your tests reveal? So far you have told us everything except if it actually worked or not, and if not, in what way did it not work?

None of my tests revealed anything. I haven't been able to connect to the specified IP-address at all.
So well it did not work in anyway. It compiles without problems, it can be transfered without problem. But the webserver is not running on the Atmega2560.

If you have any idea what i need to change in the PORTS and DDR registers, please say so :).

I've managed to specify the correct ports and bits in order to make the library function on the Arduino ATmega2560 using their Ethernet Shield.
The SPI port definitions has to be changed to the following:
#define SPI_PORT    PORTB               /* target-specific port containing the SPI lines */
#define SPI_DDR     DDRB                /* target-specific DDR for the SPI port lines */

#define CS_DDR      DDRB                /* target-specific DDR for chip-select */
#define CS_PORT     PORTB               /* target-specific port used as chip-select */
#define CS_BIT      4                   /* target-specific port line used as chip-select */

#define RESET_DDR   DDRB                /* target-specific DDR for reset */
#define RESET_PORT  PORTB               /* target-specific port used for reset */
#define RESET_BIT   8                   /* target-specific port line used as reset */

The section about the AT644p in the main() function has to be changed to the following:
/*
 *  Initialize the ATmega2560 SPI subsystem
 */
// Initial SPI Peripheral
SPI_DDR = (1<<PORTB2)|(1<<PORTB1)|(1<<PORTB0);

// CS pin is not active
SPI_PORT |= (1<<CS_BIT);

    // Enable SPI, Master Mode 0, set the clock rate fck/2
SPCR = (1<<SPE)|(1<<MSTR);
SPSR |= (1<<SPI2X);

//Disable the SD card
DDRB |= (1<<CS_BIT);


text:
graph of a function Arduino
I am making a temperature circuit with arduino.
is there any way to plot the value of the temperature in a graph using arduino?
thank you very much in advance

Yes, there are many many ways of doing it. What kind of graph do you want, and where do you want to display it?

On what? A TFT screen? LCD screen? On your computer? A slice of processed cheese?  And do you want to see live data or analyse historical data? You need to give specifics or we can't help you.

yes, on my computer. and I want to see Data in real time

Do you want to program your own graphing system or use an off-the shelf product?

Did you just casually drop the Matlab requirement in your comment? If so, please edit you question to reflect this requirement. Otherwise, if you want something simple, use processing to graph the data

Yes you can use the Plot menu command in the new Arduino 1.6.6 or you can use the Visual Micro debugger to create graphs in Visual Studio

I tried with new arduino 1.6.6 but I don't know how to use the plotter. in the menu i found Serial plotter, can you tell me how can I do to plot my function ?

it works. because if we want to plot we cannot write;
Serial.print("Output is :"); Serial.println(Output);  so we have to write just :
Serial.println(Output);

Yes that's right. In visual micro you can have multiple values with descriptions without editing your code. In Arduino you have simpler system and must change your code to use Serial.println(number) :)


text:
Alternative to patching core library source and header files
I am following a DIY guide that requires me to patch two arduino core library files: HID.cpp and USBAPI.h. This is not really practical for many reasons. I am not a native C programmer, but I am sure there are better ways to achieve the same without messing directly with system files. How can I override system library files without modifying the originals?

That all depends on what the modifications are you need to do...

@Majenko principally it adds a third device description (HID Remote) to the two devices that are described in those two files (Keyboard and Mouse). I can upload a diff.

Can't you just place a copy in the sketches folder and alter this local copy?

Unfortunately there really isn't any way of doing that other than modifying those files. The good news is that it is perfectly viable to make the modifications under a different "core" and then amend boards.txt with the core containing the modifications.