Skip to content

Instantly share code, notes, and snippets.

@sulram
Created June 23, 2012 23:05
Show Gist options
  • Save sulram/2980487 to your computer and use it in GitHub Desktop.
Save sulram/2980487 to your computer and use it in GitHub Desktop.
Oficina ARDUINO
import processing.serial.*;
Serial arduino; // The serial port
void setup () {
size(800, 600);
println(Serial.list());
arduino = new Serial(this, Serial.list()[0], 9600);
arduino.bufferUntil('\n');
noStroke();
background(0);
}
void draw () {
// everything happens in the serialEvent()
}
void serialEvent (Serial device) {
String string_arduino = device.readStringUntil('\n');
if (string_arduino != null) {
string_arduino = trim(string_arduino);
float val = map( int(string_arduino), 50, 250, 0, 1023 );
//background( val / 4 );
fill( val/4 , 20 );
rect(0,0,width,height);
fill( 255-val/4);
ellipse( width / 2, height / 2, val, val);
println(string_arduino);
}
}
#define triggerPin 4
#define echoPin 3
void setup() {
// Configura a saída serial para recuperar a leitura do sensor
Serial.begin(9600);
// Configura a porta digital em modo saida
pinMode(triggerPin, OUTPUT);
// Configura a porta digital em modo entrada
pinMode(echoPin, INPUT);
}
void loop() {
// Envia um sinal de 10ms ao sensor
digitalWrite(triggerPin, LOW);
delayMicroseconds(2);
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10);
digitalWrite(triggerPin, LOW);
// O sensor calcula o tempo gasto entre o envio e o recebimento
// do sinal e retorna um pulso com esta duração
long duration = pulseIn(echoPin, HIGH);
// Converte o tempo para distancia em centimetros
float cm = microsecondsToCentimeters(duration);
// Informa a distancia na serial
Serial.println(cm);
delay(10);
}
float microsecondsToCentimeters(long microseconds){
// Converte o tempo de microsegundos para segundos
float seconds = (float) microseconds / 1000000.0;
// Como a velocidade do som de 340m/s calcula-se a
// distancia percorrida
float distance = seconds * 340;
// Divide o resultado por dois pois o tempo é calculado
// considerando a ida e a volta do sinal
distance = distance / 2;
// Converte o resultado em metros para centimetros
distance = distance * 100;
return distance;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment