text:
How to use Multiple MPU9250 to Arduino Lilypad
Is it possible to connect more than one or to be specific 5 MPU9250 into 1 Arduino lilypad? How will I set the addresses, and where should I put the pins for SDA and SCL? I hope someone out there could help me on this project.
Cheers!
What if I have this working codes, how will I edit this to connect more than two MPU9250? Please guide me. Thanks.
 #include <Wire.h>
 #include <TimerOne.h>

 #define    MPU9250_ADDRESS            0x68

 #define    MAG_ADDRESS                0x0C

 #define    GYRO_FULL_SCALE_250_DPS    0x00
 #define    GYRO_FULL_SCALE_500_DPS    0x08
 #define    GYRO_FULL_SCALE_1000_DPS   0x10
 #define    GYRO_FULL_SCALE_2000_DPS   0x18

 #define    ACC_FULL_SCALE_2_G        0x00
 #define    ACC_FULL_SCALE_4_G        0x08
 #define    ACC_FULL_SCALE_8_G        0x10
 #define    ACC_FULL_SCALE_16_G       0x18

 // This function read Nbytes bytes from I2C device at address Address.
// Put read bytes starting at register Register in the Data array.
void I2Cread(uint8_t Address, uint8_t Register, uint8_t Nbytes, uint8_t*      Data)
{
// Set register address
Wire.beginTransmission(Address);
Wire.write(Register);
Wire.endTransmission();

// Read Nbytes
Wire.requestFrom(Address, Nbytes);
uint8_t index=0;
while (Wire.available())
Data[index++]=Wire.read();
}

// Write a byte (Data) in device (Address) at register (Register)
void I2CwriteByte(uint8_t Address, uint8_t Register, uint8_t Data)
{
// Set register address
Wire.beginTransmission(Address);
Wire.write(Register);
Wire.write(Data);
Wire.endTransmission();
}

// Initial time
long int ti;
volatile bool intFlag=false;

// Initializations
void setup()
{
// Arduino initializations
Wire.begin();
Serial.begin(115200);

// Set accelerometers low pass filter at 5Hz
I2CwriteByte(MPU9250_ADDRESS,29,0x06);
// Set gyroscope low pass filter at 5Hz
I2CwriteByte(MPU9250_ADDRESS,26,0x06);

// Configure gyroscope range
I2CwriteByte(MPU9250_ADDRESS,27,GYRO_FULL_SCALE_1000_DPS);
// Configure accelerometers range
 I2CwriteByte(MPU9250_ADDRESS,28,ACC_FULL_SCALE_4_G);
 // Set by pass mode for the magnetometers
 I2CwriteByte(MPU9250_ADDRESS,0x37,0x02);

 // Request continuous magnetometer measurements in 16 bits
 I2CwriteByte(MAG_ADDRESS,0x0A,0x16);

 pinMode(13, OUTPUT);
 Timer1.initialize(10000);         // initialize timer1, and set a 1/2   second period
 Timer1.attachInterrupt(callback);  // attaches callback() as a timer overflow interrupt

 // Store initial time
 ti=millis();
 }

 // Counter
 long int cpt=0;

 void callback()
  {
  intFlag=true;
  digitalWrite(13, digitalRead(13) ^ 1);
  }

  // Main loop, read and display data
  void loop()
  {
  while (!intFlag);
  intFlag=false;

  // Display time
  Serial.print (millis()-ti,DEC);
  Serial.print ("\t");

   // _______________
  // ::: Counter :::

   // Display data counter
  //  Serial.print (cpt++,DEC);
 //  Serial.print ("\t");

  // ____________________________________
  // :::  accelerometer and gyroscope :::

 // Read accelerometer and gyroscope
 uint8_t Buf[14];
 I2Cread(MPU9250_ADDRESS,0x3B,14,Buf);

 // Create 16 bits values from 8 bits data

// Accelerometer
int16_t ax=-(Buf[0]<<8 | Buf[1]);
int16_t ay=-(Buf[2]<<8 | Buf[3]);
int16_t az=Buf[4]<<8 | Buf[5];

// Gyroscope
int16_t gx=-(Buf[8]<<8 | Buf[9]);
int16_t gy=-(Buf[10]<<8 | Buf[11]);
int16_t gz=Buf[12]<<8 | Buf[13];

 // Display values

// Accelerometer
Serial.print (ax,DEC);
Serial.print ("\t");
Serial.print (ay,DEC);
Serial.print ("\t");
Serial.print (az,DEC);
Serial.print ("\t");

// Gyroscope
Serial.print (gx,DEC);
Serial.print ("\t");
Serial.print (gy,DEC);
Serial.print ("\t");
Serial.print (gz,DEC);
Serial.print ("\t");

// _____________________
// :::  Magnetometer :::

// Read register Status 1 and wait for the DRDY: Data Ready

uint8_t ST1;
do
{
 I2Cread(MAG_ADDRESS,0x02,1,&ST1);
}
while (!(ST1&0x01));

// Read magnetometer data
uint8_t Mag[7];
I2Cread(MAG_ADDRESS,0x03,7,Mag);

// Create 16 bits values from 8 bits data

// Magnetometer
int16_t mx=-(Mag[3]<<8 | Mag[2]);
int16_t my=-(Mag[1]<<8 | Mag[0]);
int16_t mz=-(Mag[5]<<8 | Mag[4]);

// Magnetometer
Serial.print (mx+200,DEC);
Serial.print ("\t");
Serial.print (my-70,DEC);
Serial.print ("\t");
Serial.print (mz-700,DEC);
Serial.print ("\t");

// End of line
Serial.println("");
//  delay(100);
 }

Is it possible to connect more than one or to be specific 5 MPU9250 into 1 Arduino lilypad?

Yes, that is possible with both SPI and I2C. With SPI you will need MOSI(11), MISO(12), SCK(13), and CSn where CSn is CS0..CS4 are digital pins in output mode for chip select.
With I2C the following pins are needed SDA(A4), SCL(A5), and CSn. The chip select pin is connected to AD0 on the device. AD0 is used for the lowest bit in the I2C address. Addressing is achieved by connecting AD0 to CSn and keeping all high except the one that is addressed. The I2C address is the same for all access. The CSn pin defines which device will response.
The example code below uses the lower address and chip select is put low for the selected device.
// Chip select pin device#0
const int CS0 = 4;
...
void setup()
{
  ...
  // Initiate chip select pin for device#0
  pinMode(CS0, OUTPUT);
  digitalWrite(CS0, HIGH);
  ...
}
...
void loop()
{
   ...
   // Select device#0
   digitalWrite(CS0, LOW);
   MPU9250_someFunction();
   digitalWrite(CS0, HIGH);
   ...
}

How will I set the addresses, and where should I put the pins for SDA and SCL?

SDA is connected to A4 and SCL to A5.
Using the above given example code (from the question) a rewrite of the I2Cread function could be:
// This function read Nbytes bytes from MPU9250 device with chip select pin.
// Put read bytes starting at register Register in the Data array.

void MPU9250_read(uint8_t CS, uint8_t Register, uint8_t Nbytes, uint8_t* Data)
{
  digitalWrite(CS, LOW);

  // Set register address
  Wire.beginTransmission(MPU9250_ADDRESS);
  Wire.write(Register);
  Wire.endTransmission();

  // Read Nbytes
  Wire.requestFrom(Address, Nbytes);
  uint8_t index = 0;
  while (Wire.available()) Data[index++] = Wire.read();

  digitalWrite(CS, HIGH);
}
...
// Read magnetometer data from device#3
uint8_t Mag[7];
MPU9250_read(CS3, 0x03, 7, Mag);

Cheers!

Please see above @MikaelPatel I posted the code that I am using from the internet.

What was the question? Do you want to know how to change that? It is really bad. There must be better drivers to change. And if we do that we should make that shared. A possible fork on github on a good driver?

I have added a rewrite of I2Cread to give you a hint how to do this.

where should I put the pins for SDA and SCL?

Same as on a Uno:

SDA is on pin A4
SCL is on pin A5

Can you suggest me some links that can help me learn more about SPI?

I have an SPI page and also one about I2C.
There is also a page about SPI on this site: How do you use SPI on an Arduino?
If you want to use 5 devices, it sounds like Majenko's recommendation is good: Use SPI. You would share MOSI/MISO/SCK between all devices (D11/D12/D13), and give each one a separate SS (slave select) line.

Thank you for responding to my concern. Can I ask you if you have the existing codes already on it? @NickGammon

No I don't, sorry. There are dozens of Arduino models these days, and hundreds, if not thousands, of things you can connect to them. I don't happen to have a Lilypad and 5 x MPU9250 devices. However the links I provided should help you to get started in writing your own.

Please see above @NickGammon I posted the code that I am using from the internet.

According to the datasheet the MPU-9250 can work in either I2C or SPI mode.
When it is in SPI mode you can connect up as many MPU-9250s as you have spare IO pins.  With SPI the clock and data lines are all shared, and each slave device has its own Slave Select line.
In I2C mode it is possible to only use 2 devices at once - the AD0 pin configures which is which device (connect it to GND or VCC to identify the two devices).
Interestingly the MPU-9250 does include an I2C master module for connecting other sensors to it. Theoretically it should be possible to connect the master port of an MPU-9250 to two other MPU-9250s, and each of those could connect to a further two MPU-9250s each, and so on and so forth in a huge tree.  However the programming of such an environment would be an absolute nightmare and not something I would like to undertake.
So in summary: use SPI mode, it's simpler.

Thank you for giving me that idea. It helped me enlighten my mind about this project. @Majenko Can you suggest me some links that can help me learn more about SPI, or some working codes which can be a stepping stone to start making the said project work? Cheers!

https://www.arduino.cc/en/Reference/SPI http://playground.arduino.cc/Code/Spi

Please see above @Majenko posted the code that I am using from the internet.

If you use I2C, you can use an I2C multiplex chip to handle the arbitration to handle lots of MPU-9250s.  I had a setup with 6x of them going.  I did find however, that the amount of CPU time that it takes for I2C communication is high, so once you get in to that many 9250s, you don't have much CPU time left over for other things.  Using SPI is a bit trickier to get going, but it is wicked fast and also lets you take advantage of the FIFO buffer on the 9250s.
Majenko mentioned using the I2C master functionality on the 9250 to daisy chain - I had also tried that approach before I tried the I2C multiplexer.  I have to say it was a horrible experience.  When you use that I2C master function, you are actually programming the advanced functionality of the 9250 instead of using the Arduino coding in C.  Once it all starts working (if it does), it acts quite flaky.  That functionality on the chip was really designed to enable using an external magnetometer on the 6250 to get 9dof.  Any more complex use than that gets hairy with the interchip timing, and initializing on startup is also rough.
Final answer - put in the time to learn how to use the SPI bus as mentioned in some of the other answers.  Once you get through the learning curve, it can run at up to 20khz communication speed.  SPI is designed for high speed communication.  I2C is designed to be easier to use but for things with lower update rates.


