Showing posts with label Programació. Show all posts
Showing posts with label Programació. Show all posts

Nov 4, 2011

Send a method / function as a parameter in Processing

To send a method or a function as a parameter you can use the folloing code.
This code is also usable in Android-Processing and Java.

import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

///////////////////////////////// Metode class ////////////////////////////// 
class Metode{
  Object obj;             // objecte que conté el mètode que HA de ser PUBLIC
  Method method;
  
  Metode(Object lobj, String lnomMetode, Class... parametres) {
    obj = lobj;
    
    try {
      method = lobj.getClass().getMethod(lnomMetode, parametres);     //parametres = new Class[] {  }  ||  new Class[] { int.class, float.class }
    } catch (NoSuchMethodException nsme) {
      System.err.println("There is no " + lnomMetode + "() method " + "in the class " + obj.getClass().getName());
    } catch (Exception e) {
      e.printStackTrace();
    } 
  }////////
 

 
  Object run(Object... parametres) {
    try {
      return(method.invoke(obj, parametres));                  //parametres = new Object[] {  }  ||  new object[] { 1, 5.1 }
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.getTargetException().printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return(null);
  }////////  
  
}//end class Metode


///////////////////////////// Example //////////////////////////

A aObj = new A();
C cObj = new C();

void setup(){
  Metode a = new Metode(  aObj, "metA", int.class, float.class  );
  a.run(3, 5.1);  // prints '3 5.1'
  
  rebMetode(  new Metode(  this, "metB")  );  // prints 'hola'
  
  Metode c = new Metode(  cObj, "metC", int.class  );
  int res = (Integer)c.run(2);  // prints 'Has dit: 2 i jo et dic: 12' 
  println(res);  // prints '12'
}


void rebMetode(Metode metode){  metode.run();  }


public void metB(){  println("hola");  }

class A{  A(){}  public void metA(int i, float f){  println(i+" "+f);                                                   }  }
class C{  C(){}  public int  metC(int i)         {  println("Has dit: " + i + " i jo et dic: "+(i+10));  return(i+10);  }  }

////////////////////////////// Example End ///////////////////////////////////



Oct 4, 2011

Set Window (Screen) Bright in Processing-Android

To Set the Window Bright in Processing for Android simply add the following code to your sketch:

void setup(){...}
void draw() {...}

//www.akeric.com/blog/?p=1313

//-----------------------------------------------------------------------------------------
// Override the parent (super) Activity class:
// States onCreate(), onStart(), and onStop() aren't called by the sketch.  Processing is entered at
// the 'onResume()' state, and exits at the 'onPause()' state, so just override them:

void onResume() {
  super.onResume();

  setWindowBright();

  println("RESUMED! (Sketch Entered...)");
}

import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;



void setWindowBright(){
  getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON | LayoutParams.FLAG_TURN_SCREEN_ON);

// to set a diferent bright level (other than default)
//  WindowManager.LayoutParams layoutParams = getWindow().getAttributes();   
//  layoutParams.screenBrightness = 0.8f;                    
//  getWindow().setAttributes(layoutParams);
}

That's all.

Sep 14, 2011

Translucent window en Processing


Per aconseguir una finestra transparent o translúcida en processing:



Aqui teniu el codi:


//http://java.sun.com/developer/technicalArticles/GUI/translucent_shaped_windows/
import com.sun.awt.AWTUtilities;  // no necessària amb jre7
import java.awt.*;
import javax.swing.JFrame;

JFrame topFrame = null;
PGraphics pg3D;
int framePosX = 800;
int framePosY = 100;
int frameWidth = 300;
int frameHeight = 300;
float opacitatTopFrame = 1.0f;

