Anda di halaman 1dari 20

Proyecto Arduino Radar

En este tutorial de Arduino, te mostraré cómo puedes hacer que este radar de aspecto genial use
la placa Arduino y el entorno de desarrollo de procesamiento. Puede ver el siguiente video o leer
el tutorial escrito a continuación para obtener más detalles.

Componentes necesarios para este Proyecto Arduino


 Sensor ultrasónico HC- SR04 .......
 Servomotor .................................
 Arduino Board ...........................
 Tablero y cables de salto ...

Construyendo el dispositivo
 Primero hice un soporte de cartón para conectar el sensor ultrasónico al Servo motor. Lo doblé
como se muestra en la siguiente imagen, lo pegué y aseguré al servomotor con un tornillo
como este.

 También adjunté un encabezado de alfiler en el que soldé 4 cables de puente para conectar el
sensor.
 Finalmente aseguré el servo motor a la placa Arduino usando una banda elástica.

Esquema de circuito

Conecté el sensor ultrasónico HC-SR04 a los pines número 10 y 11 y el servomotor al pin número
12 en la placa Arduino.
Códigos fuente
Ahora necesitamos crear un código y subirlo a la Junta de Arduino que permitirá la interacción
entre Arduino y el IDE de procesamiento. Para entender cómo funciona la conexión, haga clic aquí
para visitar mi Tutorial de procesamiento y Arduino .

Aquí está el código fuente de Arduino con una descripción de cada línea del código (ESPAÑOL)

1. // Incluye la biblioteca Servo


2. #include <Servo.h>.
3.
4. // Define los pines Tirg y Echo del sensor ultrasónico
5. const int trigPin = 10 ;
6. const int echoPin = 11 ;
7. // Variables para la duración y la distancia
8. larga duración;
9. distancia int ;
10.
11. Servo myServo; // Crea un objeto servo para controlar el servomotor
12.
13. void setup ( ) {
14. pinMode ( trigPin, OUTPUT ) ; // Establece el trigPin como salida
15. pinMode ( echoPin, INPUT ) ; // Establece el echoPin como entrada
16. De serie. comenzar ( 9600 ) ;
17. myServo. adjuntar ( 12 ) ; // Define en qué pin está el servomotor conectado
18. }
19. void loop ( ) {
20. // gira el servomotor de 15 a 165 grados
21. para ( int i = 15 ; i <= 165 ; i ++ ) {
22. myServo. escribir ( i ) ;
23. retraso ( 30 ) ;
24. distance = calculateDistance ( ) ; // Llama a una función para calcular la distancia medida por el sensor ultrasónico para cada grado
25.
26. De serie. imprimir ( i ) ; // Envía el grado actual en el puerto serie
27. De serie. imprimir ( "," ) ; // Envía el carácter de adición justo al lado del valor anterior necesario más tarde en el IDE de
procesamiento para la indexación
28. De serie. imprimir ( distancia ) ; // Envía el valor de la distancia al puerto serie
29. De serie. imprimir ( "." ) ; // Envía el carácter de adición justo al lado del valor anterior necesario más tarde en el IDE de
procesamiento para la indexación
30. }
31. // Repite las líneas anteriores de 165 a 15 grados
32. para ( int i = 165 ; i> 15 ; i-- ) {
33. myServo. escribir ( i ) ;
34. retraso ( 30 ) ;
35. distance = calculateDistance ( ) ;
36. De serie. imprimir ( i ) ;
37. De serie. imprimir ( "," ) ;
38. De serie. imprimir ( distancia ) ;
39. De serie. imprimir ( "." ) ;
40. }
41. }
42. // Función para calcular la distancia medida por el sensor ultrasónico
43. int calculateDistance ( ) {
44.
45. digitalWrite ( trigPin, BAJO ) ;
46. delayMicroseconds ( 2 ) ;
47. // Establece el trigPin en estado ALTO durante 10 micro segundos
48. digitalWrite ( trigPin, ALTO ) ;
49. delayMicroseconds ( 10 ) ;
50. digitalWrite ( trigPin, BAJO ) ;
51. duration = pulseIn ( echoPin, HIGH ) ; // Lee el echoPin, devuelve el tiempo de viaje de la onda de sonido en microsegundos
52. distancia = duración * 0 . 034 / 2 ;
53. distancia de regreso ;
54. }

INGLES

1. // Includes the Servo library


2. #include <Servo.h>.
3.
4. // Defines Tirg and Echo pins of the Ultrasonic Sensor
5. const int trigPin = 10;
6. const int echoPin = 11;
7. // Variables for the duration and the distance
8. long duration;
9. int distance;
10.
11. Servo myServo; // Creates a servo object for controlling the servo motor
12.
13. void setup() {
14. pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
15. pinMode(echoPin, INPUT); // Sets the echoPin as an Input
16. Serial.begin(9600);
17. myServo.attach(12); // Defines on which pin is the servo motor attached
18. }
19. void loop() {
20. // rotates the servo motor from 15 to 165 degrees
21. for(int i=15;i<=165;i++){
22. myServo.write(i);
23. delay(30);
24. distance = calculateDistance();// Calls a function for calculating the distance measured by the Ultrasonic sensor for each degree
25.
26. Serial.print(i); // Sends the current degree into the Serial Port
27. Serial.print(","); // Sends addition character right next to the previous value needed later in the Processing IDE for indexing
28. Serial.print(distance); // Sends the distance value into the Serial Port
29. Serial.print("."); // Sends addition character right next to the previous value needed later in the Processing IDE for indexing
30. }
31. // Repeats the previous lines from 165 to 15 degrees
32. for(int i=165;i>15;i--){
33. myServo.write(i);
34. delay(30);
35. distance = calculateDistance();
36. Serial.print(i);
37. Serial.print(",");
38. Serial.print(distance);
39. Serial.print(".");
40. }
41. }
42. // Function for calculating the distance measured by the Ultrasonic sensor
43. int calculateDistance(){
44.
45. digitalWrite(trigPin, LOW);
46. delayMicroseconds(2);
47. // Sets the trigPin on HIGH state for 10 micro seconds
48. digitalWrite(trigPin, HIGH);
49. delayMicroseconds(10);
50. digitalWrite(trigPin, LOW);
51. duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds
52. distance= duration*0.034/2;
53. return distance;
54. }

