Tuesday, July 11, 2017

How to install Jupyter Notebook in Zybo board with Linux. IPhyton 3

Jupyter is a nice web app, open source, easy and confortable to use instead of the Python shell. Once it is installed, you can test your small programs on a web browser (Mozilla, Chrome, etc).

In this tutorial I am going to show how to install Jupyter in the ZYBO board using a version of Linux-Debian. The previous steps to run the Linux on Zybo can be found on the other Linux-Zybo tutorials.
Also the library Matplotlib is going to be installed. This library helps with the plot of graphs, making it easy and interactive.

1- First, you have to connect to the Zybo board, as shown before via Ethernet. Now you have to share internet with the board. Normally on your Linux-computer, you should receive internet connection via Wifi. Now you have to share this via Ethernet port.
Open a terminal window and the write the following command to see the available connections on the system:

sudo ifconfig

Now all the connections are shown, at least the wlan and the ethernet connection with the Zybo board.
In my case, the name of the ethernet connection is enxa0cec808ceb6

Now to activate the net, we try with the commands to switch off/on and it should work.

sudo ifdown enxa0cec808ceb6
sudo ifup enxa0cec808ceb6

Now to check if the internet connection is arriving to the Ahora deberemos tener internet y Ethernet a la vez.
Using the ping command on the terminal:

ping www.elmundoporrecorrer.com #Check the internet connection to a website
ping 192.168.1.120  #check the Zybo connection

2- To install Python 3 and the libraries Numpy and Matplotlib from the terminal, you will need the following commandos:

apt-get -y install python3-dev python-dev
apt-get -y install python3-numpy swig python3-dev python3-wheel # seems to work
apt-get install python3-matplotlib python3-tk

This will install the packages. (note in my case it only actualized it because I had already installed, when I run the commands)
After instalation
Once installed, you can run the Jupyter notebook by the following command:

jupyter notebook

Open the Safari/Mozilla or equivalent and now you can introduce the address of the notebook. If you dont change anything, you should get the default address:

http://localhost:8888

The Dashboard of Jupyter will open showing the root of the Zybo SD card.
Dashboard the Jupyter notebook

To start writing the first code, we need to create a new Python 3 file by clicking on "new" (or 2.7 if you have this version of Python installed):
Create a new Python 3 file

If you open the new python 3 file, you will open a new tab with the following window:

Programming window
Here you can write the typical Hello world:

print ("hello world!")

Remember that to execute the code, you should press "Shift + Enter".


Note: In the last versions of Jupyter, by default, the authentication is activated. In the case, the ask you for a password, you should write on the terminal the command:

jypiter notebook list

This will return the Jupyter servers opening (normally it should be one). It will give you a url or a token, which you can open the Jupyter in the web browser. In my case it was like this:

Jupyter url token






Monday, July 10, 2017

tutorial ZYBO-Linux(III): Program ZYBO with linux. Small program to use the leds

This is the third part of Linux tutorial for Linux using the ZYBO board from Digilent.
In this part I am going to describe the steps to start up Linux from the previously c burnt SD card. The communication with the board are hold via Ethernet. At the end some easy programs will be shown to handle with the Zybo Leds.


Monday, July 3, 2017

ZYBO-Linux(II): Install Ubuntu or Linux in a Windows machine without a virtual box

This is the second part of the tutorial ZYBO-Linux to use Debian from a SD card. This part explains how to make a partition in your hard-drive to install Ubuntu on a Windows machine, or another version of Linux you like.
The other part of the tutorial are:
In this tutorial we are going to install Ubuntu via a USB in a Windows computer. To create the LInux-Ubuntu image, we will need a USB memory stick with at least 4GB.

Saturday, July 1, 2017

Tutorial ZYBO Linux (I): How to load Linux-Debian in ZYBO (Zynq) with a SD card

This is the first part of the tutorial for Linux and the board Zybo from Digilent. Here a image of Linux-Debian version is going to be created on a SD card. This SD is going to startup Linux in our ZYBO board.

