Showing posts with label Sketches. Show all posts
Showing posts with label Sketches. Show all posts

Thursday, January 20, 2011

ACS712 Low Current Sensor Breakout test.

Despite finding a solution to solve the problem of knowing when the speed controllers are on or off and have abandoned the ACS712 Low Current Sensor Breakout for this purpose the sensor continues to be useful to monitor the battery status.
Figure 1
After some research and some help that I have got from this forum I could do a procedure to test the current sensor. First I have created the circuit shown in figure 1 above, which consists of two parts. One part that includes the Arduino board, the current sensor and a digital voltmeter (I used a multimeter). The other part includes the 9V battery, a resistance, an on/off toggle switch and a micro motor. The idea is to measure the current that flows from the 9V battery to the micro motor.
Before using the current sensor we must calibrate it. Looking at the sensor specifications I have noticed that the output from the sensor IC is Vcc/2 (~2.5 V, in this case) if there is no current. This is because the sensor IC has a bidirectional output. If the current is "forward", its output is between Vcc/2 and Vcc (~2.5 V and ~5 V, in this case); if the current is "backward", its output is between Gnd and Vcc/2 (~0 V and ~2.5 V, in this case). So let's try to set the board's output to 2.5 V with no input current. According to the note on the schematic, the two trimpots need to be turned in different directions to increase the values they control. The current sensor uses a hall-effect sensor internally. Therefore, it should be used a diddle stick (a small non-metallic, non-conductive screwdriver like tool for making fine adjustments) to adjust the trimpot (I used a toothpick and cut it with a x-ato). With a diddle stick, we rotate the "Vref" trimpot until we get the value of ~2.5 V. If we verify that there are great fluctuations in readings, rotates the "Gain" trimpot until you get readings closer to each other. When we have a more or less stable value, then turns on the motor and immediately we can see an increase in the value of the voltage read by the voltmeter. Remind that the current sensor outputs an analog voltage that varies linearly with sensed current. To read the value of the current sensor in analog pin "0" from the arduino board, I have done a sketch that can be seen below. The values read from the analog pin "0” ranging from 0 to 1023.
/*
  Reads values from a ACS712 low current sensor connected to
  the analog input pin 0 on Arduino board and print them to
  the serial monitor.
*/

void setup() {
  Serial.begin(9600);         // sets the serial port to 9600
}

void loop() {
  int value = analogRead(0);  // read analog input pin 0
  Serial.println(value, DEC); // prints the value read
  delay(1000);                // wait 1s for next reading
}
To see the variation of values read from the analog pin "0” in real time I have created a graph using a pair of perl scripts. The first script is a flexible, command-line-oriented frontend to the program “Gnuplot”. It creates plots from data coming in on STDIN or given in a filename passed on the command line and can be found on this site. The second script - which can be seen below - allows us to read from the serial port the stream of values received in analog pin "0" of the Arduino board and sends them to the STDIN.
#!/usr/bin/perl -w

use strict;
use Device::SerialPort;

my $port = "/dev/ttyUSB0";

my $ob = Device::SerialPort->new($port);
$ob->databits(8);
$ob->baudrate(9600);
$ob->parity("none");
$ob->stopbits(1);

select STDOUT;

$| = 1;

my $n = 0;
my $buffer = "";
while(1) {
  my $byte = $ob->read(1);
  if($byte =~ /^\d/) {
    $buffer .= $byte;
  } elsif($byte =~ /^\n/) {
    if($buffer =~ /^\d+/) {
      print STDOUT "$buffer\n";
      $n++;
      sleep(1);
    }
    $buffer = "";
  }
}
undef $ob;
The connection between the two scripts is done with a pipeline (pipe character "|"). The command to start the plot is shown below.
$ ./ReadSerialPort.pl | ./feedGnuplot.pl --stream --lines --points \
--legend "Readings" --title "ACS712 Low Current Sensor Test" \
--ymin 450 --ymax 600 --xlen 100 --xlabel "Time (s)" --ylabel "Value"
In figure 2 we can see the plot in real time and can be observed that there is a sudden increase of the values readed from the sensor, which corresponds to the moment when the motor is turned on. Later, we can observe a decline of values, which correspond to the moment when the motor is turned off.
Figure 2
As can be seen in the graph of the figure 2, the readings still have a fluctuation although of having reduced the gain as much as possible. The graph displays the raw value from the analog to digital converter (ADC) in the Arduino. After reading some material on the Arduino forum about smoothing out the values, measuring voltage and converting the raw ADC value to something more useful, I decided to reduce the fluctuation of the readings using the average of 10 readings taken at an interval of 10 ms and then send the result to the Serial port. The new sketch can be seen below.
/*
  Computes the average of 10 readings at intervals of 10 ms
  from a ACS712 low current sensor connected to the analog
  input pin 0 on Arduino board and print them to the serial
  monitor.
*/

int counter = 0;
int total = 0;

void setup() {
  // sets the serial port to 9600
  Serial.begin(9600);
}

void loop() {
  // read analog input pin 0
  int reading = analogRead(0);
  // add the reading to the total
  total = total + reading;
  // incrementing the counter
  counter = counter + 1;
  // if have already been done 10 readings...
  if (counter >= 10) {
    // set the counter to 0
    counter = 0;
    // calculate the average
    int average = total / 10;
    // send it to the serial port (as ASCII digits)
    Serial.println(average, DEC);
    // set the total to 0
    total = 0;
  }
  // wait 1 ms for next reading
  delay(100);
}
As one can now see in graph of the figure 3, the moments when the motor is turned on and off is now clearer.
Figure 3
The sketch can be improved to reject the values that are not within the expected range making use of several statistical criteria. After some investigation I found a statistical method easy to implement to reject the "bad" data, known as the Chauvenet's criterion. The implementation of the method can be seen in the following sketch.
/*
  Computes the average of a sample of N readings at intervals
  of 1000/N ms from a ACS712 low current sensor connected to
  the analog input pin 0 on Arduino board and print them to the
  serial monitor.
  This sketch uses the the Chauvenet's statistical criterion
  for rejecting the bad readings.
*/

const int num_readings = 20;
// Chauvenet’s criterion for rejecting a reading
// http://people.ohio.edu/bayless/seniorlab/lecture1.ppt
// http://people.ohio.edu/bayless/seniorlab/chauvenet.pdf
// Consult the table of the pdf document to find the ratio
// of maximum acceptable deviation to precision index for
// this sampling.
const int mad = 2.24;
int readings[num_readings];
int index = 0;

void setup() {
  // sets the serial port to 9600
  Serial.begin(9600);
}

int average() {
  int total = 0;
  for(int i=0; i<num_readings; i++)
    total = total + readings[i];
  return total/num_readings;
}

float standard_deviation(int avg) {
  int total = 0;
  for(int i=0; i<num_readings; i++)
    total = total + pow((avg - readings[i]), 2);
  return sqrt(total/num_readings);
}

void loop() {
  // read analog input pin 0
  int reading = analogRead(0);
  readings[index] = reading;
  // incrementing the index
  index = index + 1;
  // if have already been done 10 readings...
  if (index >= num_readings) {
    // set the index to 0
    index = 0;
    // compute the average
    int avg = average();
    // compute the standard deviation
    float std = standard_deviation(avg);
    
    float madstd = mad * std;
    float lowlimit = avg - madstd;
    float highlimit = avg + madstd;
    
    int count = 0;
    int total = 0;
    for(int i=0; i<num_readings; i++) {
      // Check if the values of the readings are within the limits.
      if(readings[i] >= lowlimit && readings[i] <= highlimit) {
        total = total + readings[i];
        count = count + 1;
      }
    }
    // compute the new average
    int newaverage = total/count;
    // send it to the serial port (as ASCII digits)
    Serial.println(newaverage, DEC);
  }
  // wait 1000/num_readings ms for next reading
  delay(int(1000/num_readings));
}
The figure 4 shows the graph of the average variation of the readings after being analyzed with the Chauvenet's statistical criterion.
Figure 4
When comparing with the graph of figure 3, we can see that there is not much difference between the two graphs. However, these statistical methods are useful because many sensors are very sensitive to external influences that may cause momentary readings outside of the expected values.
Figure 5
In the figure 5 we can see the circuit in operation connected to my Gentoo laptop. I lost a lot of time with this sensor but finally, I think I understand how I can use it.

Tuesday, December 21, 2010

Sometimes the best solutions are the simplest ones.

To solve the problem of knowing when the speed controllers are initialized or not, I decided that the best solution to solve the problem would be to use a current sensor. So I bought a current sensor. But unfortunately this solution has proved difficult to implement since the sensor is not working as I expected. To test the sensor I connected it to a Arduino board. The first problem I encountered is that the sensor reads the same values, regardless of whether or not connected to a circuit. I also tried to calibrate the sensor by following the procedure that is on the product page but without success. The second problem has to do with the little information available about this sensor.
However, while I tried to solve the sensor problem I found a simple solution to the problem of whether the speed controllers were initialized or not using only one on-off switch push. There is a switch designated switch DPST (Double Pole, Single Throw), which consists of a pair of on-off switches which operate together but in different circuits. The quadcopter has two independent circuits, one connecting the motors and speed controllers to one battery and other circuit that connects the Seeeduino board to the other battery. To test the idea I had based on this example from the page of the Arduino board. I designed a scheme that can be seen in figure 1 and that lets me know when the green LED is turned on or off.
Figure 1
As can be seen in the scheme of the figure 1 there are two independent circuits. One include the 9V battery and the LED and the another is on the Arduino board. Both circuits are connected to the on-off switch push. The following sketch lets me know at any moment if the LED is turned on or off.
#define SWITCHPUSH 7  // the input pin where the
                      // on-off switch push is connected

int state = -1;   // state variable will be used to store
                  // the state of the input pin

void setup() {
  Serial.begin(9600);          // open the serial port
  pinMode(SWITCHPUSH, INPUT);  // tell Arduino SWITCHPUSH is an input
}

void loop() {
  int val = digitalRead(SWITCHPUSH);  // read input value
  
  // check if the read value is different of the state value
  if(val != state) {
    // check whether the input is HIGH (switch push pressed)
    if(val == HIGH) {
      // print the string "LED is ON" to the serial port
      Serial.println("LED is ON");
    } else {
      // print the string "LED is OFF" to the serial port
      Serial.println("LED is OFF");
    }
    state = val;  // store the value read in state variable
  }
  delay(100);  // wait 100 ms between each send
}
If I press the on-off switch push turns on the LED. From the Arduino board I get to know that the LED is turned on. If I turn off the Arduino board and re-connect it again I continue to know the status of the LED, because the on-off switch push operating in different circuits. This is very simple.
Figure 2
In Figure 2 we can see the two circuits with the various components in operation. The on-off switch push is in the image upside down so we can see the connections. By comparison we can see the LED as the speed controller. Sometimes the best solutions are the simplest ones.

Friday, November 26, 2010

How to convert a string of Euler angles characters read by the 9DOF Razor IMU board into numeric values.

