Archive for the ‘Processing/Arduino’ Category

[Processing] Direct print without dialog

Tuesday, May 5th, 2009

Processing 의 New Tab 을 클릭하여 PrintIt 이라는 이름으로 새로운 탭 생성 후 다음 코드 입력

// //////////////////////////////////////////////////////////////////////////
// Printer – Jpg and Text (more can easily be implemented)
//
// PrintService http://java.sun.com/j2se/1.4.2/docs/api/javax/print/PrintService.html
// DocFlavor http://java.sun.com/j2se/1.4.2/docs/api/javax/print/DocFlavor.html
// PrintRequestAttributeSet http://java.sun.com/j2se/1.4.2/docs/api/javax/print/attribute/PrintRequestAttributeSet.html
// Attribute http://java.sun.com/j2se/1.4.2/docs/api/javax/print/attribute/Attribute.html
//
//
// Yonas Sandbæk – http://seltar.wliia.org
// //////////////////////////////////////////////////////////////////////////

import javax.print.*;
import javax.print.attribute.*;
import com.sun.image.codec.jpeg.*;

class PrintIt{
PrintService[] services;
PrintService service;
DocFlavor docflavor;
Doc myDoc;
PrintRequestAttributeSet aset;
DocPrintJob job;
PrintIt(){
myDoc = null;
job = null;
services = null;
setService(PrintServiceLookup.lookupDefaultPrintService());
setDocFlavor(DocFlavor.BYTE_ARRAY.AUTOSENSE);
aset =  new HashPrintRequestAttributeSet();
}

void setService(PrintService p)
{
service = p;
}

void setDocFlavor(DocFlavor d)
{
docflavor = d;
}

void listPrinters(){
services = PrintServiceLookup.lookupPrintServices(null, null);
for (int i = 0; i < services.length; i++) {
System.out.println(services[i].getName());
DocFlavor[] d = services[i].getSupportedDocFlavors();
for(int j = 0; j < d.length; j++)
System.out.println(”  “+d[j].getMimeType());
}
services = null;
}

// prints a given image
void printJpg(PImage img){
setDocFlavor(DocFlavor.BYTE_ARRAY.JPEG);
print(bufferImage(img));
}

// prints a given string
void printString(String s){
setDocFlavor(DocFlavor.BYTE_ARRAY.AUTOSENSE);
print(s.getBytes());
}

boolean print(byte[] b){
if(!service.isDocFlavorSupported(docflavor)){
println(”MimeType: \”"+docflavor.getMimeType()+”\” not supported by the currently selected printer”);
return false;
}

boolean ret = true;
try{
myDoc = new SimpleDoc(b, docflavor, null);
}
catch(Exception e){
println(e);
ret = false;
}

job = service.createPrintJob();
try {
job.print(myDoc, aset);
}
catch (PrintException pe) {
println(pe);
ret = false;
}

return ret;
}

// used with printJpg()
byte[] bufferImage(PImage srcimg){
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedImage img = new BufferedImage(srcimg.width, srcimg.height, 2);
img = (BufferedImage)createImage(srcimg.width, srcimg.height);
for(int i = 0; i < srcimg.width; i++)
{
for(int j = 0; j < srcimg.height; j++)
{
int id = j*srcimg.width+i;
img.setRGB(i,j, srcimg.pixels[id]);
}
}
try{
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam encpar = encoder.getDefaultJPEGEncodeParam(img);
encpar.setQuality(1,false);
encoder.setJPEGEncodeParam(encpar);
encoder.encode(img);
}
catch(FileNotFoundException e){
System.out.println(e);
}
catch(IOException ioe){
System.out.println(ioe);
}
return out.toByteArray();
}

}

사용될 메인 코드에서는 다음과 같이 사용하면 됩니다.

글로벌하게 PrintIt 의 인스턴스 생성

PrintIt p = new PrintIt();

draw() 안에 다음과 같이 작성, 특정키보드를 누르면 현재화면이 프린트 되도록 함

if(keyPressed && key == ‘p’) p.printJpg(get(0,0,width,height));

Arduino – XBee

Monday, March 2nd, 2009

Arduino에서 XBee 를 사용하는 방법입니다. 책 Making Things Talk 의 203페이지에서는 XBee 칩의 초기화
및 주소 설정 과정이 있습니다만, 브로드케스팅방식을 사용하는데는 굳이 위의 주소설정 과정을 거치지 않아도 잘 동작 합니다.

책에서는 XBee 의 좁은 핀을 넓혀주는 Breakout board를 사용하거나 Arduino 에 장착되기 쉽게 만든 XBee Shield를 사용합니다. 여기서는 sadi의 XBee Shield 를 사용하였으나, 굳이 Shield 가 없어도 구성 방법은 동일합니다. XBee의 핀에 소켓등을 꽂아 핀번호에 맞게 Power / Tx, Rx 등을 연결만 해주면 됩니다. (선들이 좀 주렁주렁 지저분 해지겠지만요)

sadi XBee shield 를 사용할 경우 다음과 같이 Analog 와 Digital Pin 을 사용할 수 있습니다.
주의할점은, USB 를 통하여 컴퓨터와 통신 (Arduino 프로그램 작성 및 다운로드 등) 하는 경우는 우측하단의 점퍼 두개를 왼쪽두개로 잡아주어야 합니다. (XBee 와 통신시에는 오른쪽 두개)

XBee 간의 통신은 브로드캐스팅 방식으로, 별 특별한 코드 없이 일반적인 Serial.print() 와 Serial.read() 로 정보를 쏘고 수신할 수 있습니다. 다음과 같이 마스터/슬레이브 또는 서버/클라이언트 구분없이 동일 코드에서 송신/수신을 테스트 해 볼 수 있습니다.

void setup() {
Serial.begin(19200);
pinMode(txLed, OUTPUT);
pinMode(rxLed, OUTPUT);
}

void loop() {

if(Serial.available() > 0) { // Listening
digitalWrite(rxLed, HIGH);
handleSerial();

… 중간생략

char sensorValue = readSensor();

if(sensorValue > 0) {

digitalWrite(txLed, HIGH);
Serial.print(sensorValue, DEC);
Serial.print(”\r”);
digitalWrite(txLed, LOW);
}
}

void handleSerial() {

inByte = Serial.read();

if((inByte >= ‘0′) && (inByte <= ‘9′)) {
inString[stringPos] = inByte;
stringPos++;
}

if(inByte == ‘\r’) {
int brightness = atoi(inString);
analogWrite(analogLed, brightness);

for(int c=0 ; c<stringPos ; c++) {
inString[c] = 0;
}

stringPos = 0;

}
}

통신 가능한 거리는 실내에서는 30미터가 안되는 것 같고 확 트인 야외에서는 100미터 정도 가능하다고 합니다.


Arduino – Processing 연동

Friday, February 27th, 2009

Arduino 보드에서 Arduino 프로그램으로 USB Serial 방식으로 전송하기때문에, Processing 에서도 Serial API를 활용하여
Arduino 보드에서 보내는 데이터를 읽어낼 수 있다.

Arduino 코드에서는 Serial.print를 이용하여 Serial 데이터를 송신

int flexiSensor = 5;
int button1 = 2;
int button2 = 3;


int flexiValue = 0;
int button1Value = 0;
int button2Value = 0;

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

pinMode(button1, INPUT);
pinMode(button2, INPUT);
}

void loop ()
{
flexiValue = analogRead(flexiSensor);
button1Value = digitalRead(button1);
button2Value = digitalRead(button2);

Serial.print(flexiValue, DEC);
Serial.print(”,”);
Serial.print(button1Value, DEC);
Serial.print(”,”);
Serial.println(button2Value, DEC);
}


Processing 에서는 serial 라이브러리를 추가해주고,  Serial.list() 를 이용해 목록확인, 읽어들일 포트를 설정한 후

serialEvent 함수를 구현하여 그안에서 데이터가 왔을경우에 대한 처리를 한다

import processing.serial.*;

Serial inputPort;
int linefeed = 10;
int ballPosition = 10;

void setup()
{
size(640,480);
println(Serial.list()); // 가용한 serial port 의 자원의 목록을 보여준다

inputPort = new Serial(this, Serial.list()[0], 9600); // 이경우는 목록의 [0] 번이 Arduino 인경우임
inputPort.bufferUntil(linefeed);

}

void draw()
{
background(0);
fill(255,230,0);
ellipse(ballPosition, 50, 50, 50);
print(”ballPosition=” + ballPosition);

}

void serialEvent(Serial inputPort) // serial port 로 데이터가 들어올 경우 호출되는 함수
{
String inputString = inputPort.readStringUntil(linefeed);

if(inputString != null)
{
inputString = trim(inputString);
int sensorValues[] = int(split(inputString, ‘,’));
ballPosition = sensorValues[0];

}
}

이와 같은 방법으로 Arduino 를 통한 다양한 센서, 버튼 등의 physical 한 interface 의 입력을 받아
Processing 을 통하여 graphical 한 visual 요소를 표현 할 수 있다.