Hello, im building a robot, and im using a IR sensor, so when it detects it doesnt do anything, but when it doesnt detect it makes a move, the problem im having is with the code, because i dont know how to do that when it finishes the action he needs to detect and undetect again to work, is it possible?
Very good. Please, show the wiring diagram with all your devices connected with names and pin numbers AND the code you are using (in a <CODE> block so the code is easy to read and copy for testing.
Sounds like your "logic" is upside down (DETECT = nothing, NO DETECT = something)... Look in your code for when the IR sensor reading is compared to HIGH or LOW.
Anything is possible.
Look at the sensor as a true/false. You can use either high or low as true and the converse would be true. So true do something and if false stop.
It sounds like quickly fixed by earlier helpers.
Before posting the next time, please take a walk here: “How to get the best out of this forum - Projects / General Guidance - Arduino Forum“
Hello, i didnt explain very well, sorry. I want my robot to do something when It doesnt detect.
What i want:
Detects hand: Nothing
Remove hand: Makes a cicle that cant be interfered
If there is no hand: Makes cicle when you put and remove the hand
If there is hand: Just makes cicle when its removed.
I tried tons of codes, with 2 variables like x and y so when both are true It moves but It doesnt work, after the cicle if i put my hand It moves, i dont know why.
Show one.
im spanish, so variables may confuse you hehe
const int stepPin = 3;
const int dirPin = 2;
const int sensorPin = 7;
const int stepsPerRev = 200;
const int velocidad = 600;
bool mano = false; // detectando
bool noMano = false; // dejó de detectar
bool detectaAnterior = 1;
void setup() {
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(sensorPin, INPUT);
}
void loop() {
bool detecta = digitalRead(sensorPin);
if (detecta == 1) {
mano = true;
}
if (detecta == 0) {
noMano = true;
}
if (mano == true && noMano == true) {
secuencia();
mano = false;
noMano = false;
}
detectaAnterior = detecta;
}
void secuencia() {
digitalWrite(dirPin, HIGH);
girar(5);
digitalWrite(dirPin, LOW);
girar(5);
}
void girar(int vueltas) {
long pasos = vueltas * stepsPerRev;
for (long i = 0; i < pasos; i++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(velocidad);
digitalWrite(stepPin, LOW);
delayMicroseconds(velocidad);
}
}
What is your sensor reading using this:
const int sensorPin = 7;
void setup() {
Serial.begin(115200);
pinMode(sensorPin, INPUT);
}
void loop() {
Serial.print(digitalRead(sensorPin));
delay(100);
}
Also... with a hand and without a hand have the same result...
if (detecta == 1) {
mano = true;
}
if (detecta == 0) {
noMano = true;
}
Same here...
if (mano == true && noMano == true) {
secuencia();
mano = false;
noMano = false;
}
It seems to me the "mano" and "noMano" should be opposite to cause something to happen with a hand and then without a hand.
so, i did a test, because i was starting to struggle, so chatgpt gave me this test
// y da una pequeña confirmación con el motor al cambiar el estado interpretado.
//
// Pines:
const int stepPin = 3; // STEP del driver
const int dirPin = 2; // DIR del driver
const int sensorPin = 7; // OUT del sensor
// Motor / test
const int stepsConfirm = 10; // pasos a dar como "tick" de confirmación
const unsigned int stepDelay = 800; // microsegundos por mitad pulso
// Variables
int prevInterpret = -1; // -1 = no inicializado, 0 = no detecta, 1 = detecta
void setup() {
pinMode(stepPin, OUTPUT);
pinMode(dirPin, OUTPUT);
pinMode(sensorPin, INPUT); // empezamos sin pull-up para la primera lectura
digitalWrite(stepPin, LOW);
digitalWrite(dirPin, LOW);
Serial.begin(115200);
Serial.println();
Serial.println("TEST SENSOR + MOTOR - Inicio");
Serial.println("Coloca la mano delante/quitala y observa los valores:");
Serial.println(" rawFloating | rawPullup | interpretado");
Serial.println(" (INPUT) | (PULLUP) | 0=no detecta 1=detecta");
Serial.println();
}
void loop() {
// 1) lectura sin pull-up (puede estar flotando)
pinMode(sensorPin, INPUT);
delay(10); // pequeño tiempo para estabilizar
int rawFloating = digitalRead(sensorPin);
// 2) lectura con pull-up interno
pinMode(sensorPin, INPUT_PULLUP);
delay(10);
int rawPullup = digitalRead(sensorPin);
// Interpretación automática:
// Elegimos usar rawPullup como referencia (más fiable contra flotaciones).
// Con INPUT_PULLUP: raw == LOW normalmente significa que el sensor "saca 0" (activo),
// y raw == HIGH significa "sin activación".
//
// Pero cada módulo es distinto; el comportamiento que buscamos es "detecta" = 1, "no detecta" = 0
// Por convención aquí definimos:
// detecta = (rawPullup == LOW) ? 1 : 0;
//
// Si al probar ves que ocurre al revés, lo cambiarás en base a lo que imprime el Monitor Serie.
int interpretado = (rawPullup == LOW) ? 1 : 0;
// Imprimir resultados
Serial.print(" ");
Serial.print(rawFloating);
Serial.print(" | ");
Serial.print(rawPullup);
Serial.print(" | ");
Serial.println(interpretado);
// Si el estado interpretado cambia respecto al anterior -> confirmación con motor
if (prevInterpret == -1) {
prevInterpret = interpretado; // inicializamos la referencia
} else if (interpretado != prevInterpret) {
// Cambio detectado: damos una confirmación física con el motor
Serial.print("Cambio detectado: ");
Serial.print(prevInterpret);
Serial.print(" -> ");
Serial.println(interpretado);
// Dar pasos de confirmación (10 pasos rápidos)
confirmStep(stepsConfirm);
prevInterpret = interpretado;
}
delay(150); // espera entre lecturas (ajustable)
}
// Función para dar N pasos (usada como "tick" de confirmación)
void confirmStep(int pasos) {
// Gira un poco en el mismo sentido (no se hace vuelta completa)
digitalWrite(dirPin, HIGH); // sentido fijo
for (int i = 0; i < pasos; i++) {
digitalWrite(stepPin, HIGH);
delayMicroseconds(stepDelay);
digitalWrite(stepPin, LOW);
delayMicroseconds(stepDelay);
}
}
And i obtained
detect 0 0 1
stops detect 1 1 0
Also, i made the mano and nomano, so that It has to detect and stop detecting before working again.
Basically im doing this for an inyecting machine, that closes and makes a piece, so when It opens (stop detecting) it works, It goes to the initial position (finishes cicle) and to work again the machine has to close to inyect (detects) and open to take the piece (stop detecting). So what i really need is to watch detection, and if after detection It stops detecting, it works. Did i explain better? Sorry for my english
. And thanks.
If it solved your problem, very good.
nope, i mean, i still dont know how to make It work how i want to, do you see any solution?
You explained 2 different behaviours of your machine/robot. In the first, the cycle can be interrupted during execution by the operator hands. In the last one, the machine will do the injection and come back to the initial position. Which one is the correct?
@xfpd gave you a good hint in post #8. Instead of using 2 different variables mano and nomano, just do
if (detecta == 1) {
mano = true;
}
if (detecta == 0) {
mano = false;
}
Keep in mind that the machine can’t be stopped while stuck into this part of the code:
If you want the machine to stop during the injection when something is detected, you will need to let the motor do one step each passing through the loop and also check wether the hand is there or not.
Two programming topics for you to take a look: state machines and interruptions.
Gold hint: in the current development state, AI can help you a lot if you know what you’re doing. Before that, getting a working sketch will need lots of iterations.
This two behaviours are the same, mano = machine i just wrote mano because im testing with my hand, mano is hand in spanish, the thing is, machine will close for inyection (IR will detect, the mold is closed) after it opens (IR not detecting) my robot makes a move, returning to original position (so its a cicle), the cicle will last for example 10 secs, and the mold will close in 11 secs, so to activate the robot again the sensor will need to detect and stop detecting. Because, if it doesnt detect when he finishes the action, it will start again and the mold will smash it. I need the sensor to detect and stop detecting before making an action, not just to stop detecting, and there is where im struggling.
The people here understand code without needing to understand languages. We see this as a variable (for example, we see "m" rather than "mano", and "m2" rather than "nomano"), without knowing the tongue of you, the author.
I now see that your intent with the "mano/nomano" is to count "present" and "notpresent" before starting the sequence (then resetting "mano/nomano"). I ran your code, but because of how the mano/nomano is in the code, every two times detecta registers something, the motor spins.
I wrote similar code to what you are doing, but using buttons rather than an IR sensor. This code reads the two buttons and determines the order (inside first or outside first). Once the first button is detected, only by pressing the second button will a full cycle be recognized.
I think your code will need which sensor detects first. Then you can tell the direction (off to on, or on to off).
Would you make a list of:
- How the machine determines where to start detecting
- What is the sequence of events to make a successful run
- What sequence of events must be guarded against
- Does this run forever, or is there a stopping point
Having owned and operated a large plastic injection machine, it had and they all have an enclosure with doors that must be completely closed before any machine operation can be started or continued. Your machine should be the same.
That is true, however, most of this robots are above the machine, that usually have spaces for them, as you can see wittman have most of them, my robot will move in just y axis like a 3d printer, and will have a clamp that take the piece, then if my robots cicle takes 10 secs i will program the machine to inyect each 15 secs.
thanks a lot, i was able to understand your code, finally i was able to fix mine, now my robot just moves after a detection and no detection happens, without being able to be interfered while It works.
Very good.