This tutorial is divided in some parts:

  • ZYBO-Linux(I): Start and how to write a linux image into a SD card
  • ZYBO-Linux(II): Install and start up Linux from ZYBO

1- The first step is to download the Linux-Debian pre-compile image on the following link. Debian-Linux  and unzp it. It should size arround 3.9 GB. This image of Debian have already preloaded the configurarion to connect via Ethernet through the terminal. The default IP is 192.168.1.120

Thursday, December 29, 2011

How to read RC radio signals with Arduino using PPM signal. Tutorials

Differences between reading servo signals or PPM signals:

           By Jordi Muñoz: performance and simplicity in code are the reasons for intercept the PPM signals instead servo signals.
           With PPM (Pulse Position Modulation) you can collect all the radio channel in one line. In that way you can read all the channels with only one Arduino's pin. (less wires = less problems).
          The main idea is read the radio signals with a auxiliar Arduino and send the readed data to the principal Arduino board by SPI or i2C.
          Besides, if we disassemble the receiver housing and all input pins, we lose almost 70% weight and also save space.
           
           PPM and PWM are two different protocols for radio information. PPM has the advantage that you can get all the channels information through one port only. Some call it "PPM sum" since it’s the sum of all channels. That helps a lot when you have limited number of connectors to your flightcontroller. So I will use PPM into my flight controller, and then the flight controller will use PWM outputs to the ESCs and to the servos for the camera mount.
By using the PPM input, I can now use 10 PWM outputs from my Open Pilot Copter Control instead of 6 PWM outputs. That is for obvious reasons essential for me, because my camera mount needs two servo outputs plus the 6 ESC outputs.


           Radio transmitters often have two operating modes:   PPM (Pulse Position Modulation) and PCM (Pulse Code Modulation). We must put it in PPM and ACRO mode, without TRIM, without DUAL-RATE and neither EXPONENTIAL. In this way the lectures will not be distorted by the transmitter software.




           Turnigy 9X 8C V2 can not get PPM signal on anywhere on the PCB. This receiver works with two microprocessor, one receiver and the other one  decoder, and they talks by SPI. Here you can check a big list with a lot of common receiver and how to get the PPM signal. LIST
             Another hardware solution is add one extra chip.

           If you don't know where are your PPM signal, you can upload this Jordi's code to try to find the right pin in our receiver board. With one wire connected to pin 3, start touching every pins and spots of your receiver untill you see random values on the Arduino Serial Monitor between 300 to 9000. That means you found it. Don't forget connect ground to ground.


void setup()
{
Serial.begin(57600);
pinMode(3, INPUT);
}
void loop()
{
Serial.println(pulseIn(3, LOW));
}


           The programs below were written by Jordi Muñoz and uploaded to Arduino's Forum 1st de January 2008.

Basic PPM reader with Arduino
#define channumber 6 //Cuantos canales tiene tu radio?/How many channels have your radio?
int channel[channumber]; //Valores de canales leidos/ readed Channel values
int PPMin = 4;

void setup()
{
  Serial.begin(9600); //Iniciamos com serial/
  pinMode(PPMin, INPUT); //Patita 4 como entrada / Pin 4 as input
}

void loop()
{
  //Espera hasta que la senal de sincronizacion llegue, debe ser > 4 milisegundos
  //waits ultil synchronize arrives > 4 miliseconds
  if(pulseIn(PPMin , HIGH) > 4000); //Si el pulso del pin 4 es > que 4 msegundos continua /If pulse > 4 miliseconds, continues
  {
    for(int i = 1; i <= channumber; i++) //lee los pulsos de los demas canales / Read the pulses of the remainig channels
    {
 channel[i-1]=pulseIn(PPMin, HIGH);
    }
    for(int i = 1; i <= channumber; i++) //Imprime los valores de todos los canales / Prints all the values readed
    {
 Serial.print("CH"); //Canal/Channel
 Serial.print(i); // Numero del canal / Channel number
 Serial.print(": "); // que te importa
 Serial.println(channel[i-1]); // Imprime el valor/ Print the value
    }
    delay(200);//Le da tiempo para imprimir los valores en el puerto/ Give time to print values.
  }
}


PPM reader with glitch filter:

#define channumber 6 //Cuantos canales tiene tu radio???????/How many channels have your radio???
#define filter 10 // Filtro anti salto/ Glitch Filter
int channel[channumber]; //Valores de canales leidos/ readed Channel values
int lastReadChannel[channumber]; //Ultima lectura obtenida/ Last  values readed
int conta=0; //Contador/couter


void setup()
{
  Serial.begin(9600); //Iniciamos com serial/ Serial Begin
  pinMode(4, INPUT); //Patita 4 como entrada / Pin 4 as input
  pinMode(13, OUTPUT); // Led pin 13
}

void loop()
{

  if(pulseIn(4, HIGH) > 3000) //Si el pulso del pin 4 es > 3000 usegundos continua /If pulse > 3000 useconds, continues
  {
    for(int i = 0; i <= channumber-1; i++) //lee los pulsos de los canales / Read the pulses of the channels
    {
 channel[i]=pulseIn(4, HIGH);
    }
    for(int i = 0; i <= channumber-1; i++) //Promedia los pulsos/Average the pulses
    {
 if((channel[i] > 2000) || (channel[i] <100))//Si se pasa del rango envia ultimo pulso/ If channel > max range, chage the value to the last pulse
 {
  channel[i]= lastReadChannel[i];
 }
 else
 {
 channel[i]=(lastReadChannel[i]+channel[i])/2; //Promedio el pulso pasado con el nuevo pulso/Average the last pulse eith the current pulse
 conta++; //Incrementa el contador/ increment counter
 }
    }

    }
    if(conta > filter)//Si el contador es mayor al filtro imprime valores/ If counter is > than filter, then prints values
    {
 for(int i = 0; i <= channumber-1; i++) //Ciclo para imprimir valores/Cycle to print values
 {
   Serial.print("CH"); //Canal/Channel
   Serial.print(i+1); // Numero del canal / Channel number
   Serial.print(": "); // que te importa
   Serial.println(channel[i]);
   lastReadChannel[i]=channel[i];
 }
 if(channel[4] > 1000) //si el canal 5 tiene un rango mayor a 500 enciende el LED/ If channel 5 is > than 500 turn on the led
 {
   digitalWrite(13, HIGH);
 }
 else
 {
   digitalWrite(13, LOW);//Si no lo apaga/If not turn it off
 }
 delay(400); //Delay
 conta=0;//Reinicia el contador/ Restart couter.
    }
  } 

How to drive a Brushless motor with Arduino. Tutorial

            A continuación explico con un pequeño tutorial, como controlar un motor Brushless con un variador de velocidad (ESC) y una placa Arduino o en mi caso, ArduPilotMega.



Necesitamos un batería LiPo, un ESC, un motor Brushless y un Arduino.

El esquema de conexión utilizado es el siguiente:


              Para controlar un motor de este tipo hay que mandar al ESC señales como si quisiéramos controlar un servo normal. Estas señales son cuadradas con un tiempo en alto que varían entre 1 y 2 milisegundos, que correspondería a un águlo de entre 0 y 180 grados. Podemos probar primero con un servo: Si un servo no se mueve, el motor brushless nunca lo hará.



          Para la conexión con el microcontrolador usaremos un pin de salida, en nuestro caso usaremos el pin 8. Si usamos ArduPilot Mega, este pin número 8 equivale al canal número 5 (CH_5). Conectamos el cable blanco al pin, el cable rojo, alimentación, queda libre y las tierras las unimos. (cable negro a GND del arduino)

          Para conectar el ESC, le conectamos los cables de alimentación a la batería LiPo mediante un conector tipo banana de 4mm.(también podemos utilizar un fuente de alimentación externa, pero debemos de asegurarnos que tenga la potencia que el motor requiera.. que por lo general suele ser alta) Y para las conexiones del motor, en mi caso he soldado unas pinzas como se muestra en la figura. Importante amarrar bien el motor a una madera, ya que al arrancar puede ser peligroso y más si es un motor outrunner.


      Para el código,importante armar el motor antes de arrancarlo, ya que si no lo hacemos no arrancará nunca. Para inicializar un motor basta con enviar señales de ángulo 0 hasta que el motor emita pitidos. Consiste en recibir un pulso de 1 milisegundo cada 20 milisegundos por un tiempo aproximado de 4 o 5 segundos.
        El proceso es:


  • Alimentar el ESC y escuchar la música de confirmación.
  • Armar: 

          myservo.write(0);   // Aramado

  • Esperar pitidos  "Ready".
  • Mover el motor:

           myservo.write(pulsoMotor); //pulsoMotor lo variamos desde alrededor de 70 a 180 (máximo)


          Notas:

  • Cada motor arranca con una señal de ángulo diferente, en mi caso está en 65º.
  • Si despues de armarlo envío señal de 70 directamente no arranca, hay que subir progresivamente. Basta con mandar un 30º y ya pasar a 70º.
  • Si queremos cambiar el sentido de giro al motor, intercambiando 2 de los 3 cables de motor es suficiente.



