Bonjour, j'essaie d'activer un solénoïde via un interrupteur.
A chaque pression sur le bouton je souhaite que le solénoïde s'active 60 millisecondes.
Je ne peux pas utiliser la fonction delay()
Mes connaissances en C sont très sommaire et assez inégales.
Pouvez vous me dire ce qui cloche dans le code svp ?
Il y a plusieurs fichiers dans le code.
------------------------solenoid.cpp----------------------
//
// Created by Eric Vantillard on 22/05/2022.
//
#include "Solenoid.h"
Solenoid::Solenoid(int pin, bool allowReactivation) : pin(pin), allowReactivation(allowReactivation) {
activated = false;
activatedUntilMs = -1;
lastActivationMs = -1;
}
void Solenoid::setup() const {
pinMode(pin, OUTPUT); //Sets that pin as an output
digitalWrite(pin, LOW);
}
void Solenoid::update() {
if (activated) {
auto now = millis();
if (now >= activatedUntilMs) {
desactivate();
}
}
}
void Solenoid::activate(unsigned long durationMs) {
if (!activated || allowReactivation) {
activated = true;
const auto now = millis();
lastActivationMs = now;
activatedUntilMs = now + durationMs;
digitalWrite(pin, HIGH);
}
}
void Solenoid::desactivate() {
activated = false;
activatedUntilMs = -1;
digitalWrite(pin, LOW);
}
unsigned long Solenoid::lastActivation() const {
return lastActivationMs;
}
bool Solenoid::isActive() const {
return activated;
}
#include "Solenoid.h"
Solenoid solenoid(7, false);
void setup() {
solenoid.setup();
}
void loop() {
solenoid.update();
if(digitalRead(A2)==LOW){
solenoid.activate(60);//60 milli seconds
}
}
-------------------------------solenoid.h-----------------------------
//
// Created by Eric Vantillard on 22/05/2022.
//
#ifndef ARDUINO_SOLENOID_LIB_SOLENOID_H
#define ARDUINO_SOLENOID_LIB_SOLENOID_H
#include <Arduino.h>
class Solenoid {
public:
explicit Solenoid(int pin, bool allowReactivation = true);
void setup() const;
void update();
void activate(unsigned long durationMs);
void desactivate();
unsigned long lastActivation() const;
bool isActive() const;
private:
const int pin;
const bool allowReactivation;
bool activated;
unsigned long activatedUntilMs;
unsigned long lastActivationMs;
};
#endif //ARDUINO_SOLENOID_LIB_SOLENOID_H
------------------------------le code--------------------------
#include <Arduino.h>
#include "Solenoid.h"
Solenoid solenoid(7, false);
void setup() {
solenoid.setup();
}
void loop() {
solenoid.update();
if(digitalRead(A2)==HIGH){
solenoid.activate(60);//60 milli seconds
}
auto now = millis();
if(now%1000==0){
solenoid.activate(60);//60 milli seconds
}
}