text:
What could I use to vary the temperature of a Heating Pad?
Could I get something like this, a 12v silicone heating pad, and vary its temperature with an arduino somehow?
http://www.banggood.com/Waterproof-Silicone-Flexible-Heating-Pad-6060MM-DC-12V-10W-p-972464.html
My grand plan is to put temperature sensors on it and make it hit a certain temperature, and make it hotter/cooler to try and reach a target temperature.

Specifically, could I use something like this? http://www.banggood.com/MOSFET-Tube-Driver-Module-For-Arduino-SCM-ARM-Raspberry-Pi-p-938040.html

In principle, I don't see any problems. Your heating pad uses 12V and 10W, which means it would be consuming slightly less than one amp of current. The MOSFET you linked can go up to 5A (needing a heat sink with over 1A).
You could use PWM (there are 6 pins on a Uno that can do that) to provide pulse-width modulation to control the amount of output you give to the heater.
You would, of course, need to measure the heat of the device to work out when to adjust the PWM output. You might look up using a PID algorithm to adjust the PWM output depending on the sensed heat input.

References:

pid
pwm
mosfet
sensors

If you want to control the temperature very accurately, try connecting a shunt resistor (value: <0.1 ohm) in series with the heater. Use an op-amp to amplify the voltage difference on its two terminals and read with Arduino the resulting value. You can calculate with it the actual current and therefore the actual resistance of the heating pad.
The value changes with temperature, you can use the resistance value to measure the surface temperature of the heating pad.

source: Stack Exchange

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

sort: votes


text:
PID tuning help
I'm currently working on a self-balancing robot with an Arduino Uno and a 10DOF ADXL345 sensor. Everything is going fine until I got to this PID tuning part. I've read about it several times but I'm unable to get the desired results. Can somebody give a detailed guide on PID tuning? Thank you.

How tall is it? How fast do the measurements and adjustments have to happen to keep things from falling down? How fast are they happening?  Where is the code?

Maybe you can help yourself with this tutorial for PID line follower robot. I successfully tuned my PID for line following and had some success with PID for wall following with sonar.

Thanks. Let me try it first. I'll tell you when it works :)

That tutorial looks pretty good.  One difference from most discussions and usages of the normal Arduino PID control is that it focuses on error by putting the setpoint outside the PID algorithm as "Tp", so you can use the arduino PID like this if you do those calcs outside. And "I just take the maximum value we want to send to the motor's power control (100) and divide by the maximum useable error value. For our line following robot we've assumed the maximum error is 5 so our guess at Kp is 100/5=20. When the error is +5 the motor's power will swing by 100 units." is the crux of PID tuning.

Thanks man. Didn't get the desired results yet but I'm a lot closer now. The robot is much more stable now. Thanks man

In real life there is no set equation to find the PID values. At best you'll get close with equations and then need to tune the parameters.
For anyone into PID loops have a read of this.
I've found it to be excellent.
My advice is to:

only use P
set I & D to 0
get it and good as you can by trial and error
add I and trial it too

D is for experts really and may cause weird/undesirable jitter.

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


text:
Arduino declaring class in h and cpp file Undefined Reference
I am trying to compile my project, but unfortunately get errors.
I created class and separated implementation and declaration (cpp file and h file)
Here they are
sensor.h
#ifndef SENSOR_H
#define SENSOR_H
#include <stdint.h>
#include "Arduino.h"
// Sensor types
enum SensorType {
  ANY_SENSOR,
  UNKNOWN_SENSOR,
  WATER_SENSOR,
  TEMPERATURE_SENSOR,
  VIBRATION_SENSOR,
  INTERCOM_SENSOR,
  HUMIDITY_SENSOR,
  PIR_SENSOR,
  SOUND_SENSOR,
  LIGHT_SENSOR
};
class Sensor {
  public:
  // Variables declaration
    uint32_t sensorId;
    SensorType sensorType;
    float currentValue;
    bool isEnabled;
    float criticalLowerLevel;
    float criticalUpperLevel;
   // Methods declaration
    Sensor();
    Sensor(uint32_t id,SensorType type,long currentValue,bool isEnabled,long lower,long upper);
    String toString();
    bool isCriticalLevelRised() {
      return (this->currentValue >= this->criticalUpperLevel || this->currentValue <= this->criticalLowerLevel);
    };
    void enable(bool enable);
    void toggle();
    static String convertSensorTypeToString(SensorType sensorType);
};

#endif

And cpp file
#include "sensor.h"
Sensor::Sensor()
{
  this->sensorId = 0;
  this->sensorType = UNKNOWN_SENSOR;
  this->currentValue = 0;
  this->isEnabled = false;
  this->criticalLowerLevel = 0;
  this->criticalUpperLevel = 0;
}
Sensor::Sensor(uint32_t id,SensorType type,long currentValue,bool isEnabled,long lower,long upper) {
  this->sensorId = id;
  this->sensorType = type;
  this->currentValue = currentValue;
  this->isEnabled = isEnabled;
  this->criticalLowerLevel = lower;
  this->criticalUpperLevel = upper;
}
void Sensor::enable(bool enable) {
   this->isEnabled = enable;
}
void Sensor::toggle() {
  this->enable(!this->isEnabled);
}
String Sensor::toString()
{
  String response = "";
  response += F("Sensor id is ");
  response += this->sensorId;
  response += '\n';
  response += F("Sensor type is ");
  response += convertSensorTypeToString(this->sensorType);
  response += '\n';
  response += F("Sensor current value is ");
  response += this->currentValue;
  response += '\n';
  response += F("Sensor isEnabled is ");
  response += this->isEnabled;
  response += '\n';
  response += F("Sensor criticalLowerLevel is ");
  response += this->criticalLowerLevel;
  response += '\n';
  response += F("Sensor criticalLowerLevel is ");
  response += this->criticalUpperLevel;
  response += '\n';
  return response;
}
String Sensor::convertSensorTypeToString(SensorType sensorType) {
  switch (sensorType) {
    case UNKNOWN_SENSOR:
      return F("UNKNOWN SENSOR");
    case ANY_SENSOR:
      return F("ANY_SENSOR");
    case WATER_SENSOR:
      return F("WATER_SENSOR");
    case TEMPERATURE_SENSOR:
      return F("TEMPERATURE_SENSOR");
    case VIBRATION_SENSOR:
      return F("VIBRATION_SENSOR");
    case HUMIDITY_SENSOR:
      return F("HUMIDITY_SENSOR");
    case PIR_SENSOR:
      return F("PIR_SENSOR");
    case SOUND_SENSOR:
      return F("SOUND_SENSOR");
    case LIGHT_SENSOR:
      return F("LIGHT_SENSOR");
    default:
      return F("UNKNOWN TYPE");
  }
}

And I got following errors
ketch/NodeIntercom.ino.cpp.o: In function `sendSensorMessageToMaster(RF24Mesh*, SensorDataMessage*, char, unsigned int, bool)':
/home/iron/Arduino/What'sHappening/NetworkMaster/additional_functions.h:48: undefined reference to `Sensor::toString()'
sketch/NodeIntercom.ino.cpp.o: In function `handleSetSensorDataRequest(RF24NetworkHeader*)':
/home/iron/Arduino/What'sHappening/NodeIntercom/NodeIntercom.ino:97: undefined reference to `Sensor::toggle()'
/home/iron/Arduino/What'sHappening/NodeIntercom/NodeIntercom.ino:89: undefined reference to `Sensor::enable(bool)'
sketch/NodeIntercom.ino.cpp.o: In function `SensorDataMessage':
/home/iron/Arduino/What'sHappening/NetworkMaster/common.h:40: undefined reference to `Sensor::Sensor()'
sketch/NodeIntercom.ino.cpp.o: In function `__static_initialization_and_destruction_0':
/home/iron/Arduino/What'sHappening/NodeIntercom/NodeIntercom.ino:35: undefined reference to `Sensor::Sensor(unsigned long, SensorType, long, bool, long, long)'
collect2: error: ld returned 1 exit status

What I am doing wrong ?
Please help.
EDIT
Yes main sketch compiles perfectly where this files are located.
But I don't want to duplicate common files in my all my arduino sketches withing the project, they are the same for whole project. Here my files location
--ArduinoProjects
---NodeIntercom
----NodeIntercom.ino
---MasterNode
----MasterNode.ino
----sensor.h
----sensor.cpp
----common.h

So this files are only located in MasterNode directory
And I tried to include them like this
#include "/home/iron/Arduino/What'sHappening/NetworkMaster/common.h"
#include "/home/iron/Arduino/What'sHappening/NetworkMaster/additional_functions.h"

And in common.h I include sensor.h
Also tried to include directly, but still the same
But headers files included as above works perfectly.
What is the right way to solve this problem, I don't want to duplicate this class in each folder whenever I change it.
If there is no way, maybe create symbolic link (I am using linux) ?
PARTIAL SOLUTION
Just use symbolic links in the sketch directory and this works perfectly

where are these files located? in the sketch folder? in a library?

The Arduino build preprocessing cannot locate the sensor source and header files if they are located in another sketch directory. The files needs to be moved to separate directory if shared (as a library).
--Sketchbook
---NodeIntercom
----NodeIntercom.ino
---MasterNode
----MasterNode.ino
---libraries
----Sensor
-----Sensor.h
-----Sensor.cpp

The Sensor header is included with
#include <Sensor.h>

in the sketches that needs to use it.

There is nothing wrong with that class and its code (as far as I can tell) - it compiles perfectly fine.
What is probably wrong is that the IDE isn't picking up the code and compiling it in to your project.
Is this class part of the sketch, or is it a separate library that you are writing?  If the latter you have to ensure that the IDE knows about it, and it can only look for it when you load the IDE, so if you haven't restarted the IDE since creating the library you must do that so it can find the new library.

Thank you for answer. I just created manually this class and want just to separate logic, I am not writing a library, just simple class.
I think the problem is that this files are located inside another sketch directory MasterNode this is main node sketch.
I have updated my question please see it

You're trying to use files from one sketch in another sketch? That's not going to happen. It can't be done. If you want to share files between sketches then they must be as a library. There's no two ways about it. Create yourself a library and put your shared files into it.

Thank you for explanation, I have just used symbolic links and this works perfectly !

See my post about How the IDE organizes things.


text:
Trouble with large numbers
Probably something stupid, but I can't figure out how to work with these large numbers, then cast the result (which will be small) to an integer. I keep getting negative numbers, which I think means I'm overflowing somewhere.
int freq = 440;
int len = 256;
long timer = 2000000.0 / (freq * len);
int roundedTimer = int(timer);

I should get 18, but I'm getting -108...

Well, I'm not sure I exactly understand why, but it seems that the result of freq * len needs to be explicitly a long too: long timer = 2000000L / ((long) freq * len);

Majenko has the reason - your divisor calculation overflowed. Either your solution (as coded above) or his, works. Casting either freq or len to long forces the other to be promoted to long for the calculation, and the long result to be used for division. However the solution you described (not the one you coded) would fail. You do have to calculate the divisor as a long. Casting the product comes to late; it will already have overflowed.

The "answer" by JeffThompson is really a comment on Majenko's answer. I'm going to convert it into a comment for you. Please only use answers for answers to the posted question.

freq * long, since they are both integers, are calculated as integers.
440*256=112640 - in binary that is 1 1011 1000 0000 0000 and trimmed to 16 bits becomes 1011 1000 0000 0000 which is -18432 and that is where the heart of your problem is.  Unless you explicitly say otherwise the Arduino's compiler does all calculations (except floating point) as 16-bit signed integers.
By casting the values to long it forces the compiler to 'overflow' the 16-bit limit and use a 32-bit limit instead:
long timer = 2000000 / ((long)freq * (long)len);

Another alternative is to define freq and len to be long from the outset instead of int.


text:
Calculate OCR2A from audio frequency
I'm working on a Arduino-based synthesizer using this tutorial, specifically using a wavetable and 1-bit DAC. I understand that the value for OCR2A register sets the frequency, but how do I calculate the value?
I've seen this list of notes which is great, but I want arbitrary frequencies in Hz...
Here's the code I'm working from:
#include <avr/interrupt.h>

// sinewave parameters
#define FREQ 18
#define PI2 6.283185    // 2*PI saves calculation later
#define AMP 127         // scaling factor for sine wave
#define OFFSET 128      // offset shifts wave to all >0 values

#define LENGTH 256      // length of the wave lookup table
byte wave[LENGTH];      // wavetable

void setup() {

  // populate wavetable
  for (int i = 0; i < LENGTH; i++) {
    float v = (AMP * sin((PI2 / LENGTH) * i));
    wave[i] = int(v + OFFSET);
  }

  // set timer1 for 8-bit fast PWM output
  pinMode(9, OUTPUT);       // make timer’s PWM pin an output
  TCCR1B = (1 << CS10);     // set prescaler to full 16MHz
  TCCR1A |= (1 << COM1A1);  // pin low when TCNT1=OCR1A
  TCCR1A |= (1 << WGM10);   // use 8-bit fast PWM mode
  TCCR1B |= (1 << WGM12);

  // set up timer2 to call ISR
  TCCR2A = 0;             // no options in control register A
  TCCR2B = (1 << CS21);   // set prescaler to divide by 8
  TIMSK2 = (1 << OCIE2A); // call ISR when TCNT2 = OCRA2
  OCR2A = FREQ;           // set frequency of generated wave
  sei();                  // enable interrupts to generate waveform!
}

void loop() {
  // nothing to do here!
}

// called every time TCNT2 = OCR2A
ISR (TIMER2_COMPA_vect) {   // called when TCNT2 == OCR2A
  static byte index = 0;    // points to each table entry
  OCR1AL = wave[index++];   // update the PWM output
  asm("NOP; NOP");          // fine tuning
  TCNT2 = 6;                // timing to compensate for ISR run time
}

Shouldn't this be in Arduino.SE?

Perhaps, didn't realize there was a separate forum. Happy to migrate if that's appropriate.

Whoever wrote the code for that tutorial needs their head examining. asm("NOP; NOP"); and TCNT2 = 6; are total nonsense and should be removed, as should the sei(); line from setup (it's unnecessary). Also, the LENGTH #define is totally ignored in the ISR, so if it was ever set to something other than 256 the code would break. >_<

Hmm, I tried it without TCNT2=6 and got a lot more high-freq partials. With TCNT2=6 but no asm("NOP;NOP") I get no audio, just buzzing. It seems to be fine without sei(), but (obviously) my timer programming is really bad, and I don't entirely understand what they do.

Well the asm() statement that according to the comments adds two nops only adds one, so...

The reason it misbehaves when you remove the lines is because whoever wrote the code doesn't understand how to set up the timers. In the setup it should be TCCR2A = (1<<WGM21) to set into CTC mode. Otherwise the timer just counts all the way around to 0xFF and overflows (setting TCNT2 to 6 was clearly a hack to get around that issue without understanding what was actually causing it).

@TomCarpenter – if you'd like to suggest changes to make this code better, I'm all for it!

The equation to calculate it is given in the first article you linked:

The 2MHz value comes from the factor of 8 prescale on the 16MHz clock and 256 is the size of the lookup table specified by your LENGTH define. If you start from a frequency you want to synthesize, just use the above equation to solve for the necessary value of OCR2A. Note that since you have to input integer values to OCR2A, you can't really achieve arbitrary frequencies, but you're certainly not locked in to the values given in the supplemental musical note PDF you reference.
So, to solve for OCR2A:
OCR2A = TCNT2_rate / (desiredFreq * wavetableLength);

Thanks! It took me a while to figure out that the equation told me that! So, my math is really terrible: how do I swap the equation to get me OCR2A from frequency? :)

@JeffThompson just swap them over in the equation (stick frequency where OCR2A is, and vice versa)

Sorry, feeling really stupid: so OCR2A = TCNT2/(freq*tableLen)?

@JeffThompson Yep, that's correct.

As Cheibriados said, you won't get arbitrary frequencies. From the table you linked you can see that OCR2A of 15 gives you a frequency of 523.25 Hz, and making it 16 gives you a frequency of 493.88 Hz. Thus you cannot get any frequencies in-between.


text:
Maximum frequency of digital signal in Arduino Uno?
As Arduino Uno has a 16 MHz oscillator but while running program it has less frequency because some of the processing power is used for running the program.
I have used the delay(1) but it is giving me around 500 Hz.
My questions:

Is there any way to achieve more than 500 Hz?
What would be the maximum frequency of digital signal for below program?

void setup() {
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);
  digitalWrite(13, LOW);
}

note that digitalWrite is relatively slow. Also, wrapping everything inside a while(true){...} will make it a bit faster, instead of letting the loop function exit.

Yes, use the hardware timers.
You can achieve 8 MHz.

Example sketch which outputs 8 MHz on pin 9 on a Uno:
#ifdef __AVR_ATmega2560__
  const byte CLOCKOUT = 11;  // Mega 2560
#else
  const byte CLOCKOUT = 9;   // Uno, Duemilanove, etc.
#endif

void setup ()
  {
  // set up 8 MHz timer on CLOCKOUT (OC1A)
  pinMode (CLOCKOUT, OUTPUT);
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaling
  OCR1A =  0;       // output every cycle
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

If you change OCR1A you can get lower frequencies. If you change the prescaler you can get lower frequencies again.
See my page about timers for more details.

Below I have put a oscilloscope waveform from your code. Thanks!

Also, don't forget that there are alternative methods of toggling outputs.
You can use PORTS to do the job.
Here's a good example. And another here.
And this code is the idea behind it:
void setup()
{
  DDRD = B11111111; // set PORTD (digital 7~0) to outputs
}

void loop()
{
  PORTD = B11111111; // set PORTD pins (digital 7~0) high
  PORTD = B00000000; // set PORTD pins (digital 7~0) low
}

P.S. Don't forget that the port numbering is in reference to the chip pins and not the Arduino pins/legs.

Nick Gammon's code worked fine for me. Here is an oscilloscope picture of the waveform I've got from his code:

His code above (from Nick Gammon, on Jan 25 '16 at 20:33) worked excellent for me. I used his code on Arduino UNO and got about 7.9 MHz of output frequency on an approximately 1 V amplitude (peak-to-peak, with spikes making it go to about 2 V peak-to-peak amplitude).
The image above was obtained with my 40 MHz Oscilloscope from ICEL Manaus (manufacturer) at pin 9 (I used the Arduino UNO), with a LED and a resistor as a load at pin 9:

a green LED of about 1.79 V voltage drop
and a 4.7 Ohms resistor with 5% tolerance

The oscilloscope probe (Channel 2, with fall slope trigger detect) is on the 4.7 Ohms resistor. It follows the connection order out of the pin 9 from Arduino UNO:
PIN 9 > green LED > 4.7 Ohms resistor >  GROUND.
The green LED keeps blinking at a normal luminescence, as compared when used at other output frequencies.
I used a external 5 V DC power supply, along with the USB connection on my PC.
If you have any questions just put them here. Thanks and thanks Nick Gammon

Glad it worked for you! The slight discrepancy in frequency could be explained by the fact that the Uno has a resonator rather than a crystal as a frequency source for the main processor.

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


text:
Recommendations for limit switches for Arduino
I'm looking for a limit switch to use with the Arduino. In my project I want to count how many times my turntable makes a full 360° rotation. An object (wheel, pipe, whatever) will be sticking out the side of the turntable and when it comes in contact with the limit switch that will be right next to the turntable, it should notify the Arduino.
Any suggestions on which limit switch I should get?
Thanks so much in advance!

Are you sure you want a limit switch? A limit switch is used to stop the motion at a specific point, not count rotations. For that you would use some kind of encoder, interrupter, hall effect sensor, reed switch, etc.

Indeed, a magnet under the turntable could activate a hall-effect sensor as it passes over it.

Maybe tell us a bit more about what you want to accomplish, then we can think about the problem – rather than just think about a device. From the photo of the turntable I'm thinking that you're planning to do object movies or panoramas. For that you might actually do better with a stepper motor.

I'd use a photo reflective sensor, and stick a white dot on the side of the turntable. You could add dots to get half, quarter, etc. rotation resolution

@Majenko I do want it to send a signal to my Arduino to stop the electricity going to the turntable, and then hopefully each time that signal occurs the Arduino can just increase a counter.

@NickGammon  I'll look into that.  Thanks!

@dlu I'm trying to do 360 photography, and the turntable needs to stop at the exact same spot in each rotation.

@Gerben I'll look into that for sure.  Thanks!

I don't think you could get it to stop at the same location using a regular turntable. As the turntable will continue spinning a bit after you kill the power to the motor (due to inertia). I think you would be better of replacing the DC motor in the turntable with a stepper-motor.

Besides the problem @Gerben mentioned  you may find that a switch does not give you the precision of position that you want/need. Definitely consider a stepper if you can.

Great points.  You're both right. I'll move forward with a stepper-motor for version 2 of my setup.
I'm just going this route because I was provided with an automated turntable to first work with.
Maybe I can open it up and change out some parts...

A $2 microswitch with a roller would be OK for a million revs or so.

You would put a little ramp on the diameter and use it to trigger the switch.
Non-contact magnetic or optical could be better for more cycles or faster operation.

Literally a million? That's impressive.

Honeywell's PDF at http://sensing.honeywell.com/honeywell-sensing-micro-switch-sx-basic-switch-product-sheet-004968-2-en.pdf says 10,000,000 cycles.    But one probably needs to check the datasheet.  Googling a bit, I saw some specs of 1M-5M cycles on a single switch, depending on load, but also some cheap mini ones rated for 10,000 cycles.    Also, for a 33rpm audio turntable even a million isn't long: 1,000,000/33/60/24 = 21 days

@DaveX do you have a link to a brand in particular you recommend?

I do not have a recommendation on the brand.

Beware that a physical switch will probably exhibit contact bounce.  One can filter that in software, but it requires thought.

Well, @Dlu; @Dave X is right on this point, if your project involves being used for longer duration including testing etc. My suggestion would be dont go for this solution at all. Else if its just for a couple of 10s of usage, this shouldn't be a issue.

Instead of a limit switch a hall effect sensor with a moving magnet is an optimal soltuntion since it is contact less there will be no frictional side effects on your application.
But there is one more better way to it, try to use an rotary encoder, something like a 400/600 ppr should also be fine for this, doing this way you have more positional data of the turntable,
You can calculate no of turn, arcs etc.
For eg:

A 400ppr would give you a resolution of 0.9 degree per pulse, and
600ppr would give you 0.6degree per pulse of accuracy.

Although you can go for even higher ppr encoders but you can get these at very low cost.
Pic from: https://m.ebay.co.uk/itm/400BM-Rotary-Encoder-Module-LPD3806-360-6mm-Shaft-Arduino-Pi-Flux-Workshop-/112607725039?_mwBanner=1
Note: Just an example, price may be different at other webites, haven't checked the price while writing this solution.


text:
Problem with a digital potentiometer application
I am a beginner when it comes to electronics, coding and things like that (this is practically the first time I have done anything like this), so when building an application that is supposed to vibrate a vibration motor with a strength based on the distance measurement made by the ultrasonic rangefinder, I bumped up with a problem.
The MCP 41010 digital potentiometer seems to let electricity through only when it is given a SPI.transfer(128). Any other number stops the flow of electricity completely.
I have tried some addresses such as 00, 0x00, 0x01 and 0x04 to replace the 0 and the result was the same. With addresses 0x11 and 0x08 the digital potentiometer didn't react at all.
In addition to the code I have here I have tried just copy-pasting some of the tutorials I found from the internet, for example this one Digital Potentiometer not fading LED without really understanding the commands formats thing all that well. With that code I got a vibration that didn't seem to fade in or fade out at all, so the problem remains (I lack a way to properly test that though).
So... what am I doing wrong and how to fix it?
Thank you!

Many tutorials were used when making the code.

#include <SPI.h>

int vcc = 2; // attach pin 2 to vcc
int trig = 3; // attach pin 3 to Trig
int echo = 4; // attach pin 4 to Echo
int gnd = 5; // attach pin 5 to GND

int shortest = 250;
int longest = 12000;

int CS = 10; // for digi pot

void setup() {

  SPI.begin ();
  pinMode (vcc,OUTPUT);
  pinMode (gnd,OUTPUT);
  pinMode (CS, OUTPUT); // for digi pot
  // initialize serial communication:
  Serial.begin(9600);

}

void loop()
{
  digitalWrite(vcc, HIGH);
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(trig, OUTPUT);
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(5);
  digitalWrite(trig, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(echo,INPUT);
  duration = pulseIn(echo, HIGH);

  if (duration > 200 && duration < 220)
  // Limiting out an unwanted, randomly appearing distance measurement
  // made useless by later code though
    {
     Serial.print("Error ");
     Serial.print(duration);
     Serial.print("\n");

     return;
    }

   // Compressing the result of the distance measurement into the scale of 0 - 128
  if (duration < shortest) duration = shortest;
  if (duration > longest) duration = longest;
  duration = (1.0f-((float)(duration - shortest) / (float)(longest - shortest))) * 128;

  digitalWrite(CS, LOW);
  SPI.transfer(0); // 0x01 and 0x04 seem to "work" too. With 0x11 and 0x08 no voltage goes through
  SPI.transfer(duration); // sending a number from 0 to 128 to the digital potentiometer
  digitalWrite(CS, HIGH);

  Serial.print(duration); // printing the result of the measurement and calculations
  Serial.print("\n");

  delay(100);
}

Digital potentiometers are not a good choice for controlling the speed of a motor. They are designed only for very low current applications - things like setting offset points for op-amps and things like that - things where you would use a small trimmer pot rather than a large power rheostat.
Instead you should be controlling the motor using PWM and a transistor (here is a good tutorial).
But to help you understand the digital potentiometer and so you can work with it better:
Step one is always to read the datasheet.  That details the SPI communication protocol for you so you can know what numbers mean what.
In this case the protocol is made up of two bytes - a command byte and a data byte.
The command byte is made up like this:

As you can see it's in two parts - a command and a potentiometer selector.  So to set the resistance of potentiometer 0 you would need to craft a command byte that had the write command and the code for potentiometer 0.  That would be 0b00010001 or 0x11 in hex.  So your transaction would look like:
digitalWrite(CS, LOW);
SPI.transfer(0x11);
SPI.transfer(duration);
digitalWrite(CS, HIGH);

Another important part of the datasheet is the electrical characteristics.  That is a table that tells you the minimum, typical and/or maximum values for different parameters.  One important one here is the wiper current which it states as being allowed between -1mA and +1mA.  That is the maximum current you are allowed to draw through the digital potentiometer before you risk damaging it.  That is why it's not good for powering things like motors, no matter how small.

I agree with Majenko. What you probably need to control your vibrating motor is a MOSFET to handle the current, and possibly PWM output to manage whether you want weak or strong vibration.


text:
Arduino Nano, ICSP header and 595 Shift register
I'm trying to control a 4-digit 7 segment display with an Arduino Nano, but I'm getting something wrong. I'm using the ICSP header to interface with a 74HC595 Shift Register which is then connected to the display. I've tested and retested the connections and everything seems to be alright, however the shift register doesn't have the desired output, and I notice it only shifs one single bit when I press the reset button on the arduino board.
74HC595   |    A. Nano
DS     <-----> MOSI (ICSP)
SH_CP  <-----> SCK (ICSP)
ST_CP  <-----> D6
MR     <-----> 5V (ICSP)
OE     <-----> GND (ICSP)
VDD    <-----> 5V (ICSP)
GND    <-----> GND (ICSP)

My code:
//pin connected to STCP
const int latchPin = 6;
//pin connected to SHCP
const int clockPin = 17;
//pin connected to DS (MOSI)
const int dataPin = 11;

byte val=0;

void setup() {
  // put your setup code here, to run once:
  //SPI pins are output
  pinMode(latchPin,OUTPUT);
  pinMode(clockPin,OUTPUT);
  pinMode(dataPin,OUTPUT);

  pinMode(3,OUTPUT);
  updateRegister(0);

}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(3,HIGH);
  for (int i=0; i<8; i++) {
    updateRegister();
    delay(500);
  }

}

void updateRegister() {
  //pull latch low to write new bits to the register
  digitalWrite(latchPin,LOW);
  //shift out the data
  shiftOut(dataPin,clockPin,LSBFIRST,val);
  //pull latch pin high so that the leds light up
  digitalWrite(latchPin,HIGH);
}

This site has a question and answer format. What is your question, exactly? (Note that questions generally end with a question mark). Please read How do I ask a good question?

Please post a schematic of your wiring. You say in the question that you are using the ICSP header, but then the code uses pins 6 and 17 which are not ICSP (or SPI) pins.

const int clockPin = 17;
I'm pretty sure that should be 13, not 17.

Yup, this was my mistake. http://christianto.tjahyadi.com/wp-content/uploads/2014/11/nano.jpg this image mislead me to believe SPI clock was at pin 17. With pin 13, the display is operating as it should.

It is extremely confusing to have a variable val and then use _val in your function but then:
  shiftOut(dataPin,clockPin,LSBFIRST,val);

As James pointed out, you are not sending the value passed to the function, to the shift register.
Also this is just going to give you a boolean:
 updateRegister(!i);

Why take "not i" there?

I suggest you use SPI and not muck around with shiftOut. I have a page about the 595 chip including example code. eg.
#include <SPI.h>

const byte LATCH = 10;

void setup ()
{
  SPI.begin ();
}  // end of setup

byte c;
void loop ()
{
  c++;
  digitalWrite (LATCH, LOW);
  SPI.transfer (c);
  digitalWrite (LATCH, HIGH);
  delay (20);
}  // end of loop

I posted the code with some errors (I was paying with the varaibles trying to solve the problem). As it was it was bovisously not going to work, but that was not the cause of the problem. I tried that snippet with the SPI library, but the display/leds do not light up at all. Also, it just crossed my mind - could the problem be caused by calling shiftOut() on SPI pins?

What LEDs exactly?

could the problem be caused by calling shiftOut() on SPI pins? - No. If you don't call SPI.begin() then SPI is inactive.

The leds on the 7-segment display

Do you need to add the _  to the shiftOut(dataPin,clockPin,LSBFIRST,val); ?

James, you were right about the underscore, but the Stack Exchange system automatically flags very short answers. If you expand it out a bit more you are protected from this automated flagging. Welcome to Arduino Stack Exchange. :)

It was a mistake, I was tinkering with the code. I've updated the question, but I can say that was not the source of the problem.

Your updated code sends 0 to the shift register, so I'm not too surprised nothing lights up.

The 7-segment display has a common anode, sending a '0' to the shift register should light up all the segments (an '8'), since I'm pulling the anode up with 'digitalWrite(3,HIGH); '

authors: אורין אפשטיין


text:
Analog Pins are sensing Values
I used the example code AnalogReadSerial and tried it on all analog pins from A0 to A7. None of the analog pins were connected to anything so I expectedy to get 0 in the serial monitor. But as it turns out, I was wrong. Only pin A7 shows 0 to 19 values on the serial monitor. The rest have values ranging from 100 to 300 for pins A2, A3, A4, A5 and A6. The worst performers are A1 and A0 with values from 921 to 1023 showing on the serial monitor. What is the cause of this and how will I fix it?

None of the analog pins were connected to anything so I expected to get 0 - what you should actually expect is an undefined value. how will I fix it? - don't try to read "floating" or unconnected pins. The action has no meaning.

The ADC is multiplexed across the pins, and will carry a small charge from pin to pin.  If you want them to be zero, tie them to ground.
This answer, https://arduino.stackexchange.com/a/575/6628 , suggests pulling them to ground for higher accuracy.

This is normal, as the unconnected pin may float from GND to VCC. You may  enable internal pull-up (to VCC). This is normal for all high-z inputs. If you read digital port you'll see that it floats too. Sometimes you can change digital I/O input value just by waving your hand above the board.
For that reason we always tie high-z inputs to something. You can leave it floating - it won't damage anything, but the value obtained from free-floating input is useless.


text:
Converting data between baud rates
This isn't strictly limited to Arduino but I spend a lot of time with serial devices on my Arduino and I'm sure that others do as well:
Here goes..
Let's say a device sends three characters [ABC] via serial at 9600 8N1.
And let's also say the device receiving the data only knows that it's serial stream and 8N1 but does not know the baud.
The receiving device would need to take a guess at the baud and so probably get it wrong. It would therefore receive weird characters.
Is there anyway/anything around that a user could paste the strange characters into that would reverse engineer (from the bit stream) to give the correct baud and hence correct ascii characters [ABC]?

I am not aware of anything like that, no.  The problem is what you are seeing as characters are a complete corruption of the data. Only some part of it may have been interpreted as a valid bit sequence, and even then you can't know what bit it was.
However, there is one magic character in UART communication: U
What is special about that character is its binary pattern.  It is ASCII character 85, which in HEX is 0x55, or binary it's 0b01010101.  Add to that the start and stop bits, and invert it for the UART logic (1 = LOW, 0 = HIGH) and the signal that gets sent out of the UART looks like:
____start_____     _____     _____     _____     _____
    |   |  0  | 1 |  0  | 1 |  0  | 1 |  0  | 1 | stop
    -----     -----     -----     -----     -----

And yes, that's a pretty good square wave.  The frequency of that square wave will be exactly half the baud rate - so a frequency of 4800Hz will be a baud rate of 9600 baud.
This effect is cleverly used for a system called Automatic baud rate detection whereby a receiver waits for a U character to determine the baud rate to use.  Most modern microcontrollers have this facility available.
If you can't get the frequency of a block of U characters you will have to examine the waveform with an oscilloscope.  It should be possible to identify the individual characters in the data stream as distinct blocks in the waveform.  From that you can then work out the width of one symbol and thus the baud rate.  It's best to use a DSO for this since you can then capture a short burst and use the markers to measure the time between different points in the waveform.  A logic analyser will also do the job quite well, and will most likely be able to decode the waveform and calculate the baud rate for you.
If you have neither of those it would be possible to program an Arduino to capture the time between transitions of an incoming signal and allow you to plot them in Excel to give you a waveform you can examine to determine the baud.
Another option is just to keep trying different baud rates (there's relatively few "standard" baud rates) until you see the right text coming in.

Thanks.  Following your Autobaud link down to https://en.wikipedia.org/wiki/Synchronous_Idle I found the ASCII SYN byte 0b00010110 which helps to align the frames.

There are a few papers on auto baudrate detect that might be of interest; https://www.silabs.com/Support%20Documents/TechnicalDocs/AN635.pdf, http://www.ti.com/lit/an/slaa215/slaa215.pdf, https://www.pjrc.com/tech/8051/autobaud.html, http://www.google.com/patents/US6072827

The UART logic is not inverted: 0 is LOW. But bits are transmitted least significant first.

My logic analyser has a "guess baud rate" feature, which usually is fairly accurate. If you analyse an incoming bit stream you can probably have a reasonably good guess. For example the shortest transition means the baud rate cannot be slower than that. For example, at 9600 baud sooner or later you will get a transition in 104 µs (ie. 1/9600). Thus if you see that, the baud rate could not be 4800 baud.
Also, in general, there will be a gap between "packets", so in your case after the "ABC" there would be a longer gap (of all 1s). You would assume then that the active time represents an integral number of bytes (eg. 3 bytes, 8 bytes, but not 1.5 bytes).
Another thing is that baud rates are usually multiples of a power of 2 times 300 (ie. 300, 600, 1200, 2400, 4800). So this gives you a small range of possible baud rates to test. You could test (say for 9600) and see if you get reasonable results. A "reasonable result" would be a stop bit appearing 10 bits after a start bit.
See my post: How does serial communications work on the Arduino?

Try measuring pulse width and match shortest pulse against pre-defined widths corresponding to available baudrates. This way you can detect baudrate by analysing random binary stream.
Signal glitches, such as very short spikes, will be filtered out, as they will never match the list of baudrates.
Repeat the measurement few times to raise accuracy and choose the most probable value from all guessed values.

In the days of dumb terminals and time sharing systems, setting the baud rate was accomplished by the terminal sending a pre-determined series of characters with gaps between them and the host changing its baud rate and looking for the expected data. It is best to start at a high baud rate and drop the rate between tries.
For example the terminal user would hit Enter repeadedly and the host would try decreasing baud rates until it saw the Carriage Return character. When it saw the CR, it would respond with "Login Please" and you would know you were good to go.

In those days,you didn't have many baud rates to choose from: 300 or 1200.


text:
Arduino uno not writing to file
I'd like the arduino to write to a file whenever an ajax call is made. The ajax works, but it doesn't write to the file. All other code inside the ajax handler does execute.
void handle_ajax() {
    int startUrlIndex = HTTP_req.indexOf("button");
    int endUrlIndex = HTTP_req.indexOf(" HTTP");
    String url = HTTP_req.substring(startUrlIndex, endUrlIndex);
    int startButtonIndex = url.indexOf("device-") + 7;// 7 is length of device-, I really just want the number.
    int endButtonIndex = url.indexOf("&");
    String button = url.substring(startButtonIndex, endButtonIndex);
    int startStateIndex = url.indexOf("state=") + 6; // 6 is length of state=, I really just want the number.
    String state = url.substring(startStateIndex);
    int device = button.toInt();
    int newState = state.toInt();
    dim_light(device, newState * 12);
    write_config("", "text");
}

bool write_config(String line, String text) {
    configFile = SD.open("config.ini", FILE_WRITE);

    if (configFile) {
        configFile.write("Dipshit");
    }

    configFile.close();
    Serial.println("Works.");
    return true;
}

Hi, and welcome to the Arduino StackExchange community. Just a couple of questions to try and clarify the situation: 1. Are you able to write to the SD card outside of your function? I.e., can you write something in setup()? 2. Can you expand your code snippet to include the parts where you configure the SD card?

Where have you defined SD and configFile? The statement configFile.close(); belongs into the {} just after the line with configFile.write("Dipshit");.

I fixed it already, ran out of RAM again.

You have run out of RAM. Consider moving string literals into flash with thr F() macro.

We've done that before, we don't use any strings right now though.


text:
ESP8266, Arduino IDE vs Lua?
I'm planning to buy an ESP8266. Do I really need to learn Lua to play with it? I have seen some people using it with the standard Arduino IDE.
Do you need a custom firmware to use the Arduino IDE instead of Lua?
The Arduino IDE seems better for me because I already know the syntax. Is there any downside to using the Arduino IDE instead of NodeMCU with Lua?

Using the Arduino IDE is custom firmware. That's what you're writing. You don't need any new firmware because the new firmware is what you are writing.
I can't think of any downsides to using C++ to program the ESP8266 instead of Lua - in fact it can only be a benefit since you are not using an interpreted language which is going to be slower than natively compiled code.

so why are most people using NodeMCU with Lua ?

@n0tis Because it's pre-installed and very easy to use. Also they're told to use it when they buy it and don't know any better.

so I should use this lua? I'm planning to make a mini robot using small motor, small battery and pwm

@n0tis I have only ever programmed them in C++ and wouldn't do anything else. At the end of the day you can always re-install the LUA interpreter firmware and go back to LUA if you don't get on with the Arduino-style programming of it. Nothing is permanent - you can change your mind any time you like.

It's Lua not LUA. It is not an acronym. See What's in a name?. How are you using Lua on the Arduino?

@NickGammon wHaTeVeR ;) - The NodeMCU comes with a Lua interpreter preinstalled and executes Lua script uploaded form the NodeMCU IDE.  That Lua firmware can be replaced using the Arduino IDE and the ESP8266 plugin.

@NickGammon Anyway, I refer to LUA not Lua. LUA stands for Least-ever Usable Argot ;)

Is using the Arduino IDE with a fresh out of the box ESP8266 as simple as compiling and uploading or do you need to "clean out" the ESP first? I've held off on buying an ESP because I'm not clear on what I need to do to make it work with the Arduino IDE.

Yes, you just compile and upload. The lua firmware, or the AI thnker AT firmware are both just programs uploaded to the board: one to interpret Lua script, the other to interpret AT commands. Just like your Arduino sketches.

Lua, like many scripting languages, tends to make you a lot more
productive as a programmer: things become far easier as you work at a
higher abstraction level and do not worry about trivial things like
memory management. You achieve the same goals with far less lines of
code. On the other hand, whereas it makes development faster, it also
makes program execution slower. Whether this is a good trade-off or not
is very dependent on the particular application you want to write.
In your particular case, you also have to consider the fact that you do
not know Lua, and you already know both the C++ language and the Arduino
API. Then you may not rip the benefits of Lua on a single project,
because of the time needed to learn the language. You may consider
learning the language as an investment, probably worth it if you are
going to program a lot on this platform, probably not worth it if it's
only for a single, simple enough project. If unsure, I suggest you take
a look at the API provided with Lua on this platform: how well does it
fit your project? Is it a significantly better fit than the Arduino API?

I STRONGLY RECOMMEND TO STAY WITH THE ARDUINO IDE!
Despite programming in C++ not being as friendly and versatile as Lua (working with Esplorer is really a dream come true!), Lua is VERY UNSTABLE AND UNPREDICTABLE!!!
You can run a simple program of ten lines and it works ok for a day... two... and suddenly, on the 3rd day the chip hangs unexpectedly, and with no reason!
If you are lucky, the chip will reboot and program will start running again... that WAS NOT the case with me. I had to reload the program again! After 3 cycles like this, I decided to abandon Lua... FOREVER.

Same experience here. And I really, really liked Lua.

Yeah. Lua as a language is an interesting experience. On NodeMCU, mostly a frustrating one..

I like lua and the REPL.  I also like js on the ESP8266 (espruino) and its small footprint.  As a programmer of embedded systems, it is very clear that many of the Arduino libraries are written by non-embedded programmers wasting and/or fragmenting valuable memory.  I do use Arduino but do things like using my own string management from C rather than that ugly C++ class.  Memory is a commodity to appreciate not abuse.

I learned a little trick.:.in your loop routine add a millisecond delay at the very bottom.....this will allow the chip to do its wifi 'homework' ..yóur code will not notice that...and problem solved!.....  ;)

Sorry for bumping, but this thread helped me to decide for Arduino IDE.
I started with Arduino IDE but couldn't get it to work with ESP-07.
Moved on to NodeMCU and Lua with Esplorer. Took me a while to get it working there also due to the odd bootloader baud rate. First it seemed so easy to set up a WEB-server, but problem was that all the examples found were based on an ancient FW 0.96, and trying with the latest 2.1 didn't work at all. So realising that people hadn't done much with newer FW gave me second thoughts.
Now with Arduino IDE things start to work the way they should! :)


text:
Unable to connect Ethernet shield W5100 to localhost
I have an Arduino Uno and a W5100 Ethernet Shield. I am trying to post some data from the Arduino board to the WAMP server running on my computer. I do not have a router so I have directly connected my Ethernet shield stacked onto the Arduino Uno to the laptop's Ethernet port via an Ethernet cable. I have also assigned the Ethernet connection a static IP address 192.168.0.1 and my localhost page opens when I put this address in my browser.
In my Arduino sketch I have assigned the Arduino shield an IP address 192.168.0.4, i.e. on the same IP segment. When I try to do client.connect to the server (192.168.0.1), i.e. localhost, I get "Connection failed".
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0x6F, 0xED };
IPAddress ip(192,168,0,4);
byte server[]={192,168,0,1};

int value=9;
EthernetClient client;

void setup() {
  // Serial.begin starts the serial connection between computer and Arduino
  Serial.begin(9600);
  // start the Ethernet connection
  Ethernet.begin(mac,ip);
}

void loop() {
  // Connect to the server (your computer or web page)
  if (client.connect(server, 80)) {
    Serial.println("Connecting...");
    client.print("GET /Ethernet/getData.php?"); // This
    client.print("value="); // This
    client.print(value); // And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
    client.println(" HTTP/1.1"); // Part of the GET request
    client.println("Host: 192.168.0.1");
    client.println("Connection: close");
    client.println(); // Empty line
    client.println(); // Empty line
    client.stop();    // Closing connection to server
  }

  else {
    // If Arduino can't connect to the server (your computer or web page)
    Serial.println("--> connection failed\n");
  }
  delay(10000);
}

Now when I upload the sketch onto the board and run the serial monitor, I get this output:

My Ethernet connection detail screenshot is as follows:

Please tell me any changes that I must make and also are there any WAMP settings which I should change to allow the connection to get established?
Please consider the fact that I don't have a router anywhere in this connection - just my laptop and Ethernet shield connection.

What state are the LEDs in on the ethernet board? Do they show a proper ethernet connection has been negotiated? If neither end is able to auto-negotiate uplink mode you may well need a special cross-over cable.

Are you running a firewall?
Have you checked if your server is actually listening on that interface?

@Majenko all the LEDs i.e. the full duplex ,LINK, 100M,COLL are blinking.

@IOBToolkitTeam yes my mcAfee runs a firewall. How to check if my server is listening on that interface. when i enter 192.168.0.1 in browser i am able to view the WAMP server page. if that's what you mean

With everything flashing like that it does sound like a cable problem. Most likely you need a cross-over cable. That's one where at one end of the cable the orange and green wires are swapped with each other.

@Majenko Is everything else fine.?? I mean my IP assignment and the code?

If you're running firewall, it probably blocks your Arduino. Since I'm not using windows since 1999, I can't help you with that. :)

@IOB Toolkit Team I tried turning off my firewall and then running the code again but without any success

@Majenko the LINK, FULLD, 100M,COLL LEDs are constant, they are not blinking, but yes in High state.  The TX and Rx LED blink occasionally and with that the LINK LED also flickers

Your program is fine. I have just run it and see GET requests on my Apache server: 192.168.1.4 - - [26/Jan/2016:21:34:50 +0000] "GET /Ethernet/getData.php?value=9 HTTP/1.1" 404 475 "-" "-" so it is either your cable or your PC.

@Majenko, I will try with a cross over Cable then

After uploading the sketch from your laptop you should disconnect your Arduino and Ethernet shield setup from your laptop and then use a switch.
Connect the same setup to the switch at one end and the other end of the switch must be connected to your laptop then you can try to access your web page using IP address you specified in Ethernet sketch.

Welcome to Arduino SE! As we here try to keep the quality of answers and questions high could you please fix any grammatical or spelling errors in your answer?

Well, the problem has been solved. The Ethernet shield was not properly stacked onto the Arduino board which caused connection to fail.

Could you edit and expand your answer on how it was not properly stacked...? Were some of the pins bent, or badly soldered, or was the shield just not seated correctly? Also, could you mark your answer as the accepted answer, in order to remove it from the Unanswered Questions list? Thx.


text:
Both red and blue led of ESP8266 stays on
I've connected ESP8266 to Arduino UNO. After a getting a huge trouble I successfully managed to run some AT commands. I have also tested AP mode.
Then I got some trouble with software serial communication with Arduino and decided to change baud-rate to 9600 (previously it was 115200).
I used AT+IPR=9600 command to change it.
After that blue led of esp stays on and not taking AT commands any more, but output some gibberish to serial monitor with few ascii text like below:
ets Jan  8 2013,rst cause:4, boot mode:(3,6)

wdt reset
load 0x40100000, len 1396, room 16
tail 4
chksum 0x89
load 0x3ffe8000, len 776, room 4
tail 4
chksum 0xe8
load 0x3ffe8308, len 540, room 4
tail 8
chksum 0xc0
csum 0xc0

2nd boot version : 1.4(b1)
SPI Speed      : 40MHz
SPI Mode       : DIO
SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

Note: I know it consumes a lot power tried external 3.3V power supply and voltage divider for rx pin.
Any help would be appreciated.

I have exactly the same after running that command "AT+IPR=9600".
Any update on how you fixed this?

I fixed this by updating its firmware @rabs

Here I posted what I did to solve this error. I hope somebody finds it helpful: http://bbs.espressif.com/viewtopic.php?t=4597#p15844

If you have too, you can find the firmware for the ESP8266 here and re-flash it.
There's some good info here about the instruction set.
With respect to your issue of the blue (traffic) light staying on, I can't imagine that the baud command would have caused an issue. Perhaps you need to double check your circuit and make sure that the Rx pin of the ESP8266 is not being held high.
What happens with only 3.3V and GND connected to the ESP8266?
Also the output you're getting is similar to the output from “AT+GMR”. Are you sending it that in a loop by chance?

If I only connect 3.3V and GND then only red led stays on (as usual). But if I pull CH_PD to high (connect to 3.3V using a 10K resistor) then blue led stays on. @James


text:
Arduino can't multiply?
I have a value I'm taking from a sensor module, which is 2500 when the sensor is facing a light source. This reads to my code and can be saved perfectly fine. When I try to find the weighted average of a set of values (2500*1000+2500*2000+2500*3000 etc), the Arduino comes out with very weird answers. For example
2500*1000=9632
If I just compute 2500*1000 on its own, the answer still comes out the same! The results come out negative if I use int so I switched to using double (just in case the values created were too big), this stops producing negatives as expected but the result is still like it is above.. I have no idea why.. any ideas?

Fixed it! The problem is that if you multiply a double by an int it turns into an int... I was using doubles for everything but then my weight was using the counter variable, i (e.g. 1000*(i+1)).. This turned the end result back into an int!

No. double × int → double. Actually, “doubles” are just floats on Arduino (32 bit, i.e. single precision).

Hmm, but then why did this happen:
val(double)weight(double)(i(int)+1) = the integer result and not the double?
Even though it was stored in a variable defined as a double.. Im trying to describe the problem in a way that will help people stuck with the same issue because this had me confused for ages

Show your code -- it could be how the results or intermediate results are stored.

for (int j = 0; j < NUM_SENSORS; j++)
{
sensorTotal+=sensorValues[j]; //This works
sensorWeighted+=sensorValues[j]1000(j+1); //This dosent
}
problem fixed by casting the j inside (j+1) to a double.

Makes little sense to me. If sensorValues[j] is int, (sensorValues[j] * 1000) will be computed as an int, no matter what you have in the next multiplication. You should probably show a little more of your code (at least the relevant declarations with the types). Add that to the question, indented by four spaces.

(2500*1000) % 2^16 = 9632

2500 * 1000 = 9632 is exactly what you expect with 16-bit integers. You
should use long integers instead:
2500L * 1000L == 2500000L

Floats work also, but are more expensive:
2500.0 * 1000.0 == 2500000.0

although I do not recommend testing for exact equality of floats (it
works here because these numbers are exactly representable).


text:
Branching Bus for Sensor
I am looking to setup a system where I have a master Arduino polling a number of sensors.
The way I am thinking is hooking the master TX line to the sensors RX line(and the opposite for the other line)
Questions

How long can the lines be?
Can the lines branch?

I have a page about connecting Arduinos using RS485. You can connect multiple devices up like this:

That has a reasonable range, 20 metres or more.

On that page I describe a Rolling-master system where each device takes turns to be the master and transmit information to the other devices. It also manages some devices not responding.
This screenshot shows the various devices "talking" during their timeslot:

In that particular case there were 3 devices active out of 4 configured.

I have a master ardunio polling a number of sensors.

I'm assuming in my answer that you have an Arduino at each sensor point (you could use a cheap ATtiny85 or something). That would be needed to run the rolling master code.

Does the bus need to be straight or can it branch?

I don't offhand see why you can't branch. The two wires are in parallel to each device, so I suppose you could take a branch off at some point.

From what I can see RS485 does not like branches. However what I have come up with is running two twisted pairs. One being return and that allows me to have T junctions.

How many sensors and what kind are they?
What Arduino do you have?
Basically you could use 1 Arduino Output per sensor if you have enough, or you are going to need to use a multiplex technique via additional electronic components.
The only other solution would be to use communication (I2C/Serial/etc) to receiving nodes at the sensor.

MPU 6050 with an Ardunio on each sensor to send the data onto the bus.

@Catprog Try and read up on SPI. You may not need the Arduinos at each MPU6050 if you use that protocol.


text:
What is the relation between Arduino's clock and possible VGA resolution?
I have seen it said over and over (in different places) that in order to achieve 640x480 resolution out to a DB15 VGA connection, the arduino would need to be clocked at 25Mhz or that at half resolution it would need to be clocked at 12.5Mhz.
What is the relation between resolution and internal clock? I would expect that so long we can feed the signal fast enough that would be enough.

I doubt if that would be fast enough. See my thread about connecting to a VGA monitor.
Borrowing from that page, so as to not make a link-only answer ...

For 640x480 pixels of active video you have something like this:

Vertical Sync
Let's start with the vertical sync pulses. In fact, we'll show how all the timing data can be derived from three figures:

The screen refresh rate (eg. 60 Hz)
The screen resolution (eg. 640 x 480)

So what is the refresh rate? It's the rate at which the entire screen is redrawn. If you ever looked at Windows screen resolution you probably saw something like this:

That's the refresh rate: 60 Hz (60 times a second). This figure was probably originally chosen because it is the mains frequency in the USA, so that would minimize the artifact of mains hum bars appearing on the screen, in the days of CRT monitors.
The other figure of interest is the screen resolution.
In our case we are going for the minimum we can (640 x 480) and seeing where those figures lead us.
Starting with the refresh rate, a 60 Hz refresh rate will require a "vertical sync" pulse 60 times a second, or a period of 1/60 (16.66 ms).

Generating vertical sync pulses
This code in my VGA output sketch generates the vertical sync pulses:
  // Timer 1 - vertical sync pulses
  pinMode (vSyncPin, OUTPUT);
  Timer1::setMode (15, Timer1::PRESCALE_1024, Timer1::CLEAR_B_ON_COMPARE);
  OCR1A = 259;  // 16666 / 64 uS = 260 (less one)
  OCR1B = 0;    // 64 / 64 uS = 1 (less one)

The clock period is 62.5 ns (1/16000000). By applying a prescaler of 1024 the timer counts up once every 64 µs. So to get a period of 1/60 of a second (16666 µs) we need to count up to 260 (16666 / 64 = 260). Since the timer counts are zero-relative we set OCR1A to count up to 259. This sets the frequency of Timer 1.
Then we need to set the pulse width by putting the correct value in OCR1B. We want a pulse width of two lines. One line is 1 / 60 / 525, namely 31.7 µs. So two lines would be 63.4 µs. This is close enough to exactly one timer count (64 µs). So OCR1B is set to zero (being zero-relative, making it zero gives a count of 1).
Timer 1 is configured to "clear B on compare" which effectively means that it toggles the output pin (D10 on the Uno) so it is high for the duty cycle width (64 µs) and low the rest of the time. If you wanted the opposite sync pulse polarity, change CLEAR_B_ON_COMPARE to SET_B_ON_COMPARE.
The timer is also set up to generate an interrupt, which is used to tell the code that we are starting another vertical cycle, by setting the line count to zero:
ISR (TIMER1_OVF_vect)
  {
  vLine = 0;
  messageLine = 0;
  backPorchLinesToGo = verticalBackPorchLines;
  } // end of TIMER1_OVF_vect

Horizontal sync
Horizontal sync pulses tell the monitor when to start drawing each line.
To calculate the horizontal sync frequency we need to divide the overall frame rate (60 Hz) by the number of total lines (525 if you count the sync pulse itself, and the front and back porches).
In other words:
 (1/60) / 525 * 1e6 = 31.74 µs

We also need to know the sync pulse width. That is documented to be 96 pixels, so we need to know the width of one pixel. That would be the figure above, divided by 800 (being the total screen width including the sync pulse, and front and back porches).
Thus that is:
((1/60) / 525 * 1e9) / 800 = 39.68  ns
1 / (((1/60) / 525 * 1e6) / 800) = 25.2 MHz

So our pixel width is 39.68 ns and the pixel clock is 25.2 mHz.
The horizontal sync pulse width is 96 pixels, so we want a pulse of:
96 * 39.68 ns = 3.8 µs

Generating horizontal sync pulses
Now we are ready to set up the timer for the horizontal sync pulses:
  // Timer 2 - horizontal sync pulses
  pinMode (hSyncPin, OUTPUT);
  Timer2::setMode (7, Timer2::PRESCALE_8, Timer2::CLEAR_B_ON_COMPARE);
  OCR2A = 63;   // 32 / 0.5 µs = 64 (less one)
  OCR2B = 7;    // 4 / 0.5 µs = 8 (less one)

The clock period is 62.5 ns (1/16000000). By applying a prescaler of 8 the timer counts up once every 0.5 µs. So to get a period of 32 µs we need to count up to 64 (32 / 0.5 = 64). Since the timer counts are zero-relative we set OCR2A to count up to 63. This sets the frequency of Timer 2.
Then we need to set the pulse width by putting the correct value in OCR2B. We want a pulse width of 96 pixels (3.8 µs). So OCR2B is set to 7 (being zero-relative, making it 7 gives a count of 8, which is 4 / 0.5).
Again, if you wanted the opposite sync pulse polarity, change CLEAR_B_ON_COMPARE to SET_B_ON_COMPARE.
The timer is also set up to generate an interrupt, which has the sole purpose of waking the processor up from sleep, so it can draw each line with exactly the same delay after the pulse. If it wasn't asleep, there would be a variation of two to three clock cycles (since an interrupt cannot occur during a single instruction) and this gives very bad-looking "jitter" on the screen.
ISR (TIMER2_OVF_vect)
  {
  } // end of TIMER2_OVF_vect

Pixel data
Now things get tricky ...
Let's see how long we have to draw 640 pixels:
((1/60) / 525 * 1e9) / 800  * 640 = 25396.82 ns (25.39 µs)

It just can't be done on this processor. The clock period itself is only 62.5 ns, so there is no way we can output a pixel every 39.68 ns (that is: 25396.82 / 640 = 39.68).
The fastest way we can get bits "out the door" is using the SPI hardware. That can run at a maximum clock rate of twice the system clock, that is, one pixel every 125 ns. So we will have to settle for having the pixels 4 times as wide. A horizontal resolution therefore of 160 pixels. Since we will display 8-pixel characters, that gives us 20 characters per line.

Summary
Even at 25 MHz processor speed (which exceeds its spec) you won't be able to clock out pixels fast enough for 640 pixel width (since the fastest SPI speed is half the processor clock speed).

I would expect that so long we can feed the signal fast enough that would be enough.

That's the tricky bit. To output data you have to do more than merely send it. You have to read it from memory, so it would take a least a couple of clock cycles to do that.

Example of working at that resolution
A screen shot of my sketch in action (160 characters wide - 640 pixels and 30 characters high - 480 pixels, which is 16 pixels each as they were "doubled" in height to make them look in proportion). The font data was 8x8 pixels, and thus they appear as 16x16 on the screen.

So does that mean that there really isn't a direct relation between clock speed and resolution? Other than, the clock must be faster than this

To work even at that speed the processor speed needs to be a multiple of the VGA clock, or close enough for the monitor to accept. (Looking at my figures the pixel rate is not in fact a multiple of 39.68 ns, so I am guessing that my monitor was able to adjust).
You could get better results by having a system clock which was an exact multiple of 39.68 ns (around 25 MHz - precisely 25.201613 MHz) - which is what you suggested in the question. However that just gives more accurate timing, you would still get similar resolution to what I show here.
So yes, to work on more monitors you should have a direct relation between clock speed and resolution.
I seem to have a 25.175 MHz crystal in my parts drawer, so perhaps I experimented with this a while back. Of course, you have to recalculate the other timings if you use that, and the processor is running out of spec.

It just can't be done on this processor. - I have managed to generate VGA at that kind of resolution using an 80MHz PIC32 and it was very very tight even then - it requires special optimizations to get the maximum speed out of it. Not much processing time left for anything else, and certainly no chance of any other interrupts being used - I even had to have the VGA code generate its own vsync-linked millis() since the system millis() could no longer run. No chance on a little Arduino ;)

So does that mean that there really isn't a direct relation between clock speed and resolution? Other than, the clock must be faster than this.

See my added notes in the answer.

The empty ISR can be conveniently defined as EMPTY_INTERRUPT(TIMER2_OVF_vect);.

I wrote that when I was young and foolish. ;) - However you are right, that would be faster.

Out of curiosity, what would be a better off the shelf chip for generating a VGA 640x480 60Hz signal? Preferably something that is not super over powered, easy to use, and preferably open source.

Take a look at http://www.gammon.com.au/forum/?id=12623 - that guy used an AD725 chip which outputs composite video in NTSC or PAL. This probably doesn't really answer your question, but it is interesting. Also search for tinyvga - there are various chips and boards around for generating VGA for microcontrollers.

That is awesome, thanks. I was looking for that post but I couldn't find any specifics. I thought that was done on an uno and it was one of the reasons I thought this was possible.

Yes, but he didn't have 640x480 resolution. From the linked page: The game has a display resolution of 104x80 with 256 colors.

In case someone finds this page later and wonders what I ended up using. I found an fpga board that was open source and used a Spartan chip called gameduino. It was cheapish, and readily available. More than enough for my prototyping needs.


text:
Why is my Adafruit motor shield not spinning my motors?
I'm using the Adafruit Motor Shield v2.3. I'm powering the Arduino with a USB cable and I'm powering the motor shield with a 9 volt battery.
I removed the vin pin, and I'm using this tutorial/code to make the DC motor spin.
I've tried 3 different kinds of DC motors, but none of them will do anything. The Arduino works for normal sketches, like lighting up LEDs, but I can't get the motors to work.
Any ideas?
Edit: I'm using Adafruit's "Motor Test" code from the Motor Shield v2 library, as shown below. The motor is on port 1.
// Adafruit Motor shield library
// copyright Adafruit Industries LLC, 2009
// this code is public domain, enjoy!

#include <AFMotor.h>

AF_DCMotor motor(4);

void setup() {
  Serial.begin(9600);           // set up Serial library at 9600 bps
  Serial.println("Motor test!");

  // turn on motor
  motor.setSpeed(200);

  motor.run(RELEASE);
}

void loop() {
  uint8_t i;

  Serial.print("tick");

  motor.run(FORWARD);
  for (i=0; i<255; i++) {
    motor.setSpeed(i);
    delay(10);
 }

  for (i=255; i!=0; i--) {
    motor.setSpeed(i);
    delay(10);
 }

  Serial.print("tock");

  motor.run(BACKWARD);
  for (i=0; i<255; i++) {
    motor.setSpeed(i);
    delay(10);
 }

  for (i=255; i!=0; i--) {
    motor.setSpeed(i);
    delay(10);
 }

  Serial.print("tech");
  motor.run(RELEASE);
  delay(1000);
}

You said "this tutorial/code" but there is nothing. Did you forget to add a link?

@JakeC - Thanks, I had copied it from my reddit post. It's fixed now.

What motors are you using? Are they rated to run at 9 volts? How good is the connection to the motor? It looks like from the picture that the pins are shorting on the casing. Do you have a multi-meter? Have you checked the voltage of the battery?

ACtually, ignore the above, according to Adafruit, you cannot use a 9V battery. See: https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/faq#faq-14

As pointed out here countless times before, a 9v "transistor" battery is the wrong choice for most motor projects, as it has minimal current capability.  Don't use it!