Descargar aquí el archivo con el CÓDIGO.


Para cualquier duda, sugerencia o opinión no dude en comentar. 

Tuesday, November 22, 2011

Cuadricopter, Hexacopter, small budget. Aerial photography.

Intro:

          UAV (Unmanned Aerial Vehicle) is a vehicle which is unmanned, it could be completely autonomous, or remote controled, RPA (remote Piloted Aircraft) or mix systems. Traditionally UAV has been employed for military goals, but actually many civil aplications are being developing. Specially I am interested in  aerial phography.

Design and development considerations: (UAV) (wikipedia)
             The United States and Israel were initial pioneers in this technology, and U.S. manufacturers have a market share of over 60% in 2006, with U.S. market share due to increase by 5–10% through 2016. Israeli and European manufacturers form a second tier due to lower indigenous investments, and the governments of those nations have initiatives to acquire U.S. systems due to higher levels of capability. European market share represented just 4% of global revenue in 2006.

Multicoters:
            A multicopter mainly is a helicopter with several axis and independent motors. The are Tripcopter, quadcopter, hexacopter octocopter... They have good stability and large payload capacity. The propellers spin in diferent directions. This avoid that the aircraft rotate itself over a vertical axis. The control is implemented by an electronic board which cahnges the speed of each motor. In this way you can get all the movements.




Civil purpose:

  • Aerial security fo large surfaces.
  • Transport of goods.
  • Science research: remote sensing.
  • Search and rescue in natural catastrophe. 
  • Other comercial golas like aerial video and photography.  Jeff Scholl is an american guy who work up in this theme. In his facebook profile he has lots of nice vids and photos.Usos no militares: 
www.gravityshots.com
Some of Jeff Scholl's multicopter are:




    Some of him videos:




            A Nick and Roll compensation needed if we don't want a dizzy film:




              With two servos and some damperners we can reduce the vibrations. This vibrations come from the motors and props. rubber dampeners, dampeners2.



              From Pennsylcania university, GRASP Lab is developing aggressive maneuvers for autonomous cuadricopter. Here you can see some of their works.


    :



               In the following video you can see a group of cuadricopters working together to build a small structure. You can see the potential of these small aircrafts with this example.



    Approximate budget:
                 Knowing how cost build a cuadricopter or hexacopter is so important. Here you can find a list with the basic components:

    • Motors
    • Propellers
    • Electronic Speed Controller (ESC)
    • Electronic control board.
    • Radio receiver and emisor
    • Frame

    Motores: 

    Electronic speed controller (ESC):
    Emisor-receiver:
    Receiver
    Propellers

    Part
    Quantity
    Unit price
     Total price
    Motors
    4
    20$
    80$
    ESC
    4
    12$
    48$
    Propellers
    4+4 replacement
    3$
    24$
    Reciever & emisor
    1
    53$
    53$
    Battery
    2
    25$
    50$
    TOTAL

    TOTAL
    250$


    Hexacopter: Download here the excel file.

    Elemento
    Cantidad
    Precio unitario
    Precio Total
    Motores
    6 +1
    20$
    140$
    ESC
    6
    12$
    72$
    Hélices
    6+6 Repuesto
    3$
    36$
    Reciver y emisor
    1
    53$
    53$
    Baterias
    2
    25$
    50$
    Electrónica
    1
    250$
    250$
    chasis
    1
    ¿? $
    ¿? $
    TOTAL
    TOTAL
    601$


                   The frame and the electronic board haven't been added. The electronics board that I have choosen is ArduPilot, based on a Open Source project DIYdronesit is a board similar  Arduino board. This electronics board can manage any  UAV (Unmanned Aerial Vehicle) aircraft like multicopter, airplane or glider. Almost all necessary sensors are already built-in.

     

           
           
                This board is very modular and it has free pins, so you can add other king of sensors or elements like camera stabilizer... Also you can connect a radio receiver, telemetry and an USB connection for programing. It has too one small relay to activate some load.

             Es muy modulable y posee bastantes pines libres, de forma que puedes ir añadiéndole sensores u otros elementos como estabilizadores para cámaras... Tiene conexión para el receptor de radio, es posible añadir telemetría, conexión USB para programar el micro 1280 y dispone de un relé para accionar periféricos.

    The features are:
    • 3-axis gyros
    • 3-axis accelerometers
    • Barometric pressure sensor for altitude
    • 10Hz GPS module
    • Voltage sensors for battery status
    • 16Mb of onboard datalogging memory. Missions are automatically datalogged and can be exported to KML
    • Built-in hardware failsafe processor, can return-to-launch on radio loss.
    • Include relay can trigger any device, can be controlled by mission scripts.
    • (Optional) 3-axis magnetometer
    • (Optional) Airspeed sensor
    • (Optional) Current sensor





           The kit costs around $250, and the soldered board for $299. Also is necessary a 3 axis  magnetometer if you want point to a specific direction.


            Many designs are valid  for the frame (images). Also many kind of materials can be used  and some constuction process. The best wat is a CNC machine.
          


    Cameras:
                The main goal is take pictures or videos, but we use cameras also to send live video for First Person View (FPV) flight. For our multicopter, at first, it won't have cameras.         


                With the FPV camera you can pilot without direct vision. Also is useful to take better videos and photos. This cameras are very light, only about 16 grams.  OSCS420.

              To take pictures, is important use a good photo/video camera. These cameras have remote control of the photo shooter, focus ... and many of them have video output that you can send to your  groundstation. Also is important a good shock absorber system with dampers and a smooth camera stabilizer. 






                 A good choice is  GoPro. Special designed for extreme sports like motocross, montainbike, surf, snowboarding, skateboarding... It has only basic features to a first person view video with smart video quality. it weight 94 grams and have a endurable waterproof housing. It cost arround 200$.
    The GoPro 2 version is now avaliable.   Here you can fin a GoPro lens protection by fpvmanuals.





    Commercial Aerial photography: 

                       Taking photos and videos from the sky is not nothing new, but lately has raised exponentially.
    Advances in radio contolled models have made it possible to conduct low-altitude aerial photography. Also  full-size manned aricraft are prohibited from low flights above populated locations. RC (Radio Control)  plane and multicopters are more accessible for DIY fans.
    Lots of applications for aerial photography, some of them are:      


    • Cartography: A process taht is used in photogrammetric surveys, the basis for topographic maps.
    • Environmental studies: Charting the environmental changes that have occurred in a given area.
    • Comercial advertising: Obtaining photographs that can be used to create commercial ads.
    • Construction progress shots.
    • Film production.
    • Panoramic views and 360 degree virtual tours.
               Some examples of aerial phothography can be seen here.

               There are lots of methods like planes, helicopter, ballons, kites, rokects, zeppelin, parachutes... The most commercially ussed maeby are Zeppelin. This kind of aircraft are very safety and stable. The principal issues of tradicional helicopters and multicopters are stability from vibrations and fast moves and safety. One accident could produce lots of money loss and humans damages.
            
    Zeppelin

    hexacopter
           As advantage, the multicopter can create more movement for videos, views like a bird. Here is an example:
       


               This kind of result is not posiblle to obtain with a Zeppelin. Also is needed a good stabilizator to get this videos.

       
    Project goals:

              Design and build a multicopter with payload capacity to carry a photo-video cammera. The design part includes:    
    • Design the frame based on carbon fiber or aluminum parts mades by a CNC machine.
    • Design a 2 axis stabilizator (Nick&Roll) wich can hold any kind of standar cammera.
    • Remote control of the cammera and video transmiter from ground.
    • Estimate wich motors and ESC can carry the photograph kit.
    • Control and programming for a good and stable flight.
    • Autonomous control and safety mode.


                 The final goal could be able to design and build a commercial photography multicopter for profesional use.        

    Multicopter choice:

             Depending the use of the multicopter we are going to choose more or less number of motors. For this project, the objetive is get quiality photography/video works. The main features will be:

         
    Simplicidad y bajo peso en la estructur
    • Simply and low weight.
    • Payload capacity for a good camera.
    • Transportable and folding.
    • 10 minutes of autonomy.       
             

               All posible configurations are:     (see also mikrokopter)

    Tricópter: Barato y fácil de construir, menos estable, partes móviles en la estructura (cola móvil por un servo), bajo empuje y menos tiempo de vuelo (porque los motores tienen que girar más rápido para mantenerlo en el aire).

    Cuadricópter: Más simple mecánicamente que el tricópter. Posee 1/3 más de empuje pesando casi lo mismo y suelen ser más estables ya que no  tienen partes móviles en la cola movidas por un servo. Tienen más tiempo en vuelo debido a que pueden llevar baterías más grandes y a que los motores trabajan a menos revoluciones. Todavía no contamos con redundancia: Si un motor falla... cae.

    Hexacópter: Todo lo bueno que tienen los cuadricópter pero con más potencia y más capacidad de carga. Posee algo de redundancia: Si pierde un motor todavía puede aterrizar, (perdemos el control del ángulo 'yaw'). Como desventaja son más caros y más grandes.

    Octocopter: Todo lo bueno que tienen los hexacópter más redundancia: Si pierde un motor todavía vuela bien. Se usa para asegurar cuando se ponen equipos fotográficos de alto precio. Son más caros que los hexacopter. Requieren mucha energía para volar.


            Descartamos la opción de cuadricópter (quadricopter, quad... ) pora conseguir más capacidad de carga. Sobre la opción de elegir un hexacópter (hexacopter, hexa...) o octocóptero (octocopter, octo... ):

        Ventajas de un mayor número de Motores:
    • Mayor capacidad de carga
    • No es necesario unos motores tan potentes o unas hélices tan grandes para la misma capacidad de carga.
    • Redundancia. Muy importante, en caso de rotura de una hélice, choque...
            6 motores es poco fiable, aunque, probablemente,  sobreviviría a una parada de un motor, hay que irse a 8 motores para tener ambas cualidades: Capacidad de carga y Redundancia.

          A mayor número de motores necesitaremos unas hélices más pequeñas, que dan una respuesta más rápida, resultando más estable. Por eso para conseguir estabilidad los motores/hélices han de poder cambiar de velocidad lo más rápidamente posible.


          Quizá con 6 motores sea más eficiente (Usa menos Watios pare levantar un un Kg., 5 o 10%) que 8, entre capacidad de carga y peso. Elegiremos 8 sólo si queremos más carga o por la redundancia ya que es mucho más caro (1/3 más caro, motores, ESCs y hélices).

           Las configuraciones coaxiales tienen como principal ventaja la redundancia. Podemos usar Y6 o X8, aunque son menos eficientes debido a que el aire que llega a la segunda hélice está turbulento.

           La configuración en X o en +.

           Conclusión: si el objetivo es la fotografía tienes que irte a Hexa/octo, si el uso va a ser el pilotar una aeronave o las acrobacias  lo más indicado es un cuadricóptero ligero.