viernes, 30 de agosto de 2013

Scan your Wifi with Fing

I'll suggest an app that I discovered while investigating with the Arduino Ethernet Shield, it's useful to scan the wifi your phone is connected to, it will show you all devices connected to the same router, as well as its local IP and MAC, so you'll be able to redirect ports, and other stuff

Completely free



Link to: Apple Store

Link to: Google Play





Images:

iPhone Version                                                          Android Version

lunes, 12 de agosto de 2013

Arduino power sourcing Pololu Servo Controller

Pololu Micro Maestro needs two power source, first the battery to move the servos, the second provides energy to the circuit to run the script.

Note: the Pololu circuit includes a jumper to mix the two power source into one, I used separately.

Source for circuit

Arduino: I discovered that the red wire for Vin (positive) is not needed, the signal pin (Tx) provides of energy and signal, so only GND (gnd pin) and Signal/Vin (Tx pin) are connected to the Pololu circuit.




Mid-wire: homemade mid wire to match the male and female pins from arduino and pololu


Servo Controller: this is the pololu pins going to the mid-wire





Source for servos: Homemade battery power the servos, first goes to a heat dissipator, and then to the Pololu

Note: Blue thing is the mentioned jumper included

Full project album at: http://imgur.com/a/n9pJN
And that's all for today, greetings!

jueves, 8 de agosto de 2013

Pololu Servo Controller + Arduino (3/3)

In order to call a subroutine you have to create it manually with the Pololu Software and then Save all the secuences to script so the program haves something to call. 

Command used: "Restart Script at Subroutine" with Pololu protocol http://www.pololu.com/docs/0J40/5.f
Pololu protocol: 0xAA, device number, 0x27, subroutine number

Each underlined is a byte that you must send, so in this case you send 4 bytes (4 packages of 1 byte), let's see how it works

Arduino Code, Pololu protocol: "subroutine" is a method that do all the work

void sub(unsigned int subrutine)
{
   Serial.write(0xAA); //start byte, Mandatory [byte 1]
   Serial.write(0x0C); //device id or number (seen in part 1/3) [byte 2]
   Serial.write(0x27); //command number, Mandatory [byte3]

   if(subrutine == 0){
     Serial.write(0x00); //execute subrutine number received [byte 4]
   }
   if(subrutine == 2){
     Serial.write(0x02);  //execute subrutine number received[byte 4]
   }
   if(subrutine == 3){
     Serial.write(0x03); //execute subrutine number received[byte 4]
   }
   if(subrutine == 4){
     Serial.write(0x04); //execute subrutine number received[byte 4]
   }
}

void loop()
{
   subroutine(3);        // Calling subroutine number 3 (first is 0)
   delay(1000);         // Wait 1000 miliseconds (1 sec)
   subroutine(4);        // Calling subroutine number 4
   delay(1000);         // Wait 1000 miliseconds (1 sec)
}

Video Sample:


Imgur Album

Go to part 2/3                                                                                                               

,

Pololu Servo Controller + Arduino (2/3)

This is the key to make your micro maestro understand the arduino orders:

Command used: "Set Target" with Pololu protocol http://www.pololu.com/docs/0J40/5.e
Pololu protocol: 0xAA, device number, 0x04, channel number, target low bits, target high bits

Each underlined is a byte that you must send, so in this case you send 6 bytes (6 packages of 1 byte), let's see how it works

Arduino Code, Pololu protocol: "put" is a method that do all the work

void put(unsigned char servo, unsigned int target)
{
   //servo is the servo number ( 0-11 [12 Maestro servo version] )
   //target = wanted position

 // Mandatory paraphernalia, converts the decimal angle("target") you entered into a 2 bytes (first 7 and last 7 bits), just copy and  paste blue, it's used by the last two serial.write lines
  unsigned int temp; 
  unsigned char pos_hi,pos_low;
  temp=target&0x1f80;
  pos_hi=temp>>7;           // First 7 bits

  pos_low=target & 0x7f;   // Last 7 bits

  //Sending Pololu Protocol command
  Serial.write(0xAA); //start byte -> Mandatory
  Serial.write(0x0C); //device id or number (seen in part 1/3)
  Serial.write(0x04); //command number  -> Mandatory, it depens on command you use
  Serial.write(servo); //channel number -> number of the servo, depends wich pololu you have (6,12,18, ..)
  Serial.write(pos_hi);   //data1, Sending the firsts 7 bits
  Serial.write(pos_low);    //data2, Sending the lasts 7 bits
}

void loop()
{
   put(1, 1550);        // Move servo in position 1 to angle 1550
   delay(1000);         // Wait 1000 miliseconds (1 sec)
   put(1, 2000);        // Move servo in position 1 to angle 2000
   delay(1000);         // Wait 1000 miliseconds (1 sec)
}

Video Sample:

Imgur album

Go to part 1/3                                                                                                                       Go to part 3/3

,

Pololu Servo Controller + Arduino (1/3)

I'll make a basic tutorial about how to use the Maestro Servo Controller from Pololu:

- How to move a single servo (Tutorial 2/3)
- How to call a subrutine hosted in the script of the servo controller (multiple servos) (Tutorial 3/3)

The Pololu's Servo controller called "Maestro" is a plate which allows control of different servos, controlling its position as both acceleration and speed.
Depending on the plate there are several versions (6, 12, 18, ​​24) and all are compatible with the free software provided by the brand.


Parts needed:

- Arduino (I used Arduino UNO R3)
- Pololu Servo Controller (tested in the 12 servo version)
- At least 1 servo.
- A batery pack.
- Wires

As you can see here http://www.pololu.com/docs/0J40/5.e we are going to use "Set Target" command to move the servo, and "Restart Script at Subroutine" at http://www.pololu.com/docs/0J40/5.f.

We can use the compact protocol/pololu protocol and Mini SSC, it's the same but with a diferent command.

Image shows the serial setting tab of the maestro control panel, Mini SSC offset option it's a boolean value (1 indicates NO active, 0 = active), use what you prefer. 

Also just above the "Device Number" is the parameter that you must use in the serial command, you have to converse it to Hexadecimal ("12" in Decimal = "c" in hexa)



Don't forget to conect the TX pin of Arduino (pin 1) to the RX pin of the Maestro!!!!







Imgur album

                                                                                                    Go to part 2/3

Arduino: Serial.print VS Serial.Write

In many tutorials you can see this method to send a byte tipe variable:

  buff[0]=0x80; //start byte
  buff[1]=0x01; //device id
  buff[2]=0x04; //command number


  for(int i=0;i<3;i++)

  {
    Serial.print(buff[i],BYTE);

  }

If your are using the arduino IDE 1.0 or above that code will return error, because BYTE is no longer supported, instead, the solution is using "write"

Serial.print(buff[i],BYTE);   Is trying to send the array "buff" by serial in a byte mode.

The new model accepted by Arduino IDE is using Serial.write(buff[i])

Serial.write(buff[i]);  Already send in byte mode the variable "buff" so you don't have to specify BYTE anymore.


Reference: http://arduino.cc/es/Serial/Write    //    http://arduino.cc/es/Serial/Print

Arduino Variables, Signed VS Unsigned

What's the difference?

Signed/Unsigned are reserved words that specifies whether a variable can contain negative numbers, for this, uses the first bit (0 or 1) to indicate whether it is positive or negative, so it reduces the size of the variable at a half, see this:


Language      Type                       Size                              Range                 Meaning

C#                byte                         8-bit (1 byte)          0 to 255           Byte with sign
C#                sbyte                       8-bit (1 byte)          -128 to 127       Byte without sign

Arduino          Signed byte     8-bit (1 byte)         0 to 255            Byte with sign
Arduino          Unsigned byte   8-bit (1 byte)         -128 to 127       Byte without sign

Signed vars:  00000011 = 3       //     10000011 = -3

                       01111111 = 127  //      11111111 = -128

Unsigned vars: 00000011 = 3      //   10000011 = 131
                          01111111 = 127  //   11111111 = 255


Note: by default arduino uses signed variables, so it's the same using "byte my_var" than "signed byte my_var"

Tip:

When a variable exceed their maximum capacity, turns around his minimum capacity. In both directions.
Example: 

  unsigned int x;      // contains 0 to 65535
  x = 0;               // contains 0
  x = x -1;            // now contains 65535 (turning into max)
  x = x +1;            // contains 0 (returns to minimum)