public void init(){
  frame.removeNotify();
  frame.setUndecorated(true);
  AWTUtilities.setWindowOpaque(frame, false);
  AWTUtilities.setWindowOpacity(frame, 0.0f);  
  //frame.setOpacity(0.0f);  // amb jre7
  frame.setBackground(new Color(0.0f,0.0f,0.0f,0.0f));                
  frame.setVisible(false);
  frame.setLayout( null );
  frame.addNotify();
  
  GraphicsConfiguration translucencyCapableGC;
  translucencyCapableGC = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();

  topFrame = new JFrame(translucencyCapableGC);
  topFrame.setUndecorated(true);
  //topFrame.setOpacity(opacitatTopFrame); // amb jre7
  AWTUtilities.setWindowOpaque(topFrame, false);
  AWTUtilities.setWindowOpacity(topFrame, opacitatTopFrame);    
  topFrame.setAlwaysOnTop(false);
  topFrame.setLocationRelativeTo(null);
  topFrame.setLocation(framePosX, framePosY);
  topFrame.setSize(frameWidth, frameHeight);
  topFrame.setBackground(new Color(0,0,0,0));
  topFrame.setVisible(true);
  topFrame.setTitle( frame == null? "":frame.getTitle() );
  topFrame.setIconImage( frame.getIconImage() );
  topFrame.setLayout( null ); 
  topFrame.addNotify();
  super.init();
  g.format = ARGB;
  g.setPrimary(false);
}


void setup() {
  size(frameWidth, frameHeight);
  colorMode(RGB,255,255,255,255);
  pg3D = createGraphics(frameWidth, frameHeight,P3D);
  pg3D.colorMode(RGB,255,255,255,255);
}


float angle = 0;

void draw() {
  
   background(0,0,255,135);
   fill(0,255,0,55);
   int mX = MouseInfo.getPointerInfo().getLocation().x-framePosX;
   int mY = MouseInfo.getPointerInfo().getLocation().y-framePosY;
   rectMode(CENTER);
   rect(mX, mY,50,50);
   
   pg3D.beginDraw();
     pg3D.background(0,0,0,0);
     pg3D.stroke(0); 
     pg3D.fill(255,0,0,255);
     pg3D.translate(100,100);   pg3D.rotateZ(angle);   pg3D.rotateX(angle);   pg3D.rotateY(angle);
     pg3D.rectMode(CENTER);
     pg3D.rect(0,0,50,50);
   pg3D.endDraw();
   
   image(pg3D,0,0);
   frame.setVisible(false);
   topFrame.add(this);
   
   angle+=0.02;
}

Apr 14, 2011

BarCode reading and writing with Processing



Mira aquest enllaç, però si el compiles tu, tindràs una verssió mes actualitzada.


// http://code.google.com/p/zxing/wiki/GettingStarted
// http://blog.makezine.com/archive/2011/03/codebox-use-qr-codes-in-processing.html
// http://code.google.com/p/zxing/wiki/DeveloperNotes
// http://zxing.org/w/docs/javadoc/index.html
// http://code.google.com/p/zxing/source/browse/trunk#trunk%2Fcore%2Fsrc
// http://zxing.org/w/docs/javadoc/com/google/zxing/client/j2se/package-frame.html
// http://code.google.com/p/zxing/source/browse/trunk#trunk%2Fjavase%2Fsrc%2Fcom%2Fgoogle%2Fzxing%2Fclient%2Fj2se
// http://code.google.com/p/zxing/source/browse/trunk/android/src/com/google/zxing/client/android/encode/QRCodeEncoder.java




import com.google.zxing.*;
import java.awt.image.BufferedImage;


int SIZE = 400;


//com.google.zxing.Writer writer = new com.google.zxing.qrcode.QRCodeWriter(); 
//http://zxing.org/w/docs/javadoc/index.html
//com.google.zxing.Reader reader = new com.google.zxing.qrcode.QRCodeReader();
MultiFormatWriter writer = new MultiFormatWriter();
MultiFormatReader reader = new MultiFormatReader();
BitMatrix QRBitMatrix = new BitMatrix(SIZE, SIZE);
BarcodeFormat format = BarcodeFormat.QR_CODE;
// QR_CODE
// DATA_MATRIX
// UPC_E
// UPC_A
// EAN_8
// EAN_13
// CODE_128
// CODE_39       ATENCIÓ    Només Numèric
// ITF






void setup(){
size(SIZE, SIZE);


PImage img = new PImage(SIZE, SIZE);
String codi = "Hola";//println(codi.length());


img = codificaBarCcode(codi, format, SIZE, SIZE);


image(img, 0, 0);
img.save(savePath("data\\QR.jpg"));


println(decodificaBarCode(img));
}