To guide the quadcopter in the space I will use the 9DOF Razor IMU board with the 9 Degree of Measurement Attitude and Heading Reference System (AHRS) code base. This board with AHRS code has the advantage of doing all the calculations and corrections for me. All I need to do is work out the interface. With the code one can chooses three options for receiving the data according to the constants that we define. If one sets the defined value "PRINT_DCM" to 1 then one will print the whole direction cosine matrix. If one sets the defined value "PRINT_ANALOG" to 1 then one will print the analog raw data. If one sets the defined value "PRINT_EULER" to 1 then one will print the Euler angles roll, pitch and yaw. These options are selected in the AHRS code before being compiled.
But first one needs to get the data in a format that can then be used by the Seeeduino Mega board to do the calculations to orient and stabilize the quadcopter. Reading the stream data from the 9DOF Razor IMU to the Seeeduino Mega board is a simple task and it has been shown in a previous post in which the data was transferred via a serial connection between the two boards - the diagram of the assembly can be seen in the image of the this previous post.
The data that I choose consist of the Euler angles roll, pitch and yaw and are sent by the 9DOF Razor IMU board sequentially in a text line. The line has the following format: "!ANG:0.00,0.00,0.00\r\n". To use the angles are necessary to split the line and then convert the numeric characters string parts to a numeric value (in this case a floating point number). After several failed attempts to read stream data sequentially I discovered that if I did not blocking the serial reads until the 9DOF Razor IMU board send the data often do not find the end of the text line which results in incorrect values and buffer overflow problems. To solve the problem of the serial reads may block permanently due to faulty connection with the 9DOF Razor IMU board was added a timeout. If at the end of the timeout has not been read the line the program continues its execution whiles keeping the previous angles values. This, procedure is important because if the Seeeduino Mega board lost the connection with 9DOF Razor IMU board the program can predicts code for example that here the motors are turned off and is activated a parachute, that save the quadcopter from crashing.
In the following sketch we can check the path followed to obtain the Euler angles in a numerical format from the 9DOF Razor IMU board.
#define TIMEOUT 100

// { roll, pitch, yaw }
float angles[3] = {0.0, 0.0, 0.0};

char read_char() {
  unsigned long starttime = millis();
  do {
    if(Serial1.available() > 0)
      return((char)Serial1.read());
  } while((millis() - starttime) < TIMEOUT);
  return NULL;
}

void get_angles() {
  for(int n=0; n<3; n++) {
    char buffer[9];
    int received = 0;
    char ch;
    do {
      if((ch = read_char()) == NULL) return;
    } while(ch != ',' && ch != '\r' && (buffer[received++] = ch));   
    buffer[received] = '\0';
    angles[n] = atof(buffer);
  }
}

void read_9dofahrs() {
  char beginstr[6] = {'!','A','N','G','\:','\0'};
  for(int i=0; i<5; i++)
    if(read_char() != beginstr[i]) return;
  get_angles();
}

void setup() {
  Serial.begin(57600);
  Serial1.begin(57600);
}

void loop() {
  read_9dofahrs();

  Serial.print(angles[0]);
  Serial.print(" | ");
  Serial.print(angles[1]);
  Serial.print(" | ");
  Serial.print(angles[2]);
  Serial.println("");
}
The result of this sketch can be seen in the following figure.

This short sketch will then be added to the main program that will control the stabilization and orientation in space of the quadcopter.

Sunday, November 21, 2010

Brushless Motors and Speed Controllers.

I am a beginner in electronics and although my skills are still basic, I am still searching documentation to see if I understand how I can properly put into operation one or more motors using the Arduino platform. In most open source quadcopter projects are almost always used the same speed controllers, however it should be possible to use any speed controller that works with a radio control (R/C).
I have been taking a look to several web sites and I have found that there were two main ways of how to communicate with speed controllers and put the motors running. One is to write a pulse width in microseconds directly to the i/o pins and the other is to use the Arduino "Servo" library or similar libraries like "SoftwareServo". In a previous post I have described how to put four motors running with the speed controllers that I have got for this project using the "Servo" library. Although, I have not investigated in depth the internals of the library I have noticed that the motor control is achieved by sending pulses to the speed controller or alternatively by sending an angle that can varies between 0º and 180º (the angle is converted internally to a pulse width in microseconds). However and for the speed controllers I am using, if I only send pulses to the i/o pins that will not put the motors in operation since the speed controllers need be initialized before using. So, in order to have more information available, I have downloaded of the speed controller specifications that I am using. After reviewing that document I have tried to develop an algorithm with the all steps to put the motors in operation. The procedure according to my adaptation of the document to initialize the speed controller is as follow (this procedure must be done before each use):
  1. Connect the Arduino board to the computer via USB to power up the board and set the pulse width value of the stop position on output pin (the stop position must be within the range 800 us to 1700 us for my speed controller). This procedure is like move the throttle stick to the desired stop position, and switch on the transmitter.
  2. Connect now the flight battery to the speed controler. The motor responds with 2 x beep.
  3. Increase the pulse width value (microseconds) in one unit on output pin until the motor responds with 3 x beep (the full-throttle position must be at least 350 us greater than the stop position). This is like move the throttle stick to the desired full-throttle position.
  4. Set again the pulse width value of the stop position on output pin. This procedure is like move the throttle stick to the desired stop position.
  5. If you now increase the pulse width value on output pin the motor will start running. This is like move the throttle stick from the stop position towards full-throttle.