Remember:

Signed: Means number can be negative (half capacity), top bit indicates the sign (1 = negative, 0 = pos.)

Unsigned: Means that number can only be positive (full capacity)

Reference:

http://arduino.cc/es/Reference/UnsignedInt
http://arduino.cc/es/Reference/Int

------------

miércoles, 7 de agosto de 2013

Background Fixed

Update: This post indicates how to make your web background static when mouse scrolling

Alguna vez os ha pasado que en vuestra página, al bajar el scroll termina el fondo y vuelve a repetirse?

Más o menos como esto:



Pues aquí está la solución:

la imagen del body se define en el css, y esto debéis poner:

body {
          background-image: url(direccion_de_tu_imagen.jpg);
          background-attachment: fixed;            /* para que sea estático */
          background-position: top right;         /* arriba a la derecha */
          background-repeat: no-repeat;        /* que no se repita el fondo */
}

Por otro lado, si lo queréis aplicar a otro elemento, como un pequeño login que siempre esté visible o un div, etc, ponedle estos atributos:

position: fixed;       /* Estático en la página*/

top:   10 px;              /* separación de la ventana del navegador por arriba.*/

left/right: 10px;     /*separación de la ventana del navegador por la derecha/izquierda.*/

Espero que os haya servido :P

Favicon Tutorial

Este es un tema que siempre me trae por el camino de la amargura, así que para ahorraros trabajo os pongo cómo lo he solucionado.

