I was supposed to first create a 4x1 MUX using AND and NOT gates. The 4 input data lines (io,i1,i2,i3) were 4 PWM pins from the arduino (3,5,6,9), with analogWrite() values as 100,150,200,250 respectively, and the selection lines were taken from two slide switches. enter image description here
int i0=100;
int i1=150;
int i2=200;
int i3=250;
void setup()
{
pinMode(5, OUTPUT);
pinMode(6,OUTPUT);
pinMode(9,OUTPUT);
pinMode(3,OUTPUT);
analogWrite(3,i0);
analogWrite(5,i1);
analogWrite(6,i2);
analogWrite(9,i3);
Serial.begin(9600);
}
void loop()
{
}
Simulation link: https://www.tinkercad.com/things/cRZNvuwhZYV
The voltmeter + is connected to the output of the MUX. Both selection lines are HIGH, so the output is i3, which has the pWM value 250. So the voltage should be (250/255)*5, i.e about 4.9 V, which is what the meter shows. (The servo is present but not connected.)
The voltmeter values are in accordance for all the 4 possible combinations. In short, the 4x1 MUX is working perfectly.
(it was important for me to clarify this as otherwise people might have thought of the MUX implementation as the problem with my lsubsequent circuit , and with the messy wiring, it would've been impossible to confirm whether or not this is the case. However, as I have clearly shown, the problem is NOT with the MUX).
Next, I tried to control the servo using this MUX. I connected the servo control pin to the MUX output: enter image description here
#include<Servo.h>
Servo s1;
Servo s2;
Servo s3;
Servo s4;
int i0=100;
int i1=150;
int i2=200;
int i3=250;
void setup()
{
pinMode(3,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(9,OUTPUT);
analogWrite(3,i0);
analogWrite(5,i1);
analogWrite(6,i2);
analogWrite(9,i3);
s1.attach(3);
s2.attach(5);
s3.attach(6);
s4.attach(9);
Serial.begin(9600);
}
void loop()
{
s1.write((i0*180)/255);
s2.write((i1*180)/255);
s3.write((i2*180)/255);
s4.write((i3*180)/255);
}
For instance, I thought if both switches were on, then the output is i3,(which was coming from pin 9), so
only s4.attach(9);
and s4.write((i3*180)/255);
will work. (As, it is apparent that the control pin is connected to pin 9 in this case).
The servo does move around when I change the switches to on off combinations, however,something drastic has happened to the voltmeter values, which tells me that my code is messing with the MUX output. The output voltages fluctuate rapidly between 97 and 180 mV.
What exactly have I done wrong, and how exactly am I supposed to control the Servo, then?
analogWrite()
orServo.write()
repeatedly inloop()
without anything to slow it down would restart the PWM wave again and agian. Please try to put these lines intosetup()
instead. Maybe tinkercad handlesanalogWrite()
and the servo library differently.