I'm trying control the strength of an electromagnet using an Arduino. I've included my circuit and code below.
I'm still going to add a diode to protect the MOSFET but the current circuit set-up and code seem to be working. But now there's something odd happening with the circuit that I don't understand. I'm writing the value of the PWM connected to the MOSFET using the input from the potentiometer, and it seems to be mapping correctly because when I connect an LED to the drain of the MOSFET and turn the potentiometer, the brightness changes. I even tried to just write 0 in my analogWrite and the LED turned off. But when I connect the electromagnet, it seems to always be "on" at full strength even if the PWM value being written is 0.
I tried using a 2.2kohm resistor because I figured maybe it's because I'm driving too much voltage, but that just made the electromagnet really weak while still constantly on all the time.
How can I properly control the strength of the electromagnet?
This is the electromagnet I'm using.
This (TO-220) is the MOSFET I'm using.
#define MAX_ANALOG_INPUT_VAL 1023
#define NOFIELD 503L
const int POT_INPUT_PIN = A0;
const int HALL_PIN = A1;
const int OUTPUT_PIN = 3;
const int OUTPUT_PIN_LED = 9;
int prev_hall=0;
int prev_pot=0;
void setup() {
pinMode(POT_INPUT_PIN, INPUT);
delay(1);
pinMode(HALL_PIN, INPUT);
delay(1);
pinMode(OUTPUT_PIN,OUTPUT);
delay(1);
pinMode(OUTPUT_PIN_LED,OUTPUT);
delay(1);
Serial.begin(9600);
}
void loop() {
/*Reading analog input from potentiometer and mapping to pwm pin that supplies power to electromagnet*/
int POT_raw = analogRead(POT_INPUT_PIN);
int POT_pwm = map(POT_raw, 0, MAX_ANALOG_INPUT_VAL, 0, 255);
/*Mapping value for p5js*/
int POT_p5js = map(POT_raw, 0, MAX_ANALOG_INPUT_VAL, 1, 128);
/*Mapping value for and p5js */
analogWrite(OUTPUT_PIN, POT_pwm);
delay(1);
analogWrite(OUTPUT_PIN_LED, POT_pwm);
Serial.println(analogRead(OUTPUT_PIN));
delay(100);
/*Reading Hall effect sensor*/
int HALL_raw = analogRead(HALL_PIN); //Reading hall effect sensor
/*Mapping value for p5js*/
int magnet_p5js = map(HALL_raw, NOFIELD, MAX_ANALOG_INPUT_VAL, 129, 255);
/*Making some calculations to clear background magnetic field noise. Only sending signal if magnetic field changes since it's too sensitive */
if(HALL_raw < NOFIELD) {
HALL_raw = NOFIELD + (NOFIELD - HALL_raw);
}
if(abs(HALL_raw - NOFIELD)<15){
HALL_raw = NOFIELD;
}
int diff_hall = HALL_raw - prev_hall;
int diff_pot = POT_raw - prev_pot;
if(abs(diff_hall)>10){
// Serial.write(magnet_p5js);
}
if(abs(diff_pot)>2){
// Serial.write(POT_p5js);
}
prev_hall = HALL_raw;
prev_pot = POT_raw;
delay(100);
}