-- SNIP ORIGINAl CODE --
Any experts can teach me how to add 4 motors running concurrently at the same time?
The number of LEDs lights up depends on the number of motors running.
e.g like the program above in
bold
Any inputs appreciated please!
Code:
#include <p18f4520.h>
#include <delays.h>
#pragma config OSC = HS
#pragma config WDT = OFF
#pragma config LVP = OFF
#pragma config PBADEN = OFF
#define S0 PORTCbits.RC0
#define S1 PORTCbits.RC1
#define S2 PORTCbits.RC2
void main(void)
{
TRISD = 0x00;
TRISC = 0xff;
PORTD = 0b00001111;
while(1)
{PORTD = 0x00;
if((S0==1)&&(S1==0)&&(S2==0))
{
PORTD = 0b00000001;
(Motor 1 to run)
}
else if((S0==0)&&(S1==1)&&(S2==0))
{
PORTD = 0b00000011;
(Motor 1&2 to run)
}
else if((S0==1)&&(S1==1)&&(S2==0))
{
PORTD = 0b00000111;
(Motor 1&2&3 to run)
}
else if((S0==0)&&(S1==0)&&(S2==1))
{
PORTD = 0b00001111;
(Motor 1&2&3&4 to run)
}
}
}
I am no MPLAB expert, so I will just advice you on what I can, until someone with direct experience on this to further advise you.
First of all, I think your code can more compact as follows
Instead of comparing S0, S1, S2 in such laborious manner, consider compacting them using bitwise operators into an integer and compare using integral operations instead.
Code:
int COMBI = S2 << 2 | S1 << 1 | S0;
Hence
if((S0==1)&&(S1==1)&&(S2==0))
can be replaced as
if (COMBI == 3) since bitwise [S2][S1][S0] will give you 011 which is interpreted as 3 as an integer.
I'm not sure what your PORTD should correspond to, but the way you segregate your conditions can be more exclusive.
Each IF case should tackle only 1 motor, so logics will be clearer if it's
IF (MOTOR 1 CASE) { ... }
IF (MOTOR 2 CASE) { ... }
...
IF (MOTOR N CASE) { ... }
Again using bitwise operations,
the shared PORTD can be affected as
PORTD = 0;
PORTD = PORTD | 1 << MOTOR;
For Motor N, let MOTOR variable be (N-1);
So if you are trying to on MOTOR 3 and 4,
PORTD = PORTD | 1 << 2;
PORTD = PORTD | 1 << 3;
That should set the following bits in PORTD, assuming a 16bits integer
0000000000001100 --> 12
As for your codes, I don't think your PORTD is for motor, it is likely for LED lights.
i did a look up on motors, there are 2 types I knew. One is PWM stepper motor, the other is an ON/OFF type with a feedback mechanism to let you know which angle the motor is aligned to. The technique to command these 2 types of motors are different. Which one are you using ?