Not good at coding at all, so I'm at a total loss here.
But I'm doing a project that involves controlling a larger DC voltage through a mosfet. What I'm doing is I'm using a HC-05 to transmit data between a phone and the Arduino Uno. Seeing the value within a couple of seconds is necessary.
However, sending the mosfet gate a command to open or close up work very inconsistently. Sometimes never and sometimes it takes up to 30 seconds for it to register.
The code here is a short version of the project that I'm working on, but behaves similarly.
#define mosfet 11
int state = 0;
int gate = 0;
int maxgate = 255;
int mingate = 0;
void setup() {
delay(2000);
pinMode(mosfet, gate);
analogWrite(mosfet, 0); //starts closed
Serial.begin(9600);
}
void loop() {
while(Serial.available() > 0){
state = Serial.read();
for (int y=0; y <= 5; y+=5){
delay(500);
Serial.println("testphase 1");
delay(500);
}
for (int y=5; y >= 0; y--){
delay(250);
Serial.println("testphase 2");
delay(250);
}
if (state == '0') {
gate = gate + 1;
if(gate > maxgate) gate = maxgate;
analogWrite(mosfet, gate);
Serial.println(int(gate));Serial.print(", +1");
state = 0;
}
if (state == '1') {
gate = gate + 10;
if(gate > maxgate) gate = maxgate;
analogWrite(mosfet, gate);
Serial.println(int(gate));Serial.print(", +10");
state = 0;
}
}
}
When sending 'State == 1', for example it will go through both for loops multiple times and the maybe sometimes do gate + 10. Sometimes the commands goes completely ignored.
I have no idea how I would interrupt a loop to execute the given command and then go back.
1 Answer 1
Actually got it working myself, but thank you so much for your help @chrisl
Ditched the for loop completely just to try things out and reorganized my code a bit. Surprisingly it started to work well enough.
Basically just moved my measuring stuff outside the while loop*(and now that I think about it, why would it ever be withing the while loop? Literally makes no sense)* and to the end of the whole void loop part, and only polled for state changes within the while loop while the BT connection was active.
Doesn't miss a command as far as I can tell, and the adjustment is within 2 seconds when using my whole code, which is perfect. Also the whole program doesn't just freeze itself while trying to think what happened when the change set was send.
Here's a short version, should somebody bump into this thread in the future.
void loop() {
while(Serial.available() > 0){
state = Serial.read();
if (state == '0') {stuff happens here,
}
} //End of the while loop.
sensors.requestTemperatures();
delay(1000);
Celcius=sensors.getTempCByIndex(0);
}
BlinkWithoutDelay
example of the Arduino IDE.pinMode()
seems incorrect (because of the variablegate
bring where the pinmode constant should be). But that shouldn't be a problem, sinceanalogWrite()
configures the pin correctly.