a micro servo SG90 was connected with the motor shield too.

A couple of things I see...
1.) Your motor leads may be shorting out of the housing of the motor. make sure they are not.
2.) You may have the motor on the wrong port for the given code:
On line 7 of the code it reads: AF_DCMotor motor(4);
So try switching physically your motor to port 4.
3.) Also, this board has an I2C address and I dont see that addressed anywhere in the code. You can check to see what the I2C address is with this code. It will also show you that the motor control board is indeed responding.
// --------------------------------------
// i2c_scanner
//
// Version 1
//    This program (or code that looks like it)
//    can be found in many places.
//    For example on the Arduino.cc forum.
//    The original author is not know.
// Version 2, Juni 2012, Using Arduino 1.0.1
//     Adapted to be as simple as possible by Arduino.cc user Krodal
// Version 3, Feb 26  2013
//    V3 by louarnold
// Version 4, March 3, 2013, Using Arduino 1.0.3
//    by Arduino.cc user Krodal.
//    Changes by louarnold removed.
//    Scanning addresses changed from 0...127 to 1...119,
//    according to the i2c scanner by Nick Gammon
//    http://www.gammon.com.au/forum/?id=10896
// Version 5, March 28, 2013
//    As version 4, but address scans now to 127.
//    A sensor seems to use address 120.
// Version 6, November 27, 2015.
//    Added waiting for the Leonardo serial communication.
//
//
// This sketch tests the standard 7-bit addresses
// Devices with higher bit address might not be seen properly.
//

#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(9600);
  while (!Serial);             // Leonardo: wait for serial monitor
  Serial.println("\nI2C Scanner");
}

void loop()
{
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      Serial.print("Unknow error at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.println(address,HEX);
    }
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");

  delay(5000);           // wait 5 seconds for next scan
}

Thanks for the code! I had soldered my pins on a bit crooked, so it was difficult to push them all the way in. When I ran your test, it couldn't find any I2C devices, and according to some Google results, that problem can be caused by various pin connectivity issues. I detached the motor shield from the Arduino, straightened out the pins, reinserted the motor shield as firmly as I could, and then everything started working!

@Pikamander2  :) Glad I could help!

Per the comments above, and the documentation from Adafruit, a 9V battery is insufficient for use with motors as they do not provide enough current.

Well, I've tried it with 2 AA batteries as well, but no luck. Here's what it currently looks like: http://i.imgur.com/IyTPnfx.jpg

2 AA is only ~3V, nowhere near enough. Per the Adafruit guide, the Green LED needs to be lit brightly and from the pic it doesn't appear to be as bright. You would need to use at least 4 AA batteries to meet the 5V threshold and no more than 8 to stay under the 12 V maximum.

Here it is with a Tenergy 9.6V 2000mAh battery (fully charged). It's lit up a lot brighter, but the motor still does nothing. http://i.imgur.com/Uursw2z.jpg

At this point I would update your original question with the new details, and my previous comments would apply there. Check the connections to the motor (they still don't very good). Maybe use a multi-meter to check the output of the board.

Also, I've added the code to the original post. It's just the standard Adafruit motor example code, with no modifications

My multimeter is giving me 0 from all of the motor ports, so the motor shield isn't putting out any power. Any idea why?

I see that this is still not working even with a proper battery. My next best guess is you need to update your library:

// Adafruit Motor shield library
// copyright Adafruit Industries LLC, 2009
// this code is public domain, enjoy!

#include <AFMotor.h>

Judging by 2009 and AFMotor.h you have a copy of an old version of the library. I recommend getting the latest version and following the official tutorial.

The issue turned out to be that my bent pins weren't pushed all the way in to the Arduino, so Accentrix's answer was the most helpful. Still, thanks for the link, I hadn't noticed that I was using an old library.

This was my problem. For the old version of the adafruit motor shield board, the header is named "AFMotor.h". Mine is the Adafruit motor shield v2 and the correct header file is named "Adafruit_MotorShield.h". If you make this mistake then the problem is exactly as described, everything looks like it should work but nothing happens.


text:
mthread and multiple header files
I'm using mthreads (https://github.com/jlamothe/mthread) for my arduino. But now as the project is getting bigger, it would make sense to break it up in several files.
I successfully outsourced already a part which is not threaded. But somehow I cannot make up my mind how to use mthread in conjunction with several header files.
here is what I got:
main: call header:
#include "tcan.h"

tcan.h:
#ifndef tcan_h
#define tcan_h

#include "Arduino.h"

class tcan : public Thread {
  public: tcan();
  protected: bool loop();
  private:
};
#endif

tcan.cpp
#include "Arduino.h"
#include "tcan.h"
#include <mcp_can.h>

bool tcan::loop() {
  // lala
  return true;
}

but I get an error when compiling:

tcan.h:6:28: error: expected class-name before '{' token  class tcan :
  public Thread {

Thanks in advance

Check for circular #includes... The error can be caused by including Arduino.h twice.

The compiler error is due to that the compiler does not know what Thread is.

tcan.h:6:28: error: expected class-name before '{' token class tcan : public Thread {

The issue is that the header file is not complete. A good practice is to include all header files that are needed to read the header file. As Thread is defined in mthread.h the tcan.h file should be:
#ifndef tcan_h
#define tcan_h

#include <mthread.h>

class tcan : public Thread {
public: tcan();
protected: bool loop();
private:
};
#endif

Cheers!

that was the right hint "Assuming that Thread is defined in mcp_can.h".
Of course I need to include "<mthread.h>". Thanks for the hint! It's working now.

Great! I will update the answer with the correct include.


text:
arduino pro mini downloading?
I purchased the arduino pro mini atmega328 and equipped it with FTDI breakout board with USB, a battery charging board, Wireless transmitter and a wireless receiver.  I'm assuming they can all be connected.  My question is, how do I download programs to the arduino board?  And where might I find specific programs to download?

Have you done any research at all? Google will find all of your answers.

https://www.arduino.cc/

The Arduino Pro Mini has a row of connections at the small end that align with the connections on the USB-to-Serial board you have.  They are marked GND - VCC - RXI - TXI and should be in the same order as the connector on the FTDI board. I think that the pin marked GRN on the Arduino will align with the connector marked DTR on the USB-to-Serial board, but please make sure that VCC aligns with 5V!
With the FTDI board plugged into the Arduino, you can plug your computer into the FTDI board's USB port and when you run the Arduino IDE programming tool, that USB port should say that it's connected to a serial port.  Pick the "Arduino Pro or Pro Mini" as your board, then pick your processor (most likely the "ATmega328 (5V, 16MHz)" and finally your port (that serial port you found).
Now when you upload your Arduino program to the Arduino, it will know the board your have and the port to use.
As for programs to use, start simple and get the onboard LED to blink.  From there, you'll have the basics down for creating a program and getting it to the Arduino.  You'll find tons of example programs (called sketches in Arduino land) that will help you connect all your fun wireless gizmos!
As noted above - Google is your friend.  There are many places to go for examples and help.  Start with some of the commercial sites like Adafruit and SparkFun. Their staff really supports the Arduino community with how-to videos, libraries, examples, etc.


text:
Can Android phone can be used instead of( or with) Arduino as controller?
I am Android application developer and I want to modify regular toy RC car which can be controlled by Android phone. I want to use 2 Android phones: 1 as remote controller, 1 as controller in RC car. I want to use sensors like GPS, Mobile network, Wifi in RC car in RC car side. I want to know: can I use Android phone as controller in RC car. I am thinking about 2 options:

phone as controller (without arduino) - this option would be the
best
if phone cannot give commands maybe with arduino, while
using phone's sensors like gps, mobile network, wifi, bluetooth

Is this possible? If yes, what tools I should use to connect?

In what way were you hoping to physically connect the phone to the sensors and control circuitry?

You cannot directly control your RC car using and Android phone if you are talking about a normal RC car. If you have an RC car that can be already connected via bluetooth this is another story.
So for normal RC car you would need to have:
AndroidPhone -> Network -> AndroidPhone -> SerialInterface -> Arduino -> RC


text:
How to switch on 32A/240VAC with Arduino?
I have an air conditioner switch rated at 32A/240V AC - how do I turn this on using Arduino and Relay.
I'm based in India and I am unable to find a relay switch rated higher than this.
I don't want to try anything that results in a fire hazard. My aim is to switch on the AC with my mobile phone. I'm using Arduino Uno with a 2.4GHz transceiver for communication.

Google is your friend; for instance http://www.seeedstudio.com/wiki/Grove_-_SPDT_Relay%2830A%29, http://www.ebay.com/bhp/30a-relay, http://yourduino.com/sunshop2/index.php?l=product_detail&p=327 and so on.

Does the AC have a remote? If yes, you can possibly emulate it.

You need to look beyond "Arduino compatible" peripherals. All relays are Arduino compatible if you understand even the basics of electronics. For 32A you might stand a better chance finding a "Solid State Relay", but it depends on what stockists are available in India.

Just go with a solid state relay: you can search on ebay for SSR-40DA (240V, 40A, from China around 4$) or, better, SSR-100DA (240V, 100A, from China around 6$). For 32A you should definitely mount it on an heatsink (they sell quite a lot of them on ebay).
The main advantage of that kind of SSR is that you can command them directly from the arduino. No transistors, no limiting resistors, just connect the ground and the pin and you are done.
With a relay my arduino halted often (probably because of the 5V-12V boost, but it was necessary to drive the 12V relay). In the end I switched to an SSR and... Works like a charm. And since it is quite cheap I suggest you to use it.

I don't want to try anything that results in a fire hazard.

That's a good idea.
Besides those toy relays there are real ones:
440 V AC * 63 A (Around there, you can find smaller ones too)
BTW: Don't rely on what's printed on the relay itself, with cheap Arduino relay modules. 230V and some current need proper handling by the PCB board as well (size and distance of the copper tracks on the scondary side)
If you want a solution that could be certified (or certifiable) as "safe" there probably won't be an Arduino involved or being built by anyone asking questions like you do  ;(   (sorry)

What about staying with small relay and just add a contactor? The relay will deal with the low current 230v to drive the contactor and the contactor would deal with the high current.

As in https://en.wikipedia.org/wiki/Contactor

The simple answer is: you need to find a relay rated high enough for the voltage and current. There's no way you can make a small relay handle a large current, and relays cannot be joined together to share the load.
If a relay is not available in your country (and I seriously doubt that - you're probably just looking in the wrong places - instead of looking for things on Amazon or eBay try looking at proper industrial electronics suppliers) then you would have to come up with something more creative.
How about designing and building a small electro-mechanical system that physically changes the position of the existing switch for you? Solenoids to press the right bits of the switch, or motors to turn the right bit round, etc.