El caso es que hay varias formas, pero, por así decirlo algunos navegadores no dejan ver los favicons si dichas webs no están alojadas en un servidor, la alternativa a subirlas a Internet es montar un servidor virtual mediante apache (http://www.apachefriends.org/en/xampp-windows.html), en esa dirección se puede descargar, y es muy sencillo de utilizar, más adelante haré un pequeño tutorial de uso.

Una vez montada la página, sí que permite ver los iconos, yo he utilizado formato png para no complicarme.

En cuanto al código HTML, se coloca en el HEAD de la página:

<link href=”favicon.png” rel=”shortcut icon” type=”image/x-icon” />  <!– Esta línea si tu favicon es .png –>

 <link href=”favicon.ico” rel=”icon” type=”image/x-icon” />  <!– Esta línea si tu favicon es .ico –>

favicon

Slider Sencillo y rápido

Aquí os pongo cómo hacer un slider sencillo y rápido de imágenes, cada elemento li mostrará una imagen, y el javascript + css se encargarán de mostrar sólo uno cada cierto tiempo.



HTML  **Se pueden agregar links (p.ej. <li><a><img> en vez de <li><img>) u otras etiquetas siempre que se modifique el css correctamente.

<ul id="galeria">
    <li><img src="img/imagen-1.jpg" border="0" alt="otros" /></li>
    <li><img src="img/imagen-2.jpg" border="0" alt="paisaje" /></li>
    <li><img src="img/imagen-3.jpg" border="0" alt="vistas" /></li>
    ...
</ul>

JAVASCRIPT **Copiar este código en la etiqueta head del HTML

<script type="text/javascript">
    /** javascript slide-show **/
    var cons = 1;
    function slide_show()
    {
      var elemento = document.getElementById('galeria').getElementsByTagName('li');
      for(var n=cons; n <= elemento.length; n++)
      {
         elemento[n].className = 'selected';
         for(var i = 0; i<elemento.length; i++)
         {
           if(i!=cons){ elemento[i].className = 'noselected'; }
         }
         cons++;
         break;
      }
      if(cons >= elemento.length){ cons = 0; }
      return false;
    }
    window.onload = function(){ setInterval(slide_show, 5000); } /** Valor en milisegs. de tiempo de exposición de una imagen **/

</script>


CSS, EFECTO OPACIDAD (Cambio de imágenes mediante superposición de opacidad)

/** galeria **/
#galeria{display: block; margin: 0 0 0 15em; padding: 0; position: relative; width: 50%;height: 22.5em; list-style: none; border: 10px solid #1a1a1a; border-radius: 10px; box-shadow: 0 0 10px #000; overflow: hidden;}
#galeria li{position: absolute; top: 0; left: 0; width: 100%;border-radius: 10px;background-color:#1a1a1a;paddiing: .4em;}
#galeria li img{width: 100%;border-radius: 10px;background: #1a1a1a;}
#galeria .selected{z-index: 1; opacity: 1; -moz-transition: all 2s ease 0s;-ms-transition: all 2s ease 0s;-o-transition: all 2s ease 0s;-webkit-transition: all 2s ease 0s;transition: all 2s ease 0s;}
#galeria .noselected{z-index: 0; opacity: 0; -moz-transition: all 2s ease 0s;-ms-transition: all 2s ease 0s;-o-transition: all 2s ease 0s;-webkit-transition: all 2s ease 0s;transition: all 2s ease 0s;}

CSS, EFECTO PERSIANA (Tal y como suena, la imagen se retira de abajo a arriba)

/** galeria **/
#galeria{display: block; margin: 0 0 0 15em; padding: 0; position: relative; width: 50%;height: 22.5em; list-style: none; border: 10px solid #1a1a1a; border-radius: 10px; box-shadow: 0 0 10px #000; overflow: hidden;margin-top: 1em;}
#galeria li{position: absolute; top: 0; left: 0; width: 100%;overflow:hidden;}
#galeria li img{width: 100%;}
#galeria .selected{height: 22.5em; z-index: 1; -moz-transition: all 1s ease 0s;-webkit-transition: all 1s ease 0s;-o-transition: all 1s ease 0s;-ms-transition: all 1s ease 0s;transition: all 1s ease 0s;}
#galeria .noselected{height: 0; z-index: auto; -moz-transition: all 0s ease 1s;-webkit-transition: all 0s ease 1s;-o-transition: all 0s ease 1s;-ms-transition: all 0s ease 1s;transition: all 0s ease 1s;}

Este slider fué creado por Andrés Moreno.

Fuente: http://www.andresmorenostudio.com/blog/javascript/30-slideshow-css-javascript

Aplicar estilos CSS a un HTML

2 opciones:


1. En el código HTML:

Aplicar un estilo concreto a una etiqueta:

        <tag style=”opcion que queramos;”> </tag>

Por ejemplo:   <p style=”color:#F3F3F3;”>Este párrafo</p>

  ————————————————————————————————————-

Simular un trozo de .css dentro del html:

<STYLE type=”text/css”>

                   H1 {border-width: 1px; border: solid; text-align: center}

</STYLE>

Como vemos se parece mucho a lo que se pone en un archivo .css, se aplicará a todas las entidades “h1″ las propiedades de “border-width”, “border” y “text-align”.

*En este segundo caso, las etiquetas STYLE deben ir en la sección Head del HTML.

2. En el código CSS:

Requiere linkearlo desde el html

<link rel=”stylesheet” type=”text/css” href=”larutadelcss” />

En estos archivos que escribe la etiqueta a aplicar, y dentro de las llaves los atributos que quieras, cada fin de atributo está marcado por “;”

 H1 {

              border-width: 1px;

              border: solid;

              text-align: center;

         }

Como vemos hemos usado el mismo ejemplo anterior, que hará no mismo, pero sin ensuciar el HTML.

Plantilla HTML y CSS

Archivo HTML:
<html>
<head>
<!– Título de pestaña –>
<title>title</title>
<!– Hoja de estilos –>
<link rel=”stylesheet” type=”text/css” href=”styles.css”>
<!– Codificación de caracteres –>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″ />
</head>
<body>
<!– Contenedor –>
<div id=”wrapper”>
<!– Cabecera –>
<div id=”header”>
</div>
<!– Menu Adicional –>
<div id=”menu”>
</div>
<!– Contenido Principal –>
<div id=”content”>
</div>
<!– Pie de página –>
<div id=”footer”>
</div>
</div>
</body>
</html>
Archivo CSS:
body{
}
#wrapper {
}
#header {
}
#menu {
}
#content {
}
#footer {
}

martes, 6 de agosto de 2013

Hola Mundo en C#

Bienvenidos a vuestro primer programa, como es tradición en la programación, se empieza creando un pequeño programa en el cual el ordenador escribe Hola Mundo! en la pantalla, es una chorrada, pero será tu primer programa.