I tried to implement the two methods described above but the only one that worked was the method that uses the library "Servo". The implementation of the procedure is now shown:
/*

  Motors: 4 x ROXXY 2827-34
  ___ESC: 4 x Roxxy BL-Control 818
  _Board: Seeeduino Mega v1.1
  
  ATENTION: Do not put the propellers in motors because this
            sketch is not well tested and can cause damage.
  
*/
#include <Servo.h>

// Set the pulse width value of the stop position to mid-point (1250 us).
#define STOPPOSITION          800+(1700-800)/2
// The full-throttle position must be at least 350 us greater
// than the stop position (1600 us).
#define FULLTHROTTLEPOSITION  STOPPOSITION+350
// My upper speed limit for safety.
#define MAXTHROTTLEPOSITION   FULLTHROTTLEPOSITION-100
// Create servo object to control four motors
Servo escservos[4];
// Variable to store the temporarily pulse width value.
int usvalue = STOPPOSITION;

void programpositions() {
  Serial.println("Type the character [p] to program the Stop and");
  Serial.println("Full-Throttle positions after connect the flight");
  Serial.println("battery to the ESC's.");
  Serial.println("The motor responds with 2 x beep.");
  Serial.println("");
  Serial.println("Type the character:");
  Serial.println("[+] to increase the pulse width value.");
  Serial.println("[-] to decrease the pulse width value.");
  Serial.println("[0] to set the pulse width value to stop position.");
  
  // Wait until get the input from the user.
  while(Serial.available() <= 0) {
    // Set the pulse width value of the stop position on output pins.
    for(int s=0; s<4; s++)
      escservos[s].writeMicroseconds(STOPPOSITION);
  }
  
  char ch = Serial.read();
  if(ch == 'p') {
    // Increase the pulse width value in one unit on output pins.
    // Exactly after a pulse width of the 350 microseconds from
    // the stopping position the motor responds with 3 x beep.
    for(int us=STOPPOSITION; us<=FULLTHROTTLEPOSITION; us++)
      for(int s=0; s<4; s++)
        escservos[s].writeMicroseconds(us);
    delay(5000);
  }
}

void set_speeds(int servo, int usvalue) {
  escservos[servo].writeMicroseconds(usvalue);
}

void setup() {
  Serial.begin(9600);
  
  // Attaches the ESC's on pins 2, 3, 4 and 5 to the servo object.
  for(int s=0; s<4; s++)
    escservos[s].attach(s+2, STOPPOSITION, FULLTHROTTLEPOSITION);
  
  programpositions();
}

void loop() {
  if(Serial.available()) {
    char ch = Serial.read();
    if(ch == '+') {
      // Increase the pulse width value.
      // The motor only starts running after increased up to 40 us.
      usvalue++;
      if(usvalue > MAXTHROTTLEPOSITION)
        usvalue = MAXTHROTTLEPOSITION;
    } else if(ch == '-') {
      // Decrease the pulse width value.
      usvalue--;
      if(usvalue < STOPPOSITION)
        usvalue = STOPPOSITION;
    } else if(ch == '0') {
      // Set the pulse width value to the stop position.
      usvalue = STOPPOSITION;
    }
    Serial.println(usvalue);
  }
  for(int s=0; s<4; s++)
    set_speeds(s, usvalue);
}
This implementation works very well for my speed controllers, but for other speed controllers the implementation will probably be different. The difference to the previous post is that instead using the value of the angles, I have used the pulse width value in microseconds and the delay after sending the angle has been removed. One immediate problem is that the Arduino board must always be connected before the speed controller which requires that board will check if the speed controller is switched on or off. If the speed controller is already connected and initialized and if for any reason you switched off the board and switched it on again, the motor can speed up to full speed because the speed controller was already set up, but as the board does not recognize it, it will make a new initialization. Therefore it is necessary to send a character to do or not the initialization of the speed controller. To solve this problem it is necessary a current sensor which will check whether the speed controller is switched on or off.

