comenzando desde cero (Starting from scratch)

What are you working on .... Show off your Rov's Projects here.
asesorplaza1
Posts: 187
Joined: Mar 4th, 2018, 6:11 pm
Location: Valverde de Júcar, Cuenca, España

Re: comenzando desde cero (Starting from scratch)

Post by asesorplaza1 »

Un compañero de otro foro me ha dicho todo esto.

Hola asesorplaza1.
Finalmente he podido descomprimir los códigos fuente en Windows y los he revisado.
En mi opinión, no hay una sola forma buena de programar, de hecho cada persona tiene un estilo propio que no tiene que ser ni mejor ni peor. Por lo que intentaré explicar cómo haría yo aquellas cosa que me llamen la atención. El código es bastante legible y veo que has seguido el estilo que recomienda Arduino así que es un buen punto de partida.

Una de las cosas que he visto y que por lo que comentas en post anteriores no te funciona bien es la comunicación.
Voy a dar un poco de contexto:
El bucle loop() se está ejecutando continuamente una vez arrancado el micro controlador, empieza por la primera línea y va realizando las tareas que le manda el código que hemos escrito hasta llegar al final y comienza de nuevo. Dependiendo del tamaño del código y de la velocidad del micro controlador esto se repite miles de veces por segundo.
La función delay() interrumpe la ejecución del código por un determinado periodo de tiempo (es como si le damos al pause).
La función while() Interrumpe la ejecución del código hasta que se cumple la condición que hemos puesto entre paréntesis (otro pause).
Los puertos serial tienen un buffer donde se van acumulando los datos que reciben, si la cantidad de datos es mayor que el tamaño del buffer se bloquean.

Este es el código relevante dentro de loop():
Maestro
474 ETout.sendData();
476 delay (200);
// Recibe el mensaje al puerto serie para el Arduino del ROV
479 while (!ETin.receiveData());
619 delay (1000);

Esclavo
334 while (!ETin.receiveData());
711 ETout.sendData // Esta dentro de la función loop_SKU237545_E()
460 delay(200);

La secuencia del código seria:
El maestro envía un mensaje (L 474). Se queda en pause 200ms (L 476). Pause hasta recibir datos del esclavo y pause de 1000ms. El loop() se ejecuta completo una vez cada 1.2 segundos y algunas milésimas.
El esclavo esta en pause hasta que recibe un mensaje (L334). Envía un mensaje y se queda en pause 200ms (L 460). Como el maestro envía un mensaje cada 1.2s, el loop() del esclavo se ejecuta completo cada 1.4s mas algunas milésimas.
Como resultado tanto el esclavo como el maestro están en pause el 99.99% del tiempo.

Yo utilizaría la función millis() en vez de delay() para aquellas partes del código que quiero que se ejecuten cada cierto tiempo y no bloquear la ejecución del resto del código.

También sustituiría
while (!ETin.receiveData()); por if(ETin.receiveData()) { código para procesar el mensaje ; }
De esta forma el código solo se ejecuta cuando hay un mensaje y se comprueba si hay menaje cada pocos milisegundos de forma que evitamos que el buffer se llene.

Tsanshon
A demás de que me lea un libro de programación en C++, que ya lo estoy haciendo.

¿Qué te parece?

Un saludo



A colleague from another forum has told me all this.

Hello advisorplaza1.
I've finally been able to unzip the source codes in Windows and reviewed them.
In my opinion, there is not a single good way to program, in fact every person has a style of their own that doesn't have to be better or worse. So I'll try to explain how I'd do those things that catch my eye. The code is quite readable and I see that you have followed the style recommended by Arduino so it is a good starting point.

One of the things I've seen and that from what you review in previous posts doesn't work well for you is communication.
I'm going to give you some context:
The loop() is running continuously once the micro controller is booted, starts with the first line and goes performing the tasks that the code that we have written until we reach the end and starts again. Depending on the size of the code and the speed of the micro controller this is repeated thousands of times per second.
The delay() function interrupts code execution for a certain period of time (it is as if we give the pause).
The while() function interrupts code execution until the condition we have put in parentheses (another pause) is met.
Serial ports have a buffer where the data they receive accumulates, if the amount of data is greater than the buffer size is blocked.

This is the relevant code within loop():
Master
474 ETout.sendData();
476 delay (200);
Receives message to serial port for ROV Arduino
479 while (! ETin.receiveData());
619 delay (1000);

Slave
334 while (! ETin.receiveData());
711 ETout.sendData // Inside the loop_SKU237545_E()
460 delay(200);

The sequence of the code would be:
The teacher sends a message (L 474). Stays in pause 200ms (L 476). Pause until you receive slave data and pause 1000ms. The loop() runs complete once every 1.2 seconds and a few thousandths.
The slave is paused until it receives a message (L334). Sends a message and stays in pause 200ms (L 460). As the master sends a message every 1.2s, the slave loop() runs full every 1.4s plus a few thousandths.
As a result both the slave and the master are paused 99.99% of the time.

I would use the millis() function instead of delay() for those parts of the code that I want to run from time to time and not block the execution of the rest of the code.

It would also replace
while (! ETin.receiveData()); by if(ETin.receiveData()) - code to process the message ;
This way the code only runs when there is a message and checks for utensils every few milliseconds so that we prevent the buffer from filling up.

Tsanshon
Other than reading a programming book in C++, I'm already doing it

What do you think?

A greeting
User avatar
bigbadbob
Posts: 272
Joined: Nov 28th, 2011, 10:24 am

Re: comenzando desde cero (Starting from scratch)

Post by bigbadbob »

Hi AS1.
In many ways your colleague is right but...

1:a long time ago you reduced the delay(1000) to delay(200) so it is now much quicker.
1000 was too long and would have stopped your PS2 controller from working but 200 is ok.
you could try reducing 200 to 100 but I don't think it will make any difference.

2:I use the same delays and while() in my code without problems.
the delays are necessary to allow the data to be transmitted before you try to receive data.
it is a half duplex system and needs time to transmit and receive.
The slave code needs to receive data before it can act on it so the while() is good.

I will have a look at your debug serial output and see if I can find the problem with the ps2x.
it is good that you are seeing the sensor data, it means everything else is working and the buffer is not over full.

also we have moved "711 ETout.sendData // Inside the loop_SKU237545_E()" outside of that loop a long time ago. your colleague is looking at old code that we have since tidied up.
the code I sent you is more tidy and logical than the one he is reading.
asesorplaza1
Posts: 187
Joined: Mar 4th, 2018, 6:11 pm
Location: Valverde de Júcar, Cuenca, España

Re: comenzando desde cero (Starting from scratch)

Post by asesorplaza1 »

Buenos días.

Creo que como no trabaja con Windows, se ha perdido varias versiones arregladas del código, y eso mismo he pensado yo, que hemos arreglado bastante el código en los últimos días.

Aunque aun no hemos encontrado aun la solución definitiva al mando, pero el programa funciona mejor que al principio.

Y lo de cambiar

while (! ETin.receiveData ()); por if (ETin.receiveData ()) {código para procesar el mensaje; }

que te parece?

Un saludo.


Good morning.

I think because it doesn't work with Windows, it's lost several fixed versions of the code, and that's what I thought, that we've fixed the code a lot in the last few days.

Although we haven't yet found the ultimate solution to command, but the program works better than at first.

And the change

while (! ETin.receiveData ()); by if (ETin.receiveData()) {code to process the message; }

What do you think?.

Greetings.
User avatar
bigbadbob
Posts: 272
Joined: Nov 28th, 2011, 10:24 am

Re: comenzando desde cero (Starting from scratch)

Post by bigbadbob »

Ok.... here is my serial display with debug on.

Code: Select all

OUT:IN Configure
1:FF 43:41 0:5A 1:FF 0:FF 
OUT:IN Configure
1:FF 44:F1 0:5A 1:0 3:0 0:0 0:0 0:0 0:0 
OUT:IN Configure
1:FF 43:F3 0:5A 0:0 5A:0 5A:0 5A:0 5A:0 5A:0 
OUT:IN
1:FF 42:73 0:5A 0:FF 0:FF 0:80 0:80 0:80 0:80 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 
OUT:IN
1:FF 42:73 0:5A 0:FF 0:FF 0:80 0:80 0:80 0:80 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 
OUT:IN
1:FF 42:73 0:5A 0:FF 0:FF 0:80 0:80 0:80 0:80 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 
OUT:IN
1:FF 42:73 0:5A 0:FF 0:FF 0:80 0:80 0:80 0:80 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 
OUT:IN
1:FF 42:73 0:5A 0:FF 0:FF 0:80 0:80 0:80 0:80 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 
OUT:IN
1:FF 42:73 0:5A 0:FF 0:FF 0:80 0:80 0:80 0:80 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 
OUT:IN
1:FF 42:73 0:5A 0:FF 0:FF 0:80 0:80 0:80 0:80 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 
OUT:IN
1:FF 42:73 0:5A 0:FF 0:FF 0:80 0:80 0:80 0:80 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 
you have some different values in yours, i think your 79 is ok but the later values maybe not.
it will depend on whether you have-
error = ps2x.config_gamepad(13,11,10,12, false, false);
or
error = ps2x.config_gamepad(13,11,10,12, true, true);

did you use the master code I sent you when you did the debug? if not, please do.

my other thought is that there is may be a conflict between interrupts.
maybe you cannot use two com ports and the SPI port at the same time. :idea:
I will modify the code I sent you to remove all the serial1 stuff and just leave the txdata and a few messages on serial.

try this one I have attached, it will not control your rov but it will send messages to your serial monitor if you press the up pad or turn the lights on/off. use it with debug enabled in ps2x_lib.h.
Attachments
01_Maestro_09_05_2020_Arreglando_Codigo_BBB_noSerial.zip
(7.94 KiB) Downloaded 347 times
asesorplaza1
Posts: 187
Joined: Mar 4th, 2018, 6:11 pm
Location: Valverde de Júcar, Cuenca, España

Re: comenzando desde cero (Starting from scratch)

Post by asesorplaza1 »

Buenos días.

Muchas gracias por el tiempo que usted le esta dedicando a solucionar mi problema.

He cargado su programa, y cada vez que pulso un botón, y lo suelto, independientemente de cual sea en el Monitor Serie aparece lo siguiente:


Good morning.

Thank you very much for the time you are taking to fix my problem.

I've loaded your program, and every time I press a button, and I release it, regardless of which one on the Serial Monitor the following appears:

Code: Select all

Focos apagadosOUT:IN
1:FF 42:73 0:5A 0:FF 0:FF 0:7B 0:84 0:84 0:7B 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 

 Focos encendidosOUT:IN
1:FF 42:73 0:5A 0:FF 0:FF 0:7B 0:84 0:84 0:7B 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 
OUT:IN
1:FF 42:73 0:5A 0:7F 0:FF 0:7B 0:84 0:84 0:7B 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 

 Focos apagadosOUT:IN
1:FF 42:73 0:5A 0:FF 0:FF 0:7B 0:84 0:84 0:7B 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 

 Focos encendidosOUT:IN
1:FF 42:73 0:5A 0:FF 0:FF 0:7B 0:84 0:84 0:7B 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 
OUT:IN
1:FF 42:73 0:5A 0:7F 0:FF 0:7B 0:84 0:84 0:7B 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 

 Focos apagadosOUT:IN
1:FF 42:73 0:5A 0:FF 0:FF 0:7B 0:84 0:84 0:7B 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 

 Focos encendidosOUT:IN
1:FF 42:73 0:5A 0:FF 0:FF 0:7B 0:84 0:84 0:7B 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 
OUT:IN
1:FF 42:73 0:5A 0:7F 0:FF 
Lo cual quiere decir, que el mando de la PS2 funciona correctamente, y lo que da errores en el programa, como usted bien sospechaba, es la comunicación, y algunas interrupciones.


Which means that the PS2 controller works properly, and what gives errors in the program, as you well suspected, is communication, and some interruptions.

Y entonces, ¿Cual puede ser la solución?, Eliminar el puerto Serie1, y entonces, como comunico los Arduinos, usando por ejemplo los pines 0 RX, y 1 TX, en vez de usar los pines 18 y 19. Muchas gracias, un saludo.

And then, what can be the solution?, Delete the serial1 port, and then, as I communicate the Arduinos, using for example the pins 0 RX, and 1 TX, instead of using pins 18 and 19. Thank you very much, a greeting.
asesorplaza1
Posts: 187
Joined: Mar 4th, 2018, 6:11 pm
Location: Valverde de Júcar, Cuenca, España

Re: comenzando desde cero (Starting from scratch)

Post by asesorplaza1 »

Ya estoy viendo, que hasta que no tenga el modulo RS485, no se va solucionar el problema de la transmisión de datos entre los Arduinos.

I'm already seeing, that until I have the RS485 module, the problem of data transmission between Arduinos is not going to be solved.

https://proyectoarduino.com/comunicaciones-con-rs485/
asesorplaza1
Posts: 187
Joined: Mar 4th, 2018, 6:11 pm
Location: Valverde de Júcar, Cuenca, España

Re: comenzando desde cero (Starting from scratch)

Post by asesorplaza1 »

Buenas tardes.

Acabo de descubrir un error, en el programa Esclavo, en el que no habíamos caído ninguno de los dos, resulta que al pulsar el botón del mando de la izquierda, esperábamos que se encendieran los focos, pero faltaba lo mas importante, la orden de poner en alto el pin 32, que es el que controla los focos, ahora lo hace bien.

Así estaba antes.

Code: Select all

void loop_Luces() { // Bloque de trabajo de los focos
  digitalWrite(HeadLts, rxdata.LEDHdlts);
  // Enciende los faros en función del retraso de los datos del mensaje
  if (rxdata.LEDHdlts > 0) {
    Serial.print (F(" \n Focos apagados "));
  }
  else {
    (rxdata.LEDHdlts < 0);
    Serial.print (F(" \n Focos encendidos "));
  }
}
Así esta ahora.


void loop_Luces() { // Bloque de trabajo de los focos
digitalWrite(HeadLts, rxdata.LEDHdlts);
// Enciende los faros en función del retraso de los datos del mensaje
if (rxdata.LEDHdlts > 0) {
digitalWrite(HeadLts, LOW); // ***
Serial.print (F(" \n Focos apagados "));
}
else {
(rxdata.LEDHdlts < 0);
digitalWrite(HeadLts, HIGH); // ***
Serial.print (F(" \n Focos encendidos "));
}
}


Good afternoon.

I just discovered an error, in the Slave program, in which neither of us had fallen, it turns out that when we pressed the button on the left, we expected the spotlights to turn on, but the order to put the pin 32, which controls the spotlights, was missing, now it does well.

That's how it was before.

Code: Select all

void loop_Luces() { // Bloque de trabajo de los focos
  digitalWrite(HeadLts, rxdata.LEDHdlts);
  // Enciende los faros en función del retraso de los datos del mensaje
  if (rxdata.LEDHdlts > 0) {
    Serial.print (F(" \n Focos apagados "));
  }
  else {
    (rxdata.LEDHdlts < 0);
    Serial.print (F(" \n Focos encendidos "));
  }
}
That's how it is now.

void loop_Luces() { // Bloque de trabajo de los focos
digitalWrite(HeadLts, rxdata.LEDHdlts);
// Enciende los faros en función del retraso de los datos del mensaje
if (rxdata.LEDHdlts > 0) {
digitalWrite(HeadLts, LOW); // ***
Serial.print (F(" \n Focos apagados "));
}
else {
(rxdata.LEDHdlts < 0);
digitalWrite(HeadLts, HIGH); // ***
Serial.print (F(" \n Focos encendidos "));
}
}



Y así trabajan mejor los focos.

Un saludo.



And that's how the spotlights work better.

Greetings.
Attachments
48_10_05_2020.rar
(16.52 KiB) Downloaded 313 times
Last edited by asesorplaza1 on May 10th, 2020, 1:56 pm, edited 1 time in total.
asesorplaza1
Posts: 187
Joined: Mar 4th, 2018, 6:11 pm
Location: Valverde de Júcar, Cuenca, España

Re: comenzando desde cero (Starting from scratch)

Post by asesorplaza1 »

Pero eso no quita que haya un problema en la comunicación, porque aun así, tardan mucho de encenderse o apagarse, los focos.
Y ese problema no lo tenemos con el LED amarillo, que sigue sin encenderse, cuando pulso algún botón.

But that doesn't take away from a communication problem, because they still take a long time to turn the spotlights on or off.
And that problem we don't have with the yellow LED, which still doesn't turn on, when I press a button.
User avatar
bigbadbob
Posts: 272
Joined: Nov 28th, 2011, 10:24 am

Re: comenzando desde cero (Starting from scratch)

Post by bigbadbob »

Yipee. :D

ok...this code should sort out your yellow pin. it was working before but was on and off again so fast that you didn't see it. :lol:
note that I have used "ps2x.buttonPressed" and "PSB_PAD_UPstate = (!PSB_PAD_UPstate);" etc so press the button once and the led should come on press it again and it should go off.

In my system I use the master to send commands to the ROV and another microprocessor to receive sensor data from the rov and display it on the video screen. so I am not using two serial ports as well as the ps2 spi bus on the master.
you could split your master code between two arduino's one to transmit and one to receive/display serial.
I thought that the mega could handle all the interrupts at once but obviously not. I do not have a mega to try it with, I only have nano's.
Good luck.
Attachments
01_Maestro_10_05_2020_Arreglando_Codigo_BBB.zip
(7.87 KiB) Downloaded 312 times
asesorplaza1
Posts: 187
Joined: Mar 4th, 2018, 6:11 pm
Location: Valverde de Júcar, Cuenca, España

Re: comenzando desde cero (Starting from scratch)

Post by asesorplaza1 »

Buenas noches.

Lo primero que tengo que hacer, es darle las gracias por el tiempo que está dedicando a solucionar los problemas de mi proyecto, usted casi ha escrito ya tantas líneas de código como yo.

He realizado los cambios que usted me envió en su código, y lamento tener que decirle que no hemos avanzado nada por desgracia.

El mando sigue sin hacer caso de las órdenes, lo único que hace es encender y apagar los focos con mucha dificultad, tarda mucho tiempo, ocho segundos de reloj, con el botón pulsado, cuando debería ser casi inmediato, y el LED sigue sin encenderse.

Sin embargo, con su programa Maestro, en el Monitor Serie, si que puedo ver casi inmediatamente la frase de botón pulsado, pero los periféricos no reaccionan, ni los LEDs, ni los motores, ni el servo.

Vamos a tener que esperar a ver si me llegan los RS485, que ya no tienen que tardar mucho, y podemos mejorar los problemas de comunicación entre los Arduinos.

Ya hemos visto que el mando solo si funciona, pero en cuanto el Arduino tiene que gestionar el envió y recepción de datos, a demás del mando, no funciona nada como debería.

Todos los programas que he visto de la Comunicación Serie, por cable, sin RS485, se limitan a encender un LED y poco más, no he visto en ningún programa que el Esclavo gestione más de dos sensores y un LED a la vez, y el Maestro solo recibe los datos y los muestra en un LCD.

No hay ningún programa tan complicado como este.

Ya he encontrado una página de Internet que nos puede servir de guía, para la transformación hacia la comunicación con los RS485, pongo el enlace, para ir estudiando la adaptación del código al uso del SR485.

https://proyectoarduino.com/comunicaciones-con-rs485/

Creo que la mejor manera de conseguir una comunicación mucho mejor sería la que describe como opción tres, la que llama Comunicaciones con RS485 en modo Full-Duplex, para una comunicación bidireccional fluida, creo que si no lo hacemos así, vamos a estar dando vueltas sin conseguir nada que nos mejore la situación actual.

Mientras podemos seguir depurando y mejorando el código, o puedo dedicarme a seguir montando el casco y poniendo fotos del progreso, para no perder el contacto a través del foro.

No es que me dé por vencido, es que me preocupa que usted se esté interesando tanto por buscar una solución al proyecto, y no estamos solucionando el problema con el mando.

Usted me está siendo de gran ayuda, ya que hemos mejorado mucho el código, pero tampoco quiero abusar de su colaboración.

A sí que lo dejo en sus manos, o intentamos más pruebas, o nos esperamos al RS485.

Un saludo.




Good night.

The first thing I have to do is thank you for the time you are solving the problems of my project, you have almost written as many lines of code as I have.

I've made the changes you sent me to your code, and I'm sorry to have to tell you that we haven't unfortunately advanced anything.

The controller still ignores the commands, all it does is turn the spotlights on and off very difficult, it takes a long time, eight seconds of clock, with the button pressed, when it should be almost immediate, and the LED still does not turn on.

However, with your Master program, in the Serial Monitor, I can see almost immediately the button phrase pressed, but the peripherals do not react, neither the LEDs, nor the motors, nor the servo.

We're going to have to wait and see if I get the RS485, which don't have to take long anymore, and we can improve communication problems between the Arduinos.

We have already seen that the controller only if it works, but as soon as the Arduino has to manage the sending and receiving of data, other than the controller, nothing works as it should.

All the programs I have seen of the Serial Communication, wired, without RS485, are limited to turning on an LED and little else, I have not seen in any program that the Slave manages more than two sensors and one LED at a time, and the Master only receives the data and displays them on an LCD.

There is no program as complicated as this.

I have already found a website that can serve as a guide, for the transformation towards communication with the RS485, I put the link, to study the adaptation of the code to the use of the SR485.

https://proyectoarduino.com/comunicaciones-con-rs485/

I think the best way to get a much better communication would be the one that describes as option three, the one that calls Communications with RS485 in Full-Duplex mode, for a fluid two-way communication, I think that if we do not do so, we will be going to be going to be going to be going around without getting anything that improves the current situation.

While we can continue to debug and improve the code, or I can dedicate myself to continue mounting the helmet and putting photos of progress, so as not to lose contact through the forum.

It's not that I give up, it's that I'm worried that you're being so interested in looking for a solution to the project, and we're not solving the problem with the controller.

You're being very helpful to me, as we've improved the code a lot, but I don't want to abuse your collaboration either.

I'll leave it in your hands, or we'll try more tests, or we're waiting for RS485.

Greetings.
Attachments
49_11_05_2020.rar
(16.36 KiB) Downloaded 315 times
Post Reply