Ahora recibiremos los valores para el ángulo y la distancia medida por el sensor desde la placa
Arduino en el IDE de procesamiento usando la función SerialEvent () que lee los datos del puerto
serial y vamos a poner los valores del ángulo y la distancia en las variables iAngle e
iDistance. Esta variable se usará para dibujar el radar, las líneas, los objetos detectados y parte
del texto.

Para dibujar el radar hice esta función drawRadar () que consiste en funciones de arco () y line
() .
1. void drawRadar ( ) {
2. pushMatrix ( ) ;
3. traducir ( 960 , 1000 ) ; // mueve las coordinadas iniciales a la nueva ubicación
4. noFill ( ) ;
5. strokeWeight ( 2 ) ;
6. golpe ( 98 , 245 , 31 ) ;
7. // dibuja las líneas de arco
8. arco ( 0 , 0 , 1800 , 1800 , PI, TWO_PI ) ;
9. arco ( 0 , 0 , 1400 , 1400 , PI, TWO_PI ) ;
10. arco ( 0 , 0 , 1000 , 1000 , PI, TWO_PI ) ;
11. arco ( 0 , 0 , 600 , 600 , PI, TWO_PI ) ;
12. // dibuja las líneas de ángulo
13. línea ( - 960 , 0 , 960 , 0 ) ;
14. línea ( 0 , 0 , - 960 * cos ( radianes ( 30 ) ) , - 960 * sin ( radianes ( 30 ) ) ) ;
15. línea ( 0 , 0 , - 960 * cos ( radianes ( 60 ) ) , - 960 * sin ( radianes ( 60 ) ) ) ;
16. línea ( 0 , 0 , - 960 * cos ( radianes ( 90 ) ) , - 960 * sin ( radianes ( 90 ) ) ) ;
17. línea ( 0 , 0 , - 960 * cos ( radianes ( 120 ) ) , - 960 * sin ( radianes ( 120 ) ) ) ;
18. línea ( 0 , 0 , - 960 * cos ( radianes ( 150 ) ) , - 960 * sin ( radianes ( 150 ) ) ) ;
19. línea ( - 960 * cos ( radianes ( 30 ) ) , 0 , 960 , 0 ) ;
20. popMatrix ( ) ;
21. }

INGLES…………………………………………………………….

1. void drawRadar() {
2. pushMatrix();
3. translate(960,1000); // moves the starting coordinats to new location
4. noFill();
5. strokeWeight(2);
6. stroke(98,245,31);
7. // draws the arc lines
8. arc(0,0,1800,1800,PI,TWO_PI);
9. arc(0,0,1400,1400,PI,TWO_PI);
10. arc(0,0,1000,1000,PI,TWO_PI);
11. arc(0,0,600,600,PI,TWO_PI);
12. // draws the angle lines
13. line(-960,0,960,0);
14. line(0,0,-960*cos(radians(30)),-960*sin(radians(30)));
15. line(0,0,-960*cos(radians(60)),-960*sin(radians(60)));
16. line(0,0,-960*cos(radians(90)),-960*sin(radians(90)));
17. line(0,0,-960*cos(radians(120)),-960*sin(radians(120)));
18. line(0,0,-960*cos(radians(150)),-960*sin(radians(150)));
19. line(-960*cos(radians(30)),0,960,0);
20. popMatrix();
21. }
Para dibujar la línea que se mueve a lo largo del radar hice esta función drawLine () . Su centro
de rotación se establece con la función translate () y utilizando la función de línea () en la que se
utiliza la variable iAngle, la línea se vuelve a dibujar para cada grado.

1. void drawLine ( ) {
2. pushMatrix ( ) ;
3. strokeWeight ( 9 ) ;
4. golpe ( 30 , 250 , 60 ) ;
5. traducir ( 960 , 1000 ) ; // mueve las coordinadas iniciales a la nueva ubicación
6. line ( 0 , 0 , 950 * cos ( radianes ( iAngle ) ) , - 950 * sen ( radianes ( iAngle ) ) ) ; // dibuja la línea según el ángulo
7. popMatrix ( ) ;
8. }
INGLES

1. void drawLine() {
2. pushMatrix();
3. strokeWeight(9);
4. stroke(30,250,60);
5. translate(960,1000); // moves the starting coordinats to new location
6. line(0,0,950*cos(radians(iAngle)),-950*sin(radians(iAngle))); // draws the line according to the angle
7. popMatrix();
8. }

Para dibujar los objetos detectados hice esta función drawObject () . Toma la distancia del sensor
ultrasónico, lo transforma en píxeles y, en combinación con el ángulo del sensor, atrae el objeto en
el radar.

1. void drawObject ( ) {
2. pushMatrix ( ) ;
3. traducir ( 960 , 1000 ) ; // mueve las coordinadas iniciales a la nueva ubicación
4. strokeWeight ( 9 ) ;
5. golpe ( 255 , 10 , 10 ) ; // color rojo
6. pixsDistance = iDistance * 22.5 ; // cubre la distancia desde el sensor de cm a píxeles
7. // limitando el rango a 40 cms
8. if ( iDistance < 40 ) {
9. // dibuja el objeto según el ángulo y la distancia
10. line ( pixsDistance * cos ( radianes ( iAngle ) ) , -pixsDistance * sin ( radianes ( iAngle ) ) , 950 * cos ( radianes ( iAngle ) ) , - 950
* sin ( radianes ( iAngle ) ) ) ;
11. }
12. popMatrix ( ) ;
13. }