PImage codificaBarCcode(String codi, BarcodeFormat format, int ample, int alt){
color negre = color(0), blanc = color(255);
PImage img = new PImage(ample, alt);
Hashtable hints = new Hashtable(1);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

try {
QRBitMatrix = writer.encode(codi, format, ample, alt, hints);
} catch (Exception e) {println(e.toString());}

int width = QRBitMatrix.getWidth();
int height = QRBitMatrix.getHeight();

for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
if(QRBitMatrix.get(x, y)) img.set(x, y, negre); else img.set(x, y, blanc);
}
}
return(img);
}




String decodificaBarCode(PImage img){
String retorn = "";
Result result = null;

try {
LuminanceSource source = new BufferedImageLuminanceSource((BufferedImage)img.getImage());
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
result = reader.decode(bitmap);
retorn = result.getText();
if (retorn != null) {
//println(result.getText());
ResultPoint[] points = result.getResultPoints();

for (int i = 0; i < points.length; i++) {
fill(#ff8c00);
ellipse(points[i].getX(), points[i].getY(), 20,20);
}
}
} catch (Exception e) {println(e.toString());}

return(retorn);
}

Mar 5, 2011

Us de punters en Processing

En el següent exemple simulo l'us de punters en processing.
Per fer-ho he declarat la clse Boolean.
A més a més el codi també és un exemple del us del threading en Processing.

//http://wiki.processing.org/w/Threading




Boolean pinta = new Boolean(false);


void setup() {
  setValueAfterMs(pinta, true, 2000);
  setValueAfterMs(pinta, false, 3000);
  setValueAfterMs(pinta, true, 4000);
  setValueAfterMs(pinta, false, 5000);
  setValueAfterMs(pinta, true, 6000);
  setValueAfterMs(pinta, false, 7000);
}


void draw() {
  print(pinta.valor);
}


ArrayList StacksetValueAfterMsClass = new ArrayList();
int usedArrayListElements = 0;

void setValueAfterMs(Boolean lVarDest, boolean lValor, int lWait){
  int index = StacksetValueAfterMsClass.size();

  StacksetValueAfterMsClass.add(new setValueAfterMsClass(lVarDest, lValor, lWait));
  ((setValueAfterMsClass)StacksetValueAfterMsClass.get(index)).start();
}


class Boolean{
  boolean valor;

  Boolean(boolean lValor){
    valor = lValor;
  }
}


class setValueAfterMsClass extends Thread {
  boolean running; // Is the thread running? Yes or no?
  int wait; // How many milliseconds should we wait in between executions?
  Boolean varDest;
  boolean valor;

  // Constructor, create the thread // It is not running by default
  setValueAfterMsClass (Boolean lVarDest, boolean lValor, int lWait) {
    usedArrayListElements++;
    varDest = lVarDest;
    valor = lValor;
    wait = lWait;
    running = false;
  }

  void start () { // Overriding "start()"
    if(!running){
      running = true; // Set running equal to true
      super.start();
    }
  }

  void run () { // We must implement run, this gets triggered by start()
    while (running) {
      try {
        sleep((long)(wait));
        varDest.valor = valor;
        quit();
      } catch (Exception e) {
      }
    }
  }

  void quit() { // Our method that quits the thread

    running = false; // Setting running to false ends the loop in run()
    interrupt(); // IUn case the thread is waiting. . .
    usedArrayListElements--;
    if(usedArrayListElements == 0){ // Destrueix l'ArrayList
      for(int j = StacksetValueAfterMsClass.size()-1 ; j >= 0 ; j--){
        StacksetValueAfterMsClass.remove(j);
      }
    }
  }
}// end class

Nov 16, 2010

IR Shutter for Canon EOS 400D with Arduino

Per fer un disparador infraroig per la canon EOS 400D muntem aquest circuit amb arduino:


i carreguem el seguent programa:

/*

Arduino sketch for simulating a Canon RC-1 IR remote control
http://controlyourcamera.blogspot.com/
Huge thanks go to http://www.doc-diy.net/photo/rc-1_hacked/index.php for figuring out the IR code.
*/


const int irLED = 10;
const int statusLED = 13;
const int pushBUTTON = 3;

void setup() {
  pinMode(irLED, OUTPUT);
  pinMode(statusLED, OUTPUT);
  pinMode(pushBUTTON, INPUT);
}

void loop() {
  if (digitalRead(pushBUTTON) == HIGH) {
    digitalWrite(statusLED, HIGH);
    ShuttCanon();
    delay(10);
    digitalWrite(statusLED, LOW);
  }
}

void ShuttCanon() {                     // When the camera is in BULB mode,
  for(int i=0; i<16; i++) {              //        the first call to ShutCanon() opens the shutter
    digitalWrite(irLED, HIGH);      //       and a scond one closes the shutter
    delayMicroseconds(11);          // delay de 15 us (11 més el temps d'execució)
    digitalWrite(irLED, LOW);
    delayMicroseconds(11);
  }

/*






*/
  delayMicroseconds(7330);      // 7330 fa la foto inmediatament. 5360 fa la foto amb un delay de 2 s
  for(int i=0; i<16; i++) {           //           i en alguns models começa el video recording
    digitalWrite(irLED, HIGH);
    delayMicroseconds(11);
    digitalWrite(irLED, LOW);
    delayMicroseconds(11);
  }
}


Quan premem el pulsador es dispara la càmera. És important notar que si la càmera es en modus 'BULB', la primera crida a la funció ShuttCanon obre l'obturador i la segona el tanca (cosa la qual pot esser especialment útil).

Nov 9, 2010

Capacitive sensing w/ Arduino

Aquest és el meu sensor capacitiu pensat per nesurar la humitta del terra (i per aquest motiu és estanc):




Nov 2, 2010

Focs Artificials


Fes Click amb el mouse

Oct 25, 2010

Oct 20, 2010

Modificació de la plantilla del blog al Blogger de Google

Aquesta es la meva modificació de la plantilla del blog:

Primer cal fer una còpia de seguretat del blog:
      Disseny - Modifica l'HTML - Baixar la plantilla completa

A Disseny de la plantilla - Avançat - CSS, he afegit:

.tabs-inner .widget ul            {                                                  background: rgba(   0,   0,  0,    0);         }
.tabs-inner .widget li a          { border: rgba(   0,   0,   0, 0.3)  solid 1px;    background: rgba( 255, 150,  50, 0.2);         }
.tabs-inner .widget li.selected a { border: rgba(   0,   0,   0, 0.5)  solid 1px;    background: rgba( 255, 150,  50, 0.4);         }
.tabs-inner .widget li a:hover    { border: rgba(   0,   0,   0, 0.6)  solid 1px;    background: rgba( 255, 150,  50, 0.6);         }
.post           {                                                font-size: 80%;                                                       }
.post-header    {                                                font-size: 90%;                                                       }
.post-outer     { border: rgba(   0,    0,    0, 0.5) solid 1px; border-radius: 7px; background: rgba(   0,   0,   0, 0.5);         }
.sidebar        { border: rgba(   0,    0,    0,   0) solid 5px; border-radius: 7px; background: rgba(   0,   0,   0, 0.6);         }
.widget ul      {                                                                    background: rgba(   0,   0,   0, 0.1);         }
.widget-content   {                                              font-size: 90%;                                                    }
.content-outer  {                                                                    background: rgba(   0,   0,   0, 0.7);         }
'.fauxcolumn-inner {                                                                  background: rgba(   0,   0,   0, 0.3);         }
'.body-fauxcolumns {                                                                  background: rgba(   0,   0,   0, 0.3);         }
'.date-header {font-size: 120%; background: rgba(100, 1000, 1000, 0.4); text-align: center; max-width: 15%;  border:solid 20px rgba(100, 1000, 1000, 0.3); border-radius: 20px; 'height: 50px;}

Les 3 darreres línies estan comentades i per tant no s'apliquen.
i el resultat és:
Abans


Després


Oct 3, 2010

MS-Acces

Runtime:

Convert Twips to Píxeles
'''''''''''' Per convertir twips a pixels
Public Declare Function GetDC Lib "user32" (ByVal hwnd As Long) As Long
Public Declare Function ReleaseDC Lib "user32" (ByVal hwnd As Long, ByVal hdc As Long) As Long
Public Declare Function GetDeviceCaps Lib "gdi32" (ByVal hdc As Long, ByVal nIndex As Long) As Long
Public Const WU_LOGPIXELSX = 88
Public Const WU_LOGPIXELSY = 90
Public Const X_HOR    As Long = &H0
Public Const X_VERT   As Long = &H1
'''''''''''' Per convertir twips a pixels


Public Function TwipsToPixels(lngTwips As Long, lngDirection As Long) As Long
   'Handle to device
   Dim lngDC As Long
   Dim lngPixelsPerInch As Long
   Const nTwipsPerInch = 1440
   lngDC = GetDC(0)


   Select Case lngDirection
    Case X_HOR                  ' els pixels no son quadrats
      lngPixelsPerInch = GetDeviceCaps(lngDC, WU_LOGPIXELSX)
    Case X_VERT
      lngPixelsPerInch = GetDeviceCaps(lngDC, WU_LOGPIXELSY)
   End Select
   lngDC = ReleaseDC(0, lngDC)
   TwipsToPixels = (lngTwips / nTwipsPerInch) * lngPixelsPerInch
End Function


Public Function PixelsToTwips(lngTwips As Long, lngDirection As Long) As Long
   'Handle to device
   Dim lngDC As Long
   Dim lngPixelsPerInch As Long
   Const nTwipsPerInch = 1440
   lngDC = GetDC(0)


   Select Case lngDirection
    Case X_HOR                  ' els pixels no son quadrats
      lngPixelsPerInch = GetDeviceCaps(lngDC, WU_LOGPIXELSX)
    Case X_VERT
      lngPixelsPerInch = GetDeviceCaps(lngDC, WU_LOGPIXELSY)
   End Select
   lngDC = ReleaseDC(0, lngDC)
   PixelsToTwips = (lngTwips / lngPixelsPerInch) * nTwipsPerInch
End Function

Imprimir texto a la impresora predeterminada con Access Basic (1.x/2.0)
    'Obre el canal de la impressora
    Open "\\estacio4\zebra" For Output As #1
  
    'Configuració de la impressora
    Print #1, "^XA~TA-008~JSN^LT0^MMT^MNW^MTT^PON^PMN^LH0,0^JMA^PR4,4^MD0^JUS^LRN^CI27^XZ"
  
    'Nou format d'etiqueta i Llargada Etiqueta
    Print #1, "^XA^LL0200"
  
    'Amplada
    Print #1, "^PW639"
  
    'Codi de Barres de la 1ª Etiqueta
    Print #1, "^BY2,3,32^FT133,118^BCN,,N,N"
    Print #1, "^FD>;" & Ref_Imprimir & "^FS"
  
    'Codi de Barres de la 2ª Etiqueta
    Print #1, "^BY2,3,32^FT357,118^BCN,,N,N"
    Print #1, "^FD>;" & Ref_Imprimir & "^FS"
  
    'Referència 1ª etiqueta
    Print #1, "^FT162,139^A0N,23,24^FD" & Ref_Maca & "^FS"
  
    'Referència 2ª etiqueta
    Print #1, "^FT386,139^A0N,23,24^FD" & Ref_Maca & "^FS"
  
    'Imprimeix el nobre necessari d'etiquetes (Sortida de 2)
    Print #1, "^PQ" & CStr(Q2) & "," & CStr(Q2) & ",1,N^XZ"
  
    'Tanca el canal de la Impressora
    Close #1

.NET Framework Solutions—In Search of the Lost Win32 API
Per moure una finestra clicant el botó 'BotoDesp' (p.65)

'Constantes para SendMessage
Public Const WM_LBUTTONUP = &H202
Public Const WM_SYSCOMMAND = &H112
Public Const SC_MOVE = &HF010
Public Const MOUSE_MOVE = &HF012
Public Const WM_NCLBUTTONDOWN = &HA1
Public Const HTCAPTION = 2

Public Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Long) As Long
Public Declare Function ReleaseCapture Lib "user32" () As Boolean


Private Sub BotoDesp_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
    BotoDesp.Picture = DirectoriRecursos & "P" & Right(BotoDesp.Picture, 9)
    Clicat = True
    Call SendMessage(Me.hwnd, WM_SYSCOMMAND, MOUSE_MOVE, 0)
End Sub

Private Sub BotoDesp_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
    If Clicat And Button = 1 Then
        Call SetWindowPos(Application.hWndAccessApp, HWND_TOP, -200, -200, 10, 10, 0)
        Call ReleaseCapture
        Call SendMessage(Me.hwnd, WM_NCLBUTTONDOWN, HTCAPTION, 0&)
    End If
End Sub


Private Sub BotoDesp_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)
    BotoDesp.Picture = DirectoriRecursos & Right(BotoDesp.Picture, 9)
    Clicat = False
End Sub

Espais de color HSL and HSV