Stepper motor program

Thread Starter

JK-FlipFlop

Joined Jul 5, 2010
111
I made this program to run a stepper motor by uC PIC18f4520.
I need you to find a mistake in this program:

#include <hitech.h>
#include <pic18.h>
void DELAY(void); /*Spend time function*/
int sequence[8] = {0xc, 0x4, 0x6, 0x2, 0x3, 0x1, 0x9, 0x8}; /* running sequence for motor (half step)*/
int N; /*number of sequence*/
main()
{
TRISC=0xff;
TRISD=0x00;
N=0;
while((PORTC&0x2)==0x2)
{
for(;((PORTC&0x1)==0x1);N++)
{
PORTD = sequence[N];
DELAY();
if(N=8)
{
N=0;
}
}
for(;((PORTC&0x1)==0x0);N--)
{
PORTD = sequence[N];
DELAY();
if(N=0)
{
N=8;
}
}
}
}

void DELAY(void)
{
unsigned int i;
for(i=0;i<0x7fff;i++);
}

if you find any thing wrong type it.

thanks.
 

BMorse

Joined Sep 26, 2009
2,675
you need to use the code tags to make the code more readable:

Rich (BB code):
#include <hitech.h>
#include <pic18.h>
void DELAY(void); /*Spend time function*/
int sequence[8] = {0xc, 0x4, 0x6, 0x2, 0x3, 0x1, 0x9, 0x8}; /* running  sequence for motor (half step)*/
int N; /*number of sequence*/
main()
{
TRISC=0xff;
TRISD=0x00;
N=0;
while((PORTC&0x2)==0x2)
{
for(;((PORTC&0x1)==0x1);N++)
{
PORTD = sequence[N];
DELAY();
if(N=8)
{
N=0;
}
}
for(;((PORTC&0x1)==0x0);N--)
{
PORTD = sequence[N];
DELAY();
if(N=0)
{
N=8;
}
}
}
}
 
void DELAY(void)
{
unsigned int i;
for(i=0;i<0x7fff;i++);
}

Where is the configuration for the pic?
Can you attach a circuit schematic to see if code matches hardware?


B. Morse
 

Thread Starter

JK-FlipFlop

Joined Jul 5, 2010
111
The code only need to show the number of the sequence on PORT D and than by transistors driver going to the motor.

example of working code:

#include <hitech.h>
#include <pic18.h>
void T(void);
main()
{
TRISC=0xff;
TRISD=0x00;
while((PORTC&0x2)==0x2)
{
while((PORTC&0x1)==0x1)
{
PORTD=0xc;
T();
PORTD=0x4;
T();
PORTD=0x6;
T();
PORTD=0x2;
T();
PORTD=0x3;
T();
PORTD=0x1;
T();
PORTD=0x9;
T();
PORTD=0x8;
T();
}

while((PORTC&0x1)==0x0)
{
PORTD=0xc;
T();
PORTD=0x8;
T();
PORTD=0x9;
T();
PORTD=0x1;
T();
PORTD=0x3;
T();
PORTD=0x2;
T();
PORTD=0x6;
T();
PORTD=0x4;
T();
}
}
}

void T(void)
{
while((PORTC&0x2)!=0x2);
if((PORTC&0x2)==0x2)
{
unsigned int i;
for(i=0;i<0x7fff;i++);
}
}
 
Last edited:

davebee

Joined Oct 22, 2008
540
When you count up, you count from 0 to 7, testing for 8 as the overflow, setting N=0 in that case.

So counting down, don't you want to count from 7 to 0, testing for -1 as the underflow, then set N=7?
 

John P

Joined Oct 14, 2008
2,026
How about this?

Rich (BB code):
  byte incr=0, n=0;

  while(1)
  {
    if (portc & 2)
      incr = 1;
    else if (portc & 1)
      incr = 255;
    else 
      incr = 0;

    n += incr;
    portd = sequence[n & 7];

    delay();
  }
 
Top