Saturday, November 6, 2010

Read 9DOF Razor IMU data via Seeeduino Mega board (Arduino Mega clone).

Figure 1
Read the data from the 9DOF Razor IMU board is very simple, but first I had to solder the pin-headers on the Seeeduino Mega board since the board is not sold with the pin-headers soldered, and then I connected the Seeeduino Mega board to the 9DOF Razor IMU board according to the diagram in Figure 1. Below is shown the sketch that allows you to read the data, as can be seen is short and simple.
/*

Read 9DOF Razor IMU data via Seeeduino Mega board (Arduino Mega clone).

1. Connect the jumper wires between the two boards
   according to the following table:

9DOF Razor IMU | Seeeduino Mega
---------------|--------------------
TX0............|RX1..(pin 18).......
RX1............|TX1..(pin 19).......
3.3V...........|3V3.................
GND............|GND.................
---------------|--------------------

2. Connect the USB Cable between the PC and the Seeeduino Mega board.
3. Select the "Board" item from the "Tools" top menu and check the radio
   button Arduino Mega (ATmega1280). 
4. Upload this Sketch to the Seeeduino Mega board
5. Open Serial Monitor and set the Baud rate to 57600.
6. Send the character '0' to view the 9DOF Razor IMU Menu.

9DOF IMU Test Firmware v15
==========================
[1]Accelerometer: ADXL345
[2]Magnetometer: HMC5843
[3]Gyroscope: LPR530 and LY530
[4]Raw
[5]Self Test

 */

void setup() {
  Serial.begin(57600);
  Serial1.begin(38400);  // Baud rate fixed....
  Serial1.print(4);      // Begin with Raw data
}