INGLES

1. void drawObject() {
2. pushMatrix();
3. translate(960,1000); // moves the starting coordinats to new location
4. strokeWeight(9);
5. stroke(255,10,10); // red color
6. pixsDistance = iDistance*22.5; // covers the distance from the sensor from cm to pixels
7. // limiting the range to 40 cms
8. if(iDistance<40){
9. // draws the object according to the angle and the distance
10. line(pixsDistance*cos(radians(iAngle)),-pixsDistance*sin(radians(iAngle)),950*cos(radians(iAngle)),-950*sin(radians(iAngle)));
11. }
12. popMatrix();
13. }

Para el texto en la pantalla hice la función drawText () que dibuja textos en ubicaciones
particulares.

Todas estas funciones se llaman en la función principal draw ()que se repite todo el tiempo y
dibuja la pantalla. También aquí estoy usando esta función de relleno () con 2 parámetros para
simular el desenfoque de movimiento y el desvanecimiento lento de la línea en movimiento.

1. void draw ( ) {
2.
3. llenar ( 98 , 245 , 31 ) ;
4. textFont ( orcFont ) ;
5. // simulando el desenfoque de movimiento y el desvanecimiento lento de la línea de movimiento
6. noStroke ( ) ;
7. llenar ( 0 , 4 ) ;
8. rect ( 0 , 0 , ancho, 1010 ) ;
9.
10. llenar ( 98 , 245 , 31 ) ; // color verde
11. // llama a las funciones para dibujar el radar
12. drawRadar ( ) ;
13. drawLine ( ) ;
14. drawObject ( ) ;
15. drawText ( ) ;
16. }
INGLES

1. void draw() {
2.
3. fill(98,245,31);
4. textFont(orcFont);
5. // simulating motion blur and slow fade of the moving line
6. noStroke();
7. fill(0,4);
8. rect(0, 0, width, 1010);
9.
10. fill(98,245,31); // green color
11. // calls the functions for drawing the radar
12. drawRadar();
13. drawLine();
14. drawObject();
15. drawText();
16. }

Aquí está la apariencia final del radar:

Aquí está el Código fuente de procesamiento completo del radar Arduino:

1. procesamiento de importación. serial . *; // importa la biblioteca para comunicación serial


2. importar java. awt . evento . KeyEvent ; // importa la biblioteca para leer los datos del puerto serie
3. importar java. io . IOException ;
4.
5. Serial myPort; // define el objeto en serie
6. // defubes variables
7. String angle = "" ;
8. String distance = "" ;
9. String data = "" ;
10. String noObject;
11. float pixsDistance;
12. int iAngle, iDistance;
13. int index1 = 0 ;
14. int index2 = 0 ;
15. PFont orcFont;
16.
17. void setup ( ) {
18.
19. tamaño ( 1920 , 1080 ) ;
20. suave ( ) ;
21. myPort = new Serial ( esto , "COM4" , 9600 ) ; // inicia la comunicación serial
22. myPort. bufferUntil ( '.' ) ; // lee los datos del puerto serie hasta el caracter '.'. Entonces realmente lee esto: ángulo, distancia.
23. orcFont = loadFont ( "OCRAExtended-30.vlw" ) ;
24. }
25.
26. void draw ( ) {
27.
28. llenar ( 98 , 245 , 31 ) ;
29. textFont ( orcFont ) ;
30. // simulando el desenfoque de movimiento y el desvanecimiento lento de la línea de movimiento
31. noStroke ( ) ;
32. llenar ( 0 , 4 ) ;
33. rect ( 0 , 0 , ancho, 1010 ) ;
34.
35. llenar ( 98 , 245 , 31 ) ; // color verde
36. // llama a las funciones para dibujar el radar
37. drawRadar ( ) ;
38. drawLine ( ) ;
39. drawObject ( ) ;
40. drawText ( ) ;
41. }
42.
43. void serialEvent ( Serial myPort ) { // comienza a leer datos del puerto serie
44. // lee los datos del puerto serie hasta el caracter '.' y lo pone en la variable "datos" de String.
45. data = myPort. readStringUntil ( '.' ) ;
46. datos = datos. subcadena ( 0 , data. length ( ) - 1 ) ;
47.
48. index1 = datos. indexOf ( "," ) ; // encuentra el caracter ',' y lo pone en la variable "index1"
49. ángulo = datos. subcadena ( 0 , índice1 ) ; // lee los datos de la posición "0" a la posición de la variable índice1 o el valor del
ángulo que la placa Arduino envió al puerto serie
50. distancia = datos. subcadena ( índice1 + 1 , datos, longitud ( ) ) ; // lee los datos de la posición "index1" al final de los datos pr ese
es el valor de la distancia
51.
52. // convierte las variables String en Entero
53. iAngle = int ( ángulo ) ;
54. iDistance = int ( distancia ) ;
55. }
56.
57. void drawRadar ( ) {
58. pushMatrix ( ) ;
59. traducir ( 960 , 1000 ) ; // mueve las coordinadas iniciales a la nueva ubicación
60. noFill ( ) ;
61. strokeWeight ( 2 ) ;
62. golpe ( 98 , 245 , 31 ) ;
63. // dibuja las líneas de arco
64. arco ( 0 , 0 , 1800 , 1800 , PI, TWO_PI ) ;
65. arco ( 0 , 0 , 1400 , 1400 , PI, TWO_PI ) ;
66. arco ( 0 , 0 , 1000 , 1000 , PI, TWO_PI ) ;
67. arco ( 0 , 0 , 600 , 600 , PI, TWO_PI ) ;
68. // dibuja las líneas de ángulo
69. línea ( - 960 , 0 , 960 , 0 ) ;
70. línea ( 0 , 0 , - 960 * cos ( radianes ( 30 ) ) , - 960 * sin ( radianes ( 30 ) ) ) ;
71. línea ( 0 , 0 , - 960 * cos ( radianes ( 60 ) ) , - 960 * sin ( radianes ( 60 ) ) ) ;
72. línea ( 0 , 0 , - 960 * cos ( radianes ( 90 ) ) , - 960 * sin ( radianes ( 90 ) ) ) ;
73. línea ( 0 , 0 , - 960 * cos ( radianes ( 120 ) ) , - 960 * sin ( radianes ( 120 ) ) ) ;
74. línea ( 0 , 0 , - 960 * cos ( radianes ( 150 ) ) , - 960 * sin ( radianes ( 150 ) ) ) ;
75. línea ( - 960 * cos ( radianes ( 30 ) ) , 0 , 960 , 0 ) ;
76. popMatrix ( ) ;
77. }
78.
79. void drawObject ( ) {
80. pushMatrix ( ) ;
81. traducir ( 960 , 1000 ) ; // mueve las coordinadas iniciales a la nueva ubicación
82. strokeWeight ( 9 ) ;
83. golpe ( 255 , 10 , 10 ) ; // color rojo
84. pixsDistance = iDistance * 22.5 ; // cubre la distancia desde el sensor de cm a píxeles
85. // limitando el rango a 40 cms
86. if ( iDistance < 40 ) {
87. // dibuja el objeto según el ángulo y la distancia
88. line ( pixsDistance * cos ( radianes ( iAngle ) ) , -pixsDistance * sin ( radianes ( iAngle ) ) , 950 * cos ( radianes ( iAngle ) ) , - 950
* sin ( radianes ( iAngle ) ) ) ;
89. }
90. popMatrix ( ) ;
91. }
92.
93. void drawLine ( ) {
94. pushMatrix ( ) ;
95. strokeWeight ( 9 ) ;
96. golpe ( 30 , 250 , 60 ) ;
97. traducir ( 960 , 1000 ) ; // mueve las coordinadas iniciales a la nueva ubicación
98. line ( 0 , 0 , 950 * cos ( radianes ( iAngle ) ) , - 950 * sen ( radianes ( iAngle ) ) ) ; // dibuja la línea según el ángulo
99. popMatrix ( ) ;
100. }
101.
102. void drawText ( ) { // dibuja los textos en la pantalla
103.
104. pushMatrix ( ) ;
105. if ( iDistance> 40 ) {
106. noObject = "Fuera de rango" ;
107. }
108. else {
109. noObject = "Dentro del rango" ;
110. }
111. llenar ( 0 , 0 , 0 ) ;
112. noStroke ( ) ;
113. rect ( 0 , 1010 , ancho, 1080 ) ;
114. llenar ( 98 , 245 , 31 ) ;
115. textSize ( 25 ) ;
116. texto ( "10cm" , 1180 , 990 ) ;
117. texto ( "20cm" , 1380 , 990 ) ;
118. texto ( "30cm" , 1580 , 990 ) ;
119. texto ( "40cm" , 1780 , 990 ) ;
120. textSize ( 40 ) ;
121. texto ( "Objeto:" + noObject, 240 , 1050 ) ;
122. texto ( "Ángulo:" + iAngle + "°" , 1050 , 1050 ) ;
123. texto ( "Distancia:" , 1380 , 1050 ) ;
124. if ( iDistance < 40 ) {
125. texto ( "" + iDistance + "cm" , 1400 , 1050 ) ;
126. }
127. textSize ( 25 ) ;
128. llenar ( 98 , 245 , 60 ) ;
129. traducir ( 961 + 960 * cos ( radianes ( 30 ) ) , 982 - 960 * sin ( radianes ( 30 ) ) ) ;
130. rotar ( - radianes ( - 60 ) ) ;
131. texto ( "30 °" , 0 , 0 ) ;
132. resetMatrix ( ) ;
133. traducir ( 954 + 960 * cos ( radianes ( 60 ) ) , 984 - 960 * sin ( radianes ( 60 ) ) ) ;
134. rotar ( - radianes ( - 30 ) ) ;
135. texto ( "60 °" , 0 , 0 ) ;
136. resetMatrix ( ) ;
137. traducir ( 945 + 960 * cos ( radianes ( 90 ) ) , 990 - 960 * sin ( radianes ( 90 ) ) ) ;
138. rotar ( radianes ( 0 ) ) ;
139. texto ( "90 °" , 0 , 0 ) ;
140. resetMatrix ( ) ;
141. traducir ( 935 + 960 * cos ( radianes ( 120 ) ) , 1003 - 960 * sin ( radianes ( 120 ) ) ) ;
142. rotar ( radianes ( - 30 ) ) ;
143. texto ( "120 °" , 0 , 0 ) ;
144. resetMatrix ( ) ;
145. traducir ( 940 + 960 * cos ( radianes ( 150 ) ) , 1018 - 960 * sin ( radianes ( 150 ) ) ) ;
146. rotar ( radianes ( - 60 ) ) ;
147. texto ( "150 °" , 0 , 0 ) ;
148. popMatrix ( ) ;
149. }

INGLES

1. import processing.serial.*; // imports library for serial communication


2. import java.awt.event.KeyEvent; // imports library for reading the data from the serial port
3. import java.io.IOException;
4.
5. Serial myPort; // defines Object Serial
6. // defubes variables
7. String angle="";
8. String distance="";
9. String data="";
10. String noObject;
11. float pixsDistance;
12. int iAngle, iDistance;
13. int index1=0;
14. int index2=0;
15. PFont orcFont;
16.
17. void setup() {
18.
19. size (1920, 1080);
20. smooth();
21. myPort = new Serial(this,"COM4", 9600); // starts the serial communication
22. myPort.bufferUntil('.'); // reads the data from the serial port up to the character '.'. So actually it reads this: angle,distance.
23. orcFont = loadFont("OCRAExtended-30.vlw");
24. }
25.
26. void draw() {
27.
28. fill(98,245,31);
29. textFont(orcFont);
30. // simulating motion blur and slow fade of the moving line
31. noStroke();
32. fill(0,4);
33. rect(0, 0, width, 1010);
34.
35. fill(98,245,31); // green color
36. // calls the functions for drawing the radar
37. drawRadar();
38. drawLine();
39. drawObject();
40. drawText();
41. }
42.
43. void serialEvent (Serial myPort) { // starts reading data from the Serial Port
44. // reads the data from the Serial Port up to the character '.' and puts it into the String variable "data".
45. data = myPort.readStringUntil('.');
46. data = data.substring(0,data.length()-1);
47.
48. index1 = data.indexOf(","); // find the character ',' and puts it into the variable "index1"
49. angle= data.substring(0, index1); // read the data from position "0" to position of the variable index1 or thats the value of the angle
the Arduino Board sent into the Serial Port
50. distance= data.substring(index1+1, data.length()); // read the data from position "index1" to the end of the data pr thats the value of
the distance
51.
52. // converts the String variables into Integer
53. iAngle = int(angle);
54. iDistance = int(distance);
55. }
56.
57. void drawRadar() {
58. pushMatrix();
59. translate(960,1000); // moves the starting coordinats to new location
60. noFill();
61. strokeWeight(2);
62. stroke(98,245,31);
63. // draws the arc lines
64. arc(0,0,1800,1800,PI,TWO_PI);
65. arc(0,0,1400,1400,PI,TWO_PI);
66. arc(0,0,1000,1000,PI,TWO_PI);
67. arc(0,0,600,600,PI,TWO_PI);
68. // draws the angle lines
69. line(-960,0,960,0);
70. line(0,0,-960*cos(radians(30)),-960*sin(radians(30)));
71. line(0,0,-960*cos(radians(60)),-960*sin(radians(60)));
72. line(0,0,-960*cos(radians(90)),-960*sin(radians(90)));
73. line(0,0,-960*cos(radians(120)),-960*sin(radians(120)));
74. line(0,0,-960*cos(radians(150)),-960*sin(radians(150)));
75. line(-960*cos(radians(30)),0,960,0);
76. popMatrix();
77. }
78.
79. void drawObject() {
80. pushMatrix();
81. translate(960,1000); // moves the starting coordinats to new location
82. strokeWeight(9);
83. stroke(255,10,10); // red color
84. pixsDistance = iDistance*22.5; // covers the distance from the sensor from cm to pixels
85. // limiting the range to 40 cms
86. if(iDistance<40){
87. // draws the object according to the angle and the distance
88. line(pixsDistance*cos(radians(iAngle)),-pixsDistance*sin(radians(iAngle)),950*cos(radians(iAngle)),-950*sin(radians(iAngle)));
89. }
90. popMatrix();
91. }
92.
93. void drawLine() {
94. pushMatrix();
95. strokeWeight(9);
96. stroke(30,250,60);
97. translate(960,1000); // moves the starting coordinats to new location
98. line(0,0,950*cos(radians(iAngle)),-950*sin(radians(iAngle))); // draws the line according to the angle
99. popMatrix();
100. }
101.
102. void drawText() { // draws the texts on the screen
103.
104. pushMatrix();
105. if(iDistance>40) {
106. noObject = "Out of Range";
107. }
108. else {
109. noObject = "In Range";
110. }
111. fill(0,0,0);
112. noStroke();
113. rect(0, 1010, width, 1080);
114. fill(98,245,31);
115. textSize(25);
116. text("10cm",1180,990);
117. text("20cm",1380,990);
118. text("30cm",1580,990);
119. text("40cm",1780,990);
120. textSize(40);
121. text("Object: " + noObject, 240, 1050);
122. text("Angle: " + iAngle +" °", 1050, 1050);
123. text("Distance: ", 1380, 1050);
124. if(iDistance<40) {
125. text(" " + iDistance +" cm", 1400, 1050);
126. }
127. textSize(25);
128. fill(98,245,60);
129. translate(961+960*cos(radians(30)),982-960*sin(radians(30)));
130. rotate(-radians(-60));
131. text("30°",0,0);
132. resetMatrix();
133. translate(954+960*cos(radians(60)),984-960*sin(radians(60)));
134. rotate(-radians(-30));
135. text("60°",0,0);
136. resetMatrix();
137. translate(945+960*cos(radians(90)),990-960*sin(radians(90)));
138. rotate(radians(0));
139. text("90°",0,0);
140. resetMatrix();
141. translate(935+960*cos(radians(120)),1003-960*sin(radians(120)));
142. rotate(radians(-30));
143. text("120°",0,0);
144. resetMatrix();
145. translate(940+960*cos(radians(150)),1018-960*sin(radians(150)));
146. rotate(radians(-60));
147. text("150°",0,0);
148. popMatrix();
149. }
Nueva versión actualizada del código para adaptarse a cualquier resolución de pantalla:

Simplemente cambie los valores en la función size (), con su resolución de pantalla.

1. / * Proyecto de Radar Arduino


2. *
3. * Versión actualizada. Se adapta a cualquier resolución de pantalla!
4. * Simplemente cambie los valores en la función size (),
5. * con su resolución de pantalla.
6. *
7. * por Dejan Nedelkovski,
8. * www.HowToMechatronics.com
9. *
10. */
11. procesamiento de importación. serial . *; // importa la biblioteca para comunicación serial
12. importar java. awt . evento . KeyEvent ; // importa la biblioteca para leer los datos del puerto serie
13. importar java. io . IOException ;
14.
15. Serial myPort; // define el objeto en serie
16. // defubes variables
17. String angle = "" ;
18. String distance = "" ;
19. String data = "" ;
20. String noObject;
21. float pixsDistance;
22. int iAngle, iDistance;
23. int index1 = 0 ;
24. int index2 = 0 ;
25. PFont orcFont;
26.
27. void setup ( ) {
28.
29. tamaño ( 1920 , 1080 ) ; // *** CAMBIE ESTO A SU PANTALLA RESOLUCIÓN ***
30. suave ( ) ;
31. myPort = new Serial ( esto , "COM4" , 9600 ) ; // inicia la comunicación serial
32. myPort. bufferUntil ( '.' ) ; // lee los datos del puerto serie hasta el caracter '.'. Entonces realmente lee esto: ángulo, distancia.
33. orcFont = loadFont ( "OCRAExtended-30.vlw" ) ;
34. }
35.
36. void draw ( ) {
37.
38. llenar ( 98 , 245 , 31 ) ;
39. textFont ( orcFont ) ;
40. // simulando el desenfoque de movimiento y el desvanecimiento lento de la línea de movimiento
41. noStroke ( ) ;
42. llenar ( 0 , 4 ) ;
43. rect ( 0 , 0 , ancho, altura-alto * 0.065 ) ;
44.
45. llenar ( 98 , 245 , 31 ) ; // color verde
46. // llama a las funciones para dibujar el radar
47. drawRadar ( ) ;
48. drawLine ( ) ;
49. drawObject ( ) ;
50. drawText ( ) ;
51. }
52.
53. void serialEvent ( Serial myPort ) { // comienza a leer datos del puerto serie
54. // lee los datos del puerto serie hasta el caracter '.' y lo pone en la variable "datos" de String.
55. data = myPort. readStringUntil ( '.' ) ;
56. datos = datos. subcadena ( 0 , data. length ( ) - 1 ) ;
57.
58. index1 = datos. indexOf ( "," ) ; // encuentra el caracter ',' y lo pone en la variable "index1"
59. ángulo = datos. subcadena ( 0 , índice1 ) ; // lee los datos de la posición "0" a la posición de la variable índice1 o el valor del
ángulo que la placa Arduino envió al puerto serie
60. distancia = datos. subcadena ( índice1 + 1 , datos, longitud ( ) ) ; // lee los datos de la posición "index1" al final de los datos pr ese
es el valor de la distancia
61.
62. // convierte las variables String en Entero
63. iAngle = int ( ángulo ) ;
64. iDistance = int ( distancia ) ;
65. }
66.
67. void drawRadar ( ) {
68. pushMatrix ( ) ;
69. traducir ( anchura / 2 , la altura de la altura * 0 . 074 ) ; // mueve las coordinadas iniciales a la nueva ubicación
70. noFill ( ) ;
71. strokeWeight ( 2 ) ;
72. golpe ( 98 , 245 , 31 ) ;
73. // dibuja las líneas de arco
74. arco ( 0 , 0 , ( ancho-ancho * 0.0625 ) , ( ancho-ancho * 0.0625 ) , PI, TWO_PI ) ;
75. arco ( 0 , 0 , ( ancho-ancho * 0.27 ) , ( ancho-ancho * 0.27 ) , PI, TWO_PI ) ;
76. arco ( 0 , 0 , ( ancho-width * 0,479 ) , ( ancho-width * 0 . 479 ) , PI, TWO_PI ) ;
77. arco ( 0 , 0 , ( ancho-ancho * 0 687 ) , ( ancho-ancho * 0 687 ) , PI, TWO_PI ) ;
78. // dibuja las líneas de ángulo
79. línea ( -width / 2 , 0 , width / 2 , 0 ) ;
80. line ( 0 , 0 , ( -width / 2 ) * cos ( radianes ( 30 ) ) , ( -width / 2 ) * sin ( radianes ( 30 ) ) ) ;
81. line ( 0 , 0 , ( -width / 2 ) * cos ( radianes ( 60 ) ) , ( -width / 2 ) * sin ( radianes ( 60 ) ) ) ;
82. line ( 0 , 0 , ( -width / 2 ) * cos ( radianes ( 90 ) ) , ( -width / 2 ) * sin ( radianes ( 90 ) ) ) ;
83. line ( 0 , 0 , ( -width / 2 ) * cos ( radianes ( 120 ) ) , ( -width / 2 ) * sin ( radianes ( 120 ) ) ) ;
84. line ( 0 , 0 , ( -width / 2 ) * cos ( radianes ( 150 ) ) , ( -width / 2 ) * sin ( radianes ( 150 ) ) ) ;
85. line ( ( -width / 2 ) * cos ( radianes ( 30 ) ) , 0 , width / 2 , 0 ) ;
86. popMatrix ( ) ;
87. }
88.
89. void drawObject ( ) {
90. pushMatrix ( ) ;
91. traducir ( ancho / 2 , alto de altura * 0.074 ) ; // mueve las coordinadas iniciales a la nueva ubicación
92. strokeWeight ( 9 ) ;
93. golpe ( 255 , 10 , 10 ) ; // color rojo
94. pixsDistance = iDistance * ( ( altura-altura * 0.1666 ) * 0 .025 ) ; // cubre la distancia desde el sensor de cm a píxeles
95. // limitando el rango a 40 cms
96. if ( iDistance < 40 ) {
97. // dibuja el objeto según el ángulo y la distancia
98. línea ( pixsDistance * cos ( radianes ( iAngle ) ) , -pixsDistance * sen ( radianes ( iAngle ) ) , ( ancho-width * 0 0,505 ) * cos (
radianes ( iAngle ) ) , - ( ancho-width * 0 . 505 ) * sin ( radianes ( iAngle ) ) ) ;
99. }
100. popMatrix ( ) ;
101. }
102.
103. void drawLine ( ) {
104. pushMatrix ( ) ;
105. strokeWeight ( 9 ) ;
106. golpe ( 30 , 250 , 60 ) ;
107. traducir ( anchura / 2 , la altura de la altura * 0 . 074 ) ; // mueve las coordinadas iniciales a la nueva ubicación
108. línea ( 0 , 0 , ( altura-altura * 0.12 ) * cos ( radianes ( iAngle ) ) , - ( altura-altura * 0 .12 ) * sin ( radianes ( iAngle ) ) ) ; // dibuja
la línea según el ángulo
109. popMatrix ( ) ;
110. }
111.
112. void drawText ( ) { // dibuja los textos en la pantalla
113.
114. pushMatrix ( ) ;
115. if ( iDistance> 40 ) {
116. noObject = "Fuera de rango" ;
117. }
118. else {
119. noObject = "Dentro del rango" ;
120. }
121. llenar ( 0 , 0 , 0 ) ;
122. noStroke ( ) ;
123. rect ( 0 , altura-altura * 0.0648 , ancho, alto ) ;
124. llenar ( 98 , 245 , 31 ) ;
125. textSize ( 25 ) ;
126.
127. texto ( "10cm" , ancho-ancho * 0. 3854 , alto-alto * 0.0833 ) ;
128. texto ( "20cm" , ancho-ancho * 0 .281 , altura-alto * 0. 0833 ) ;
129. texto ( "30cm" , ancho-ancho * 0.177 , altura-alto * 0. 0833 ) ;
130. texto ( "40cm" , ancho-width * 0.0729 , la altura de la altura * 0 . 0833 ) ;
131. textSize ( 40 ) ;
132. texto ( "Objeto:" + noObjeto, ancho-ancho * 0.875 , alto-alto * 0.0277 ) ;
133. texto ( "Ángulo:" + iAngulo + "°" , ancho-ancho * 0. 48 , altura-altura * 0.0277 ) ;
134. texto ( "Distancia:" , ancho-ancho * 0.26 , altura-altura * 0. 0277 ) ;
135. if ( iDistance < 40 ) {
136. texto ( "" + iDistance + "cm" , ancho-width * 0 . 225 , la altura de la altura * 0. 0277 ) ;
137. }
138. textSize ( 25 ) ;
139. llenar ( 98 , 245 , 60 ) ;
140. traducir ( ( ancho-ancho * 0 .4994 ) + ancho / 2 * cos ( radianes ( 30 ) ) , ( altura-altura * 0 .0907 ) -ancho / 2 * sin ( radianes ( 30
)));
141. rotar ( - radianes ( - 60 ) ) ;
142. texto ( "30 °" , 0 , 0 ) ;
143. resetMatrix ( ) ;
144. translate ( ( ancho-ancho * 0. 503 ) + ancho / 2 * cos ( radianes ( 60 ) ) , ( altura-altura * 0. 0888 ) -ancho / 2 * sin ( radianes ( 60
)));
145. rotar ( - radianes ( - 30 ) ) ;
146. texto ( "60 °" , 0 , 0 ) ;
147. resetMatrix ( ) ;
148. traducir ( ( anchura-width * 0 0,507 ) + anchura / 2 * cos ( radianes ( 90 ) ) , ( altura de la altura * 0 . 0833 ) -width / 2 * sen (
radianes ( 90 ) ) ) ;
149. rotar ( radianes ( 0 ) ) ;
150. texto ( "90 °" , 0 , 0 ) ;
151. resetMatrix ( ) ;
152. traducir ( ancho-width * 0,513 + ancho / 2 * cos ( radianes ( 120 ) ) , ( altura de la altura * 0 . 07129 ) -width / 2 * sen ( radianes (
120 ) ) ) ;
153. rotar ( radianes ( - 30 ) ) ;
154. texto ( "120 °" , 0 , 0 ) ;
155. resetMatrix ( ) ;
156. traducir ( ( anchura-width * 0 . 5104 ) + anchura / 2 * cos ( radianes ( 150 ) ) , ( altura de la altura * 0. 0574 ) -width / 2 * sen (
radianes ( 150 ) ) ) ;
157. rotar ( radianes ( - 60 ) ) ;
158. texto ( "150 °" , 0 , 0 ) ;
159. popMatrix ( ) ;
160. }
INGLES

1. /* Arduino Radar Project


2. *
3. * Updated version. Fits any screen resolution!
4. * Just change the values in the size() function,
5. * with your screen resolution.
6. *
7. * by Dejan Nedelkovski,
8. * www.HowToMechatronics.com
9. *
10. */
11.
12. import processing.serial.*; // imports library for serial communication
13. import java.awt.event.KeyEvent; // imports library for reading the data from the serial port
14. import java.io.IOException;
15.
16. Serial myPort; // defines Object Serial
17. // defubes variables
18. String angle="";
19. String distance="";
20. String data="";
21. String noObject;
22. float pixsDistance;
23. int iAngle, iDistance;
24. int index1=0;
25. int index2=0;
26. PFont orcFont;
27.
28. void setup() {
29.
30. size (1920, 1080); // ***CHANGE THIS TO YOUR SCREEN RESOLUTION***
31. smooth();
32. myPort = new Serial(this,"COM4", 9600); // starts the serial communication
33. myPort.bufferUntil('.'); // reads the data from the serial port up to the character '.'. So actually it reads this: angle,distance.
34. orcFont = loadFont("OCRAExtended-30.vlw");
35. }
36.
37. void draw() {
38.
39. fill(98,245,31);
40. textFont(orcFont);
41. // simulating motion blur and slow fade of the moving line
42. noStroke();
43. fill(0,4);
44. rect(0, 0, width, height-height*0.065);
45.
46. fill(98,245,31); // green color
47. // calls the functions for drawing the radar
48. drawRadar();
49. drawLine();
50. drawObject();
51. drawText();
52. }
53.
54. void serialEvent (Serial myPort) { // starts reading data from the Serial Port
55. // reads the data from the Serial Port up to the character '.' and puts it into the String variable "data".
56. data = myPort.readStringUntil('.');
57. data = data.substring(0,data.length()-1);
58.
59. index1 = data.indexOf(","); // find the character ',' and puts it into the variable "index1"
60. angle= data.substring(0, index1); // read the data from position "0" to position of the variable index1 or thats the value of the angle
the Arduino Board sent into the Serial Port
61. distance= data.substring(index1+1, data.length()); // read the data from position "index1" to the end of the data pr thats the value of
the distance
62.
63. // converts the String variables into Integer
64. iAngle = int(angle);
65. iDistance = int(distance);
66. }
67.
68. void drawRadar() {
69. pushMatrix();
70. translate(width/2,height-height*0.074); // moves the starting coordinats to new location
71. noFill();
72. strokeWeight(2);
73. stroke(98,245,31);
74. // draws the arc lines
75. arc(0,0,(width-width*0.0625),(width-width*0.0625),PI,TWO_PI);
76. arc(0,0,(width-width*0.27),(width-width*0.27),PI,TWO_PI);
77. arc(0,0,(width-width*0.479),(width-width*0.479),PI,TWO_PI);
78. arc(0,0,(width-width*0.687),(width-width*0.687),PI,TWO_PI);
79. // draws the angle lines
80. line(-width/2,0,width/2,0);
81. line(0,0,(-width/2)*cos(radians(30)),(-width/2)*sin(radians(30)));
82. line(0,0,(-width/2)*cos(radians(60)),(-width/2)*sin(radians(60)));
83. line(0,0,(-width/2)*cos(radians(90)),(-width/2)*sin(radians(90)));
84. line(0,0,(-width/2)*cos(radians(120)),(-width/2)*sin(radians(120)));
85. line(0,0,(-width/2)*cos(radians(150)),(-width/2)*sin(radians(150)));
86. line((-width/2)*cos(radians(30)),0,width/2,0);
87. popMatrix();
88. }
89.
90. void drawObject() {
91. pushMatrix();
92. translate(width/2,height-height*0.074); // moves the starting coordinats to new location
93. strokeWeight(9);
94. stroke(255,10,10); // red color
95. pixsDistance = iDistance*((height-height*0.1666)*0.025); // covers the distance from the sensor from cm to pixels
96. // limiting the range to 40 cms
97. if(iDistance<40){
98. // draws the object according to the angle and the distance
99. line(pixsDistance*cos(radians(iAngle)),-pixsDistance*sin(radians(iAngle)),(width-width*0.505)*cos(radians(iAngle)),-(width-
width*0.505)*sin(radians(iAngle)));
100. }
101. popMatrix();
102. }
103.
104. void drawLine() {
105. pushMatrix();
106. strokeWeight(9);
107. stroke(30,250,60);
108. translate(width/2,height-height*0.074); // moves the starting coordinats to new location
109. line(0,0,(height-height*0.12)*cos(radians(iAngle)),-(height-height*0.12)*sin(radians(iAngle))); // draws the line according to the
angle
110. popMatrix();
111. }
112.
113. void drawText() { // draws the texts on the screen
114.
115. pushMatrix();
116. if(iDistance>40) {
117. noObject = "Out of Range";
118. }
119. else {
120. noObject = "In Range";
121. }
122. fill(0,0,0);
123. noStroke();
124. rect(0, height-height*0.0648, width, height);
125. fill(98,245,31);
126. textSize(25);
127.
128. text("10cm",width-width*0.3854,height-height*0.0833);
129. text("20cm",width-width*0.281,height-height*0.0833);
130. text("30cm",width-width*0.177,height-height*0.0833);
131. text("40cm",width-width*0.0729,height-height*0.0833);
132. textSize(40);
133. text("Object: " + noObject, width-width*0.875, height-height*0.0277);
134. text("Angle: " + iAngle +" °", width-width*0.48, height-height*0.0277);
135. text("Distance: ", width-width*0.26, height-height*0.0277);
136. if(iDistance<40) {
137. text(" " + iDistance +" cm", width-width*0.225, height-height*0.0277);
138. }
139. textSize(25);
140. fill(98,245,60);
141. translate((width-width*0.4994)+width/2*cos(radians(30)),(height-height*0.0907)-width/2*sin(radians(30)));
142. rotate(-radians(-60));
143. text("30°",0,0);
144. resetMatrix();
145. translate((width-width*0.503)+width/2*cos(radians(60)),(height-height*0.0888)-width/2*sin(radians(60)));
146. rotate(-radians(-30));
147. text("60°",0,0);
148. resetMatrix();
149. translate((width-width*0.507)+width/2*cos(radians(90)),(height-height*0.0833)-width/2*sin(radians(90)));
150. rotate(radians(0));
151. text("90°",0,0);
152. resetMatrix();
153. translate(width-width*0.513+width/2*cos(radians(120)),(height-height*0.07129)-width/2*sin(radians(120)));
154. rotate(radians(-30));
155. text("120°",0,0);
156. resetMatrix();
157. translate((width-width*0.5104)+width/2*cos(radians(150)),(height-height*0.0574)-width/2*sin(radians(150)));
158. rotate(radians(-60));
159. text("150°",0,0);
160. popMatrix();
161. }

Anda mungkin juga menyukai