Bien, comenzamos con Nuevo < Proyecto < Aplicación de consola (le ponéis nombre y donde guardarlo).
os aparecerá lo siguiente:


Bien, llegando a este punto os comentare una cosa, es muy importante "comentar" tus códigos, sirve para otro que tome el control del programa sepa que significa cada cosa.
Para comentar:

// texto de comentario

/*
* texto de comentario
*/

Para que en la consola aparezca algo se debe escribir estos comandos:

Console.WriteLine("texto que quieres");
Console.Write("texto que quieres");

Cual es su diferencia? el writeline escribirá "texto que quieres" y hará un salto de linea (enter)
el write escribirá eso y que quedara ahí.

Ahora que sabes como escribir, pon tu frase y dale al play.

TABULACIÓN:

dentro de las comillas se pueden colocar varias cosas para tabular el texto:

\n : hace un salto de linea Console.Write("ola\n mundo"); = ola
                                                                                         mundo

\t: efecto tabulador, es decir Console.Write("ola\t mundo");  =  "ola          mundo"

NOTA 1: los programas se arrancan y se cierran, si solo le dices que escriba Hola Mundo, lo escribirá y se cerrará el programa, un truco es escribir BAJO el hola mundo lo siguiente:

Console.ReadLine();

Para que es esto? es un comando que le dice al ordenador que espere a recibir algo del teclado, es decir cuando pulséis una tecla, el programa continua o si no hay nada se cierra.

NOTA 2: no olvides poner el punto y coma al final de cada línea de ordenes, SALVO en las iteraciones que veremos en el futuro (osease que omitas esto, no olvides nunca el punto y coma)

Arrancando Visual Studio

Trabajaré en VS2008, aunque el código es el mismo y se puede copiar y pegar.
Os adjunto una imagen sobre lo que deberías ver al arrancar el visual y darle a proyecto nuevo.


Nota: En versiones más modernas los colores son distintos, pero en cualquier caso lo que cambia es la interfaz, el lenguaje es exactamente el mismo.

Herramientas

Lo primero que necesitas es un entorno de programación, existen varias alternativas, yo uso Visual Studio 2005, aunque hay versiones mas modernas como la versión 2008 o la 2010, si queréis una alternativa gratuita tenéis el programa MONO (también para LINUX) o el Sharpdevelop (Sólo Windows), pese a esto, recomiendo descargarse el Visual Studio 2008 Express Edition, sólo tienes que registrarse en Microsoft y te darán una licencia gratuita, el VS es muy bueno porque te da opciones para auto completar e información sobre lo que hace cada cosa, algo muy rápido si sabes lo que haces o muy útil si no entiendes muy bien, eso lo dejo a vuestra elección.

Enlaces de interés:

Visual Studio: http://www.microsoft.com/visualstudio/eng/downloads#d-2010-express (español)

( Buscad la versión que mejor os venga )






Sharp Develop: http://www.icsharpcode.net/opensource/sd/ (español)











Mono: http://www.go-mono.com/mono-downloads/download.html (inglés)

Datatypes (Tipos de datos)

Vayamos a los Tipos de Datos, estos son algunos que maneja C#:

Enteros
TipoAncho en bitsRangoSignificado
byte8De 0 a 255Entero sin signo
sbyte8De -128 a 127Entero con signo
short16De -32.768 a 32.767Entero corto con signo
ushort16De 0 a 65.535Entero corto sin signo
int32De -2.147.483.648 a 2.147.483.647Entero medio con signo
uint32De 0 a 4.294.967.295Entero medio sin signo
long64De -9.223.372.036.854.775.808 a 9.223.372.036.854.775.807Entero largo con signo
ulong64De 0 a 18.446.744.073.709.551.615Entero largo sin signo

 Punto flotante (decimales)
TipoAncho en bitsRangoSignificado
float32De 1,5E-45 a 3,4E+38Punto flotante corto
double64De 5E-324 a 1,7E+308Punto flotante largo
decimal128De 1E-28 a 7,9E+28Punto flotante monetario

Caracteres
TipoAncho en bitsRangoSignificado
char16De 0 a 65,535 (código Unicode)Carácter

Datos lógicos
TipoAncho en bitsRangoSignificado
bool1true or false, no se usa 1 ó 0 ya que no hay conversión definidatrue or false