void loop() {
  if(Serial.available() > 0) {
    int incomingByte = Serial.read();
    /*
       DEC - BYTE
         0 - 48
         1 - 49
         2 - 50
         3 - 51
         4 - 52
         5 - 53
    */
    if(incomingByte >= 48 && incomingByte <= 53)
        Serial1.print(incomingByte, BYTE);
  }
  
  if(Serial1.available() > 0)
    Serial.print(Serial1.read(), BYTE);
}
After making the upload of the sketch, for the Seeeduino Mega Board, I opened the serial monitor and selected the baud rate to 57600 and can immediately observe the raw data to arrive (Figure 2).
Figure 2
To view the menu with more options, send the character "0". More options available can be seen in the sketch above. If you choose the Self Test (#5 in the Menu) and you always get a "MAG: BAD" message don't worry, probably your 9DOF Razor IMU board has no problem. Try upload the sketch, but where the first menu item to send is #5 (Self Test) instead of #4 (Raw) and you will see that the result will be different.

Monday, September 20, 2010

Read data from the 9 DOF Razor IMU via Arduino board.

After several problems with the original 9DOF Razor IMU board, I have finally got a board with no functional problems or bugs. The challenge we had to work around then was how to read the data from the board? So I decided do some research and found in this blog that there was a simple way to read data using the Arduino Duemilanove connected to the 9DOF Razor IMU board without requiring any additional cable as shown in Figure 1.
Figure 1
The sketch to read the data from the 9DOF Razor IMU via Arduino Duemilanove is very short and simple as shown below.
/*

Read data from the 9DOF Razor IMU board via arduino duemilanove board.

1. Upload this Sketch to the Arduino board
2. Disconnect the USB cable from the PC. 
3. Connect the jumper wires between the two boards
   according to the following table:

9DOF Razor IMU | Arduino Duemilanove
---------------|--------------------
TX0............|TX1.................
RX1............|RX0.................
3.3V...........|3V3.................
GND............|GND.................
---------------|--------------------

4. Connect again the USB Cable to the PC.
5. Open Serial Monitor.
6. Send the character '1'.
7. Send the character '0' to view the 9DOF Razor IMU Menu.

*/

void setup() {
  Serial.begin(38400);
}

void loop() {
  if(Serial.available()) {
    Serial.print(Serial.read(), BYTE);
  }
}
After doing the upload of the sketch, and open the Serial Monitor, send a character between '1' and '5' followed by a '0' then a menu is shown (Figure 2).

Figure 2
In the menu there are have five options: [1] Accelerometer (ADXL345), [2] Magnetometer (HMC5843), [3] Gyroscope (LPR530 and LY530), [4] Raw and [5] Self Test. For example, if you choose the option "1" and if you move the 9DOF Razor IMU board in any direction you will see on the Serial monitor the variation of the values for the aceleration
The following video shows the 9DOF Razor IMU board connected to the Arduino board working hard (Sorry for the bad video quality!). Notice menu of the 9DOF Razor IMU board on the monitor of the laptop.
But unfortunately this sketch does not fit what I want. With the Arduino Duemilanove only can be used a single Serial connection at a time. However, that problem can be solved by using software libraries. One of the libraries is the SoftwareSerial library which allows the serial communication on any of the Duemilanove's digital pins. But, because it's not supported by hardware, the library has a few limitations. The other library is the NewSoftSerial library that emulates an additional serial port, allowing you to communicate with another Serial device. However, there is another Arduino board where you can use more than one connection, which is the Arduino Mega. With the Arduino Mega is possible connect more three Serial devices. The last solution is more robust but, requires a further investment in a new board. So I'll have to take a look in the Arduino board clones.

Friday, April 30, 2010

Control all four motors from the arduino board with ESC's.

After some research I was able to control all four brushless motors from the arduino board with four speed controllers, one for each motor. The sketch can be seen in detail below.

Figure 1
The figure 1 shows the arduino development environment. In the left window (Serial Monitor) you can see the result of the instructions sent to the arduino board via serial port (USB-serial device). When the quadcopter is switch on must be sent the character "s" to initialize the speed controllers. After the controllers initialized, do not re-send the character "s" in any circumstance, if you send the motors immediately accelerated to full speed in less than 1 second. If you have placed the propellers in the motors of the quadcopter, then you'll see him being sent to the deep sky if you're a lucky guy. Here is the warning to anyone wishing to use this sketch. To increase the speed the character "+" is sent to the serial port and the character "-" to decrement the speed. To stop the motors the character "0" is sent.
Figure 2
The figure 2 shows how the speed controllers are attached to the side panels.
Figure 3
The figure 3 shows the cable connections of the speed controllers on board (Sorry for the bad image quality). When I have time I do a diagram of all connections.

#include <Servo.h>

#define MAXANGLE 160

typedef struct {
  int pinpwm;
  int range[2];
} ESCRecord;

ESCRecord escconf[4];
Servo escservos[4];
int angle = 0;

void config() {
  escconf[0] = (ESCRecord) {3, {836, 2400}};
  escconf[1] = (ESCRecord) {9, {836, 2400}};
  escconf[2] = (ESCRecord) {10, {836, 2400}};
  escconf[3] = (ESCRecord) {11, {836, 2400}};
}

void arm() {
  for(int esc = 0; esc < 4; esc++) {
    escservos[esc].attach(escconf[esc].pinpwm, \
                          escconf[esc].range[0], \
                          escconf[esc].range[1]);
    escservos[esc].write(0);
    delay(15);
  }
}

void cycle() {
  Serial.print("Cycle ESC Number ");
  for(int esc = 0; esc < 4; esc++) {
    Serial.print(esc);
    for(int angle = 0; angle <= MAXANGLE; angle++) {
      escservos[esc].write(angle);
      delay(15);
    }
    for(int angle = MAXANGLE; angle >= 0; angle--) {
      escservos[esc].write(angle);
      delay(15);
    }
  }
  Serial.println("");
}

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

  Serial.println("Wait for your input! [s] to init...");
  while(Serial.available() <= 0)
    delay(1000);
  int incomingByte = Serial.read();

  Serial.println("Start the system...");

  config(); 
  arm();
  delay(5000);

  if(incomingByte == 115) {
    Serial.println("Traverses all angles upward and downward.");  
    cycle();
    delay(1000);
  }
  Serial.println("Start loop...");
}

void setspeed(int angles[4]) {
  for(int esc = 0; esc < 4; esc++) {
    escservos[esc].write(angles[esc]);
    delay(120);
  }
}

void loop() { 
  if(Serial.available() > 0) {
    int incomingByte = Serial.read();
    if(incomingByte == 43)      // sends the character '+'
      angle++;                  // increases the speed
    else if(incomingByte == 45) // sends the character '-'
      angle--;                  // decreases the speed
    else if(incomingByte == 48) // sends the character '0'
      angle = 0;                // set the speed to zero
    
    if(angle < 0)
      angle = 0;
    if(angle > MAXANGLE)
      angle = MAXANGLE;
      
    Serial.print("Set the angle to: ");
    Serial.println(angle);
  }
    
  int angles[4] = {angle, angle, angle, angle};
  setspeed(angles);
}

Tuesday, April 13, 2010

Control a motor from the arduino board with a speed controller.

I connected the speed controller (ESC) to the arduino board and I connected the black cable of the receiver connection to the GND pin of the arduino and the white cable to the Digital PWM pin number 3.

I upload a sketch that I found on this post from the Arduino Forum to the board to test the motor, but nothing happening.
After some research I discovered that is necessary adjust the minim pulse width value. From the operating instructions that came with the speed controller I find that the stop position must be within the range 800 us to 1700 us and the full-throttle position must be at least 350 us than the stop position.
I make another sketch to find the the minimum pulse width value that start the motor and closer to the 0 angle. After several attempts I found that the nearest value is 836 us.
Finally, I made the sketch that is shown below, which starts the  ESC and keeps the motor running in a loop for 30 seconds and then stop for 10 seconds.

#include <Servo.h>

Servo escservo;

long lasttime = millis();

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

  // If you connected now the battery to the ESC, send
  // the 's' character. If not send another character.
  Serial.println("Wait for your input! [s] to init...");
  while(Serial.available() <= 0) delay(1000);
  Serial.println("Start the system...");
  int incomingByte = Serial.read();
  
  // Change the min pulse width value until match the
  // lowest value needed to start the motor.
  // From the ESC operation instructions the stop position
  // must be within the range 800 us to 1700 us.
  // The value 836 us is the lowest value.
  escservo.attach(3, 836, 2400);
  
  // arm the ESC
  escservo.write(0);
  delay(5000);
  
  // If you sent the character 's'
  if(incomingByte == 115) {
    Serial.println("Traverses all angles upward and downward.");
    cycle();
    delay(1000);
  }
}

void cycle() {
  int angle;
  // Danger: Try first with a value lower than 179, eg 160
  // Gradually increase to 180.
  for(angle = 0; angle <= 160; angle++) {
    escservo.write(angle);
    delay(15);
  }
  // Decrease the angle from 180 to 0.
  for(angle = 160; angle >= 0; angle--) {
    escservo.write(angle);
    delay(15);
  }
}

void loop() {
  long duration = millis() - lasttime;

  // If the duration is great than 30 seconds,
  // stop the engine for 10 seconds.
  if(duration >= 30000) {
    escservo.write(0);
    delay(10000);
    lasttime = millis();
  }
  // Put the motor to rotate in the angle 5
  escservo.write(5);
  delay(500);
}