What N-Mosfet to control a small DC motor

danadak

Feb 19, 2021
1,062
Joined
Feb 19, 2021
Messages
1,062
Found error in mBlock code, set the wrong variable to 200, here is fix :

1725274795304.png
 

Attachments

  • FadeMotor.zip
    56 KB · Views: 0

Harald Kapp

Moderator
Moderator
Nov 17, 2011
14,270
Joined
Nov 17, 2011
Messages
14,270
C:
*/
// constants won't change. They're used here to set pin numbers:
const int PushButton = 2;  // the number of the pushbutton pin
const int MOTORPin = 9;    // MOTOR connected to digital pin 9
// variables will change:
int buttonState = 0;  // variable for reading the pushbutton status

void setup() {
   // initialize the pushbutton pin as an input:
  pinMode(PushButton, INPUT);
 
}
void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(PushButton);
  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn MOTOR on:
    digitalWrite(pinMode, HIGH);
  } else {
    // turn motor off:
    digitalWrite(pinMode, LOW);
  }
 ...
    }

This code can't work. I don't even understand how it compiles without error ...:
digitalWrite(pinMode, HIGH); -> makes no sense at all as pinMode is also not defined as a variable or constant anywhere.

Your code should look something like this:
C:
*/
// constants won't change. They're used here to set pin numbers:
const int PushButton = 2;  // the number of the pushbutton pin
const int MOTORPin = 9;    // MOTOR connected to digital pin 9
// variables will change:
int buttonState = 0;  // variable for reading the pushbutton status

void setup() {
   // initialize the pushbutton pin as an input:
  pinMode(PushButton, INPUT);
 
}
void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(PushButton);
do you have the required pull-down resistor attached and pushbutton is connected to Vcc? Show us the schematic.
commonly the pushbutton is connected to GND and the input is set to PULLUP. This spares the external resistor.
however, a pressed pushbutton is the logic LOW (inverse logic)
you need to debounce the pushbutton. Otherwise the behavior will be erratic at best.
Code:
  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn MOTOR on:
    digitalWrite(MOTORPin, HIGH);
  } else {
    // turn motor off:
    digitalWrite(MOTORPin, LOW);
  }
 ...
    }
 
Top