아두이노

마우스로 서보모터 제어하기 실제 적용

ILETCTM 2014. 5. 16. 23:58
반응형

 

 

코드를 약간 수정하였다.

게임으로 적용을 목적으로 해서 오른쪽에 배터리 잔량(?)용 게이지를 넣었다.

키를 누르면 다시 복구됨

그리고 누를때 소리도 나오게 넣었다.

프로세싱 코드

import processing.serial.*;
import ddf.minim.*;

Minim minim;
AudioPlayer player;
AudioInput input;

Serial port;
public  int amm =300;
ammo serv = new ammo();
relod okay = new relod();
void setup()
{
  size(999,999);
  port = new Serial(this, Serial.list()[1],9600);
  minim = new Minim(this);
  player = minim.loadFile("laser-beam.mp3");
  input = minim.getLineIn();
 
}
int a;
int b;
int c;
int d;
int e;
int f;
int g;
 
void draw()
{
  serv.magazinedrow();
  background(255,255,255);
  if(mousePressed&&amm>0)
  {
    player.play();
    g = 1;
    amm = amm - 1;
    serv.magazinedrow();
    serv.ammoremaining();
    fill(255,0,0);
    ellipse(mouseX,mouseY,20,20);
  }
  else
  {
    player.close();
    g = 0;
    serv.magazinedrow();
    serv.ammoremaining();
    fill(255,255,255);
    ellipse(mouseX,mouseY,20,20);
    player = minim.loadFile("laser-beam.mp3");
  }
 
  int x =  mouseX;
  int y = mouseY;
  line(mouseX,0,mouseX,999);
  line(0,mouseY,999,mouseY);
  a = x/100;
  b = x/10%10;
  c = x%10;
  a += 48;
  b += 48;
  c += 48;
  d = y/100;
  e = y/10%10;
  f = y%10;
  d += 48;
  e += 48;
  f += 48;
  g += 48;
  println(a, b, c,",",d,e,f);
  port.write(a);
  port.write(b);
  port.write(c);
  port.write(d);
  port.write(e);
  port.write(f);
  port.write(g);
  port.write(10);
  okay.reload();
}

public class relod
{
  void reload()
  {
    if(keyPressed)
  {
    text("reloading",500,500,100,100);
    amm = 300;
  }
  }
}
   
public class ammo
{
  private int remainingAmmo = 300;
  private int reload;
 

public void magazinedrow()
{
  for(int fullAmmo = 300; fullAmmo > 0; fullAmmo--)
  {
  fill(255,255,255);
  rect(960,980-fullAmmo*3,20,3);
  }
}

public void ammoremaining()
{
  for(int am = amm; am > 0; am--)
  {
  fill(255,0,0);
  rect(960,980-am*3,20,3);
  }
}
}

 

 

 

아두이노 코드

#include <Servo.h>

long data = 0;
Servo xservo;
Servo yservo;
int laser = 12;
void setup()
{
 Serial.begin(9600) ;
 xservo.attach(11);
  yservo.attach(5);
  pinMode(laser, OUTPUT);
}
void loop()
{
  if(Serial.available())
  {
  int x = Serial.read();
    if(isDigit(x))
    {
      data = ((data * 10) + (x - 48));
    }
    else if(x == 10)
    {
      int a = data/10000;
      int b = data%10000/10;
      int c = data%10;
      if(c == 0)
      {
        digitalWrite(laser, LOW);
      }
      else if(c == 1)
      {
        digitalWrite(laser, HIGH);
      }
      Serial.println(data);
      a = map (a, 0, 999, 0, 180);
      b = map(b, 0,999, 0, 180);
      xservo.write(a);
      yservo.write(b);
      data = 0;
    }
}
}

 

 

 

 

 

 

반응형