PDA

View Full Version : Recommendations - Model Train Controller



malc-c
- 8th February 2007, 21:41
Hi guys and gals,

Just want to pick your brains over a project I'm looking at starting. I want to build a controller for a club layout and thought that I could use a PIC rather than traditional descrete components.

The controler will initially have direct control (ie no simulated coasting and breaking), so I thought of two possible ways the PIC could be used, and wondered if you had any comments.

The first is to use A/D to read the voltage on one pin, and then output a DC voltage to a FET / power transistor to drive the motor from a 12v supply.

The second uses the same A/D to read the voltage on a pin, but the output is PWM (or more exact PPM), which is then used to drive the FET or power transistor in the same way.

The reason I wanted to use a PIC was to add things later such as auto station stops (triggere by a sensor on the track) and simulated inetia, and programming the pick to to that might be better than loads of high value capacitors and the like

skimask
- 8th February 2007, 21:48
Hi guys and gals,

Just want to pick your brains over a project I'm looking at starting. I want to build a controller for a club layout and thought that I could use a PIC rather than traditional descrete components.

The controler will initially have direct control (ie no simulated coasting and breaking), so I thought of two possible ways the PIC could be used, and wondered if you had any comments.

The first is to use A/D to read the voltage on one pin, and then output a DC voltage to a FET / power transistor to drive the motor from a 12v supply.

The second uses the same A/D to read the voltage on a pin, but the output is PWM (or more exact PPM), which is then used to drive the FET or power transistor in the same way.

The reason I wanted to use a PIC was to add things later such as auto station stops (triggere by a sensor on the track) and simulated inetia, and programming the pick to to that might be better than loads of high value capacitors and the like

Not 100% sure what it's called, but have you ever heard of DMC control (again, not sure what it really is)?
As far as I know, you put DC power to the track, superimpose a digital HF signal over the top of the DC power (AC riding on DC). Each 'unit' has a receiver waiting for some sort of encoded sequence, whatever. 1000 different ways of doing it I suppose. Not sure how I'd do it if I had to. Maybe even IR LEDs spaced out everywhere along the track and IR detectors in each 'unit' to detect various codes and commands...

malc-c
- 8th February 2007, 22:00
Thanks for the input

Yes I'm awear of the "digital revolution" that is now appearing in the model railway world, however its not a possibility here for several reasons.

1) - its a club layout, so we need to use "traditional" controllers so that members can run their own locos, and most don't use DMC

2) - we're modelling in N gauge, and most of the modules are too large to fit is the intended stock

skimask
- 8th February 2007, 22:18
Thanks for the input

Yes I'm awear of the "digital revolution" that is now appearing in the model railway world, however its not a possibility here for several reasons.

1) - its a club layout, so we need to use "traditional" controllers so that members can run their own locos, and most don't use DMC

2) - we're modelling in N gauge, and most of the modules are too large to fit is the intended stock

So, you have member A, with his regular ol' analog controller (big transformer, big pot, reversing switch, etc) running his loco on the same length (electrically and physically) of track (only for arguments sake) as member B who has his own controller and his own loco...

And you want them to be able to control their 2 loco's independently...using those same controllers so the members don't have to go out and buy completely new stuff, but instead add new stuff to the output of their old stuff to make their old things do new things...

And be able to fit these controllers inside an N gauge loco...

Woof! Ya don't ask for much do ya :)

Or have I missed something...(I probably have). I've got a few ideas (as I'm sure others do), but each one of them would require some sort of PCB to be added to each loco so it could decode what it needs to do. A small PIC based decoder with a MOSFET using bidirectional PWM drive shouldn't take up that much space (maybe 1 or 2 sq.inches. at most). I've got a 3 channel driver board that'll handle a few amps on each channel, has a 16F628A onboard along with a few other things and it's almost small enough to fit inside an N gauge loco. Take off those 'other things', redesign the board and it should fit...but again, I've probably missed something...

malc-c
- 8th February 2007, 23:07
Or have I missed something...(I probably have).

:) - yeah you've gone a little off the rails ;)



So, you have member A, with his regular ol' analog controller (big transformer, big pot, reversing switch, etc) running his loco on the same length (electrically and physically) of track (only for arguments sake) as member B who has his own controller and his own loco...

No - the member will not be asked to bring their own controllers. The idea is that the club layout will have its own control panel with its own controllers, and as 96% of the membership don't have DCC type control the decision was taken to build "traditional" means of control so that on a club night any member can bring their own locos along and "play trains"

As we need the option to control four trains at one time, I thought that the use of a PIC could reduce the amount of descrete components required (or use 2 pics if there aren't any that have 4 A/D ports - have yet to check the Microchip site) - especially when the controller gets developed a stage further and we build in delays to represent coasting, and simulated acceleration.

Hope that makes it clearer

Acetronics2
- 9th February 2007, 10:56
Hi, Malc

Here you have THE Thing you look for ...

just to translate from "Old" logical circuits to PIC ...

All functions to program are clearly shown.

Alain

malc-c
- 9th February 2007, 11:06
Nice !

I was hoping for something with a component count in single figures :)

Seriously though, thanks for the drawing - I'll have a study in detail later

malc-c
- 9th February 2007, 14:28
hopefully the attached image will try to get over my idea. By adjusting VR1 the resulting value is used to adjust the PPM output on RB0 which (via the power tranny) is fed to the tracks.

mister_e
- 9th February 2007, 14:49
I would use PNP over NPN for that... Depending the current needed, Some P-Channel mosfet.

Acetronics2
- 9th February 2007, 15:42
Driving a '3055 straight from the PIC port ...

Interesting idea ...

Alain

malc-c
- 10th February 2007, 10:19
The diagram was for example only, I intend to use FETs for the driver (They work fine driven directly from a PIC) - If I was going to use a 3055 I would use a GP NPN tranny and connect the two in an emitter follower fashion.

I'm really after your comments on using a PIC's A/D to control the output PW modulation..

Acetronics2
- 10th February 2007, 10:36
Hi, Malc

Why not simply use RCTime to read your pots ...

That would allow "simple" pics like '84 or '628 ... even 648 !!! ... just because of the pincount !!!

Alain

malc-c
- 10th February 2007, 15:42
Alain,

One step ahead of you... I'm using a 16F828a and set up a 100K lin pot and 0.1uf capacitor, and a simple bit of code.. but can't get it to work (just slung it together in the past 5 mins)

The code compiles, but I don't get any PWM on the output (using a LED for test purposes at the moment - no FET connected.)

10k between MCLR and +5v, input from the pot to A2

Here's the code



;************ set up PIC *****************
PORTA = 0 ' declare port level BEFORE port direction = safe power-on
CMCON = 7 ' PortA Digital inputs
CCP1CON = 0 ' PWM off
VRCON = 0 ' Voltage reference disabled
OPTION_REG.7 = 0


TRISA=%11101111 'set PORTA as all input apart from A4
TRISB=%00000000 'set PORTB as all output

@RC_OSC_NOCLKOUT
@WDT_ON
@PWRT_ON
@MCLR_OFF
@BOD_ON
@LVP_OFF
@CPD_OFF
@PROTECT_OFF

;************* set up varibles ************

D var byte ;used to store the result of the pot on port A2
scale var byte ;used in the POT command
Scale = 254 ;used to set range

;************* main program ****************
Main:
Pot PORTA.2,scale,D ;used to read value from pot
pwm PORTB.4,D,1
Goto main



The main loop is self explanatory, port A2 is checked and the result is placed in the variable D, this is used to set the width of the PWM sent out on pin B4

Any ideas why I can't get it to work

mister_e
- 10th February 2007, 16:35
Malc,
Your configuration fuse don't do anything. The way you do it, it actually do nothing else than define some Labels.



'
' PIC Configuration fuses
' =======================
' _BODEN_ON
' _BODEN_OFF
' _CP_ALL
' _CP_75
' _CP_50
' _CP_OFF
' _DATA_CP_ON
' _DATA_CP_OFF
' _PWRTE_OFF
' _PWRTE_ON
' _WDT_ON
' _WDT_OFF
' _LVP_ON
' _LVP_OFF
' _MCLRE_ON
' _MCLRE_OFF
' _ER_OSC_CLKOUT
' _ER_OSC_NOCLKOUT
' _INTRC_OSC_CLKOUT
' _INTRC_OSC_NOCLKOUT
' _EXTCLK_OSC
' _LP_OSC
' _XT_OSC
' _HS_OSC
@ __CONFIG _INTRC_OSC_NOCLKOUT & _MCLRE_OFF & _LVP_OFF & _WDT_ON & _PWRTE_ON & _BODEN_ON

malc-c
- 10th February 2007, 17:38
Steve,

The code was ripped from a previous bit of code that worked fine - I just changed the main part of the program and deleted all that wasn't required, so I can't see why it wouldn't work.

Its always the fuses that catch me out !!

malc-c
- 10th February 2007, 17:53
Steve,

If I remember correctly, if I leave out any config settings it takes whats listed in the INC file ??

If I delete my listings and add your last line it errors "overwriting previous settings" - (I'm using MPSAM) - If I leave the listings as



@RC_OSC_NOCLKOUT
@WDT_ON
@PWRT_ON
@MCLR_OFF
@BOD_ON
@LVP_OFF
@CPD_OFF
@PROTECT_OFF


it compiles fine

mister_e
- 10th February 2007, 18:15
:eek:Sure it compile fine but it simply don't do anything.

You could also Type


@SantaClausIsComingToTown_ON


And MPASM won't yell, it just define a LABEL



@SpinHere
@ GOTO SpinHere




@MCLR_OFF
@ Goto MCLR_OFF

also work

Have a look at the following...
http://www.picbasic.co.uk/forum/showpost.php?p=6775&postcount=5

Acetronics2
- 10th February 2007, 18:33
Alain,

One step ahead of you... I'm using a 16F828a and set up a 100K lin pot and 0.1uf capacitor, and a simple bit of code.. but can't get it to work (just slung it together in the past 5 mins)

pwm PORTB.4,D,1
4

Any ideas why I can't get it to work

Hi, Malc

1) May be you should try the HPWM function ... i've noticed it worked much better for motor PWM ... on PORTB.3 instead of B.4 ( ! )

2) Try RCTime ...instead of this stupid POT ... linearity will be far better !!!

AND KEEP WITHIN THE MANUAL VALUES ( 5 -50 k ; 0.1µF ) IF STILL USING POT !!!

heuuuu ... your scale value (254 ) is a bit surprising ...

Alain

Acetronics2
- 11th February 2007, 11:10
Hi, Malc

When your 1 Channel PWM will work ...

Have a look there, then :

http://www.pbpgroup.com/modules/wfsection/article.php?articleid=12

for implementing the 4 Channels ...

Alain

malc-c
- 11th February 2007, 11:50
Thanks for the link, and really interesting site.

I'm going to browse the forum to sort out my basic config problems ( Its often months between projects and I forget how to do the simple stuff ) That was the one thing I liked about JAL, you simply added something like #include 16F628a.inc at the start of the code and that took care of all the config settings.

Thanks guys for your input - much head scratching to do !

malc-c
- 11th February 2007, 13:20
Ok I now realise where I went wrong.. since I last used PBP I re-built the PC and thus the changes made to the 16F628a inc file had been lost.. I followed Steves advice and now have a working device..sorta !

Just need to tweek the scale so that I get a full duty cycle from 0 to 255

malc-c
- 11th February 2007, 16:20
Ok I got nowhere with that POT command, so jump in the deep end and try using ADC.

I've used a 12F675 with the following code. As I've never used ADC before and still find datasheets confusing I just cut and pasted examples from the PBP manual for ADC.



@ __CONFIG _INTRC_OSC_NOCLKOUT & _WDT_ON & _PWRTE_ON & _MCLRE_OFF & _BODEN_ON

TRISIO.2 = 0 'Set GPIO.2 to output.
ANSEL.2 = 0 'Set GPIO.2 to digital
GPIO.0 = 1 'gpio.0 set to input
VRCON = 0 ' Voltage reference disabled
OPTION_REG.7 = 0

DEFINE ADC_BITS 8 ' Set number of bits in result
DEFINE ADC_CLOCK 3 ' Set clock source (rc = 3)
DEFINE ADC_SAMPLEUS 50 ' Set sampling time in microseconds

led var GPIO.2
i var byte
D var byte

main:
ADCIN 0, D
Pwm GPIO.2,D,1
goto main


To my suprise, the code compiled and works, well sort off !

using a 10K pot connected between +5v and GND with the wiper connected to GPIO 0, my DVM reads between +0.14v and +5 on GPIO 2 when the pot is turned through its range - connecting an LED to GPIO 2 confirms that something is working as its brightness can be controlled via the POT... so far so good

I then tested the FET by connecting a 10K pot between gnd and +5v with the wiper going to the gate, the track between +12v and FET and the FET to GND. Adjusting the pot produced some degree of control over a loco... so I moved the link from the pots wiper and connected it to GPIO 2. However the DVM reads the same vdd of the 12v rail regardless of the setting of the POT.

I can only assume that its something to do with the PWM output from the PIC that is turning on the FET continiously ?? anyone have any suggestions ?? Can a PIC have DAC so I could convert the resulting digital value to a voltage that would be used to drive the FET (or whatever output stage I use).

I want to stick with a PIC for the control as it would be easier to use simple for next loops / or counters for programmable stops, acceleration, etc

Comments welcome as always

mister_e
- 11th February 2007, 16:39
i think it's more a matter how this PWM function is made...i'll do some test here first. How many different channel you need?
Which other PIC you have on hand?

malc-c
- 11th February 2007, 17:00
LOL - Steve, I sence you see I'm strugling and a bit out of my depth :)

I would like to use 4 channels in total so I can control 4 trains all independantly, but I'm not bothered if I need to use two chips.

I have at my disposal the following PICs:

16F84A
16F873A
16F628A
16F676
16F688
16F877A
16F684
18F2550
12F675
18F4550

Thanks

malc-c
- 11th February 2007, 18:07
i think it's more a matter how this PWM function is made...i'll do some test here first.

Steve, I think you might be right. I used a winscope (soundcard) and captured the output at different settings of the POT - it don't look much like a PPM signal to me

Acetronics2
- 12th February 2007, 09:12
Hi, Malc

Your scoping confirms what I thought and read ...

The pot function charges the capacitor, and then drags little amounts of current ( in coulombs ...), verifies if the pin low thresold is reached, takes another quantity of current, verifies, and so on ...

That's why you get such garbage !!!

Now, the result is a count of the little quantities ... and that explains why you must use the indicated values and not others, even the RC value remains constant.

Alain

PS: and what about a scale value of ... 64 ???

malc-c
- 12th February 2007, 09:43
Alain,

The traces were from the 12f675 that used A/D to read the voltage from a 10K pot (as detailed in post #22).



ADCIN 0, D
Pwm GPIO.2,D,1
goto main


I was expecting a traditional square wave type signal, with varying width of pulse, not the noisy signal the PIC is outputing.... The manual shows additional components for analogue output (resistor / capacitor), maybe I should try using that to get a decent signal out ?

Acetronics2
- 12th February 2007, 10:09
Huh !!!

The manual clearly tells Pwm outputs garbage ... and needs a RC or more sophisticated filter.

Now just keep in mind PWM is only good to get some "analogic" output from the PIC.

Another STAMP " Not so good a function " survivor.

Now, if you want to keep the PWM function ... just compare a sawtooth to this "analogic" voltage ( once filtered ) and you'll get a neat "real PWM" at the output of the comparators.

a quad LM 339 sould do that job very honestly ...

But we remember DARREL's slow PWM is the shiny solution to what you want to do.

Ah, last point ... and not least ! you'll discover the motors have a low PWM ratio thresold not to make some noise and unwanted heating while not turning. one more thing to add !!!

Alain

malc-c
- 12th February 2007, 10:52
Yeah, I re-read the manual and noted that it stated the PWM signal is not tidy. Tried the 10K / 1uF as suggested in the manual
http://www.melabs.com/resources/pbpmanual/images/pwm.gif

But that simply smoothed the output to a constant voltage level, regardless of what setting the pot was turned to.

I spent a lot of time browsing the web last night and most brushed motor control using PICs involved using H-Bridges, which may be impractical for this purpose...

I'll have a more indepth look of that PBgroup website and see if there is anything I can use - Thanks

malc-c
- 12th February 2007, 11:34
Alain,

I'm getting way out of my depth here. I downloaded the three files from Darrel's web site (http://www.darreltaylor.com/DT_INTS-14/SPWM.html) and copied the sample code for the LEDs. Darrel stated on the PBgroup that the code Works on just about any chip. 12F, 16F, 18F, but if I try compiling with MCS I get errors, regardless of the target pic selected.

ERROR: variable wsave3 position request 416 beyond RAM_END 335

I've never used other include files etc before, but if I understand his site correctly it should be a simple matter of downloading and saving the three files to the PBP folder, copy and pasting the sample code into MCS and then compiling ?

Any ideas ?

Acetronics2
- 12th February 2007, 12:43
YESS

Big Idea !!! just comment the faulty line ... as this location only exist in elephant memory Pics !!!

also ... as stated in one of Darrel's further replies !!!

Alain

find it ... in the beginning of " DT int 14 .bas "

' --- IF any of these three lines cause an error ?? ----------------------------
' Comment them out to fix the problem ----
' -- It depends on which Chip you are using, as to which variables are needed --
wsave1 var byte $A0 SYSTEM ' location for W if in bank1
wsave2 var byte $120 SYSTEM ' location for W if in bank2
wsave3 var byte $1A0 SYSTEM ' location for W if in bank3
' ------------------------------------------------------------------------------

YOU DO NOT HAVE BANK3 in your Pic ... isn't it ???

malc-c
- 12th February 2007, 13:45
Alain, thanks for the life saving ring... its keeping me afloat ;)

OK I have something that works... but its not as smooth as the PWM command in PBP.

This is the code, based on the sample taken from Darrel's website. Using a 12F675



@ __CONFIG _INTRC_OSC_NOCLKOUT & _WDT_ON & _PWRTE_ON & _MCLRE_OFF & _BODEN_ON

DEFINE OSC 4
CLEAR

DEFINE ADC_BITS 8 ' Set number of bits in result
DEFINE ADC_CLOCK 3 ' Set clock source (rc = 3)
DEFINE ADC_SAMPLEUS 50 ' Set sampling time in microseconds

INCLUDE "DT_INTS-14.bas" ; Base Interrupt System
INCLUDE "SPWM_INT.bas" ; Software PWM module

DEFINE SPWM_FREQ 40 ; SPWM Frequency
DEFINE SPWM_RES 256 ; SPWM Resolution

D var byte

DutyVars VAR BYTE[3] ; DutyCycle Variables
DutyVar1 VAR DutyVars[0] ; group them in an array for easy access
DutyVar2 VAR DutyVars[1] ; with FOR loops etc.
DutyVar3 VAR DutyVars[2]

ASM
SPWM_LIST macro ; Define Pin's to use for SPWM
SPWM_PIN GPIO, 0, _DutyVar1 ; and the associated DutyCycle variables
SPWM_PIN GPIO, 1, _DutyVar2 ; Notice the underscore before variables
SPWM_PIN GPIO, 2, _DutyVar3
endm
SPWM_INIT SPWM_LIST ; Initialize the Pins
ENDASM

ASM
INT_LIST macro ; IntSource, Label, Type, ResetFlag?
INT_Handler TMR1_INT, SPWMhandler, ASM, yes
endm
INT_CREATE ; Creates the interrupt processor
ENDASM

@ INT_ENABLE TMR1_INT ; enable Timer 1 interrupts

;_________________________________________________ ____________________________

Main:
ADCIN 0, D
DutyVar3 = D
GOTO Main


The output is quite pulsed, and moving the pot produces rather stepped increase in brightness rather than a smooth increase. Also the range of the brightness is limited to 2/3 the travel of the POT (unlike when I used the PWM command when it was right across from one end to the other)

The waveform is different to that previously found when using the PWM command, as can be seen by the two images attached (one low, one high)

I assume the PWM settings in Darrels code can be changed by altering the values of


DEFINE SPWM_FREQ 40 ; SPWM Frequency
DEFINE SPWM_RES 256 ; SPWM Resolution


I'll play with the values and see if anything improves - Thanks for your help on this

EDIT:
Changing the OSC to 20 and freq to 100 gives less flicker, but the transitions are still not smooth... I also think that I need to come up with some driver circuit for the FET or feed the PIC outout into a Darlington pair arrangement with a power tranny reather than a FET

Acetronics2
- 12th February 2007, 14:22
Hi, Malc ...

Think you change your Duty VERY frequently ( it's only a train ...not a jetfighter !!! ) ... so you could insert some PAUSE 100 - 300.

Secondly, you also could change DUTY ... only if the POT result changes.( a little Hysteresis w/ ADC could be useful ??? )

Third, you could insert a smooth duty transition ...

like that :


....

Dutyvar3 = 0

Main:
ADCIN 0, D

IF D <> DutyVar3 THEN

IF Dutyvar3 > D then Dtemp = Dtemp - 1 '( 1, 5, 10 ... as INERTIA needed ! )
IF Dutyvar3 < D then Dtemp = Dtemp + 1

DutyVar3 = Dtemp


ENDIF


PAUSE 200 '( to be trimmed ... 200 for 1 Channel, 100 for 2
Channels ...)

GOTO Main

... or something like that !!!

Alain

malc-c
- 12th February 2007, 21:02
In a bid to get rid of the strange noise shown on the traces in previous posts I've tried using the pulseout command.

Whilst its still not perfect as the pusle width can go down to zero, the resulting squarewave that the PIC outputs is a lot cleaner as can be seen by the attached image

I'm going to get some power transistors tomorrow and develop the output stage based on a few examples I found in an old book I used some 25 years ago and see how it performs.

Here's the code if anyone is interested.



@ __CONFIG _INTRC_OSC_NOCLKOUT & _WDT_ON & _PWRTE_ON & _MCLRE_OFF & _BODEN_ON

TRISIO.2 = 0 'Set GPIO.2 to output.
ANSEL.2 = 0 'Set GPIO.2 to digital
GPIO.0 = 1 'gpio.0 set to input
VRCON = 0 ' Voltage reference disabled
OPTION_REG.7 = 0

DEFINE ADC_BITS 8 ' Set number of bits in result
DEFINE ADC_CLOCK 3 ' Set clock source (rc = 3)
DEFINE ADC_SAMPLEUS 50 ' Set sampling time in microseconds

D var byte

main:
ADCIN 0, D
PULSOUT GPIO.2 ,D
goto main

malc-c
- 12th February 2007, 23:55
Guys, thanks for your input to this idea, however I think I'll opt for a controller using descrete parts afterall. I played about with a few transistors and the FET and managed to get some control over a loco... the drawback was that the armature sang due to the frequency of the pulses !!

Mind you I've learnt a bit more of PBP along the way, so it hasn't all been a waste of time

Darrel Taylor
- 13th February 2007, 12:08
Hi Malcolm,

Don't know anything about trains, but I can say with somewhat good confidence, that the waveforms you were getting are due to the Soundcard Oscilloscope.

Sound cards have a capacitively coupled input, And most have a minimum of around 20hz that they can see. That's a 20hz sine wave, not a squarewave. When you changed to pulsout, you can see on your picture that the frequency went up to almost 2khz, so it was able to at least see the waveform, even though still inaccurately.

I ran the program here (although on a different chip) and got a nice clean 40hz PWM.

It looks like you've given up on the PIC idea already so I won't bore you anymore.

But if you're going to build it out of transistors, this might help.
Various Transistor Throttles
http://home.cogeco.ca/~rpaisley4/Throttles.html

regards,

malc-c
- 13th February 2007, 15:52
Darrel,

Thanks for the advice, never thought that the scope / soundcard software would cause that issue...

I've not given up entirely on using a PIC, as I feel they offer a lot more and simpler than using descrete components. I'll keep plugging away and see what I come up with.

I assume that using a 100 Hz frequency for the PWM would be ideal... what PIC did you use, and is having an internal clock an issue (I'm using a 12F675 for experimential use)

skimask
- 13th February 2007, 23:26
Darrel,

Thanks for the advice, never thought that the scope / soundcard software would cause that issue...

I've not given up entirely on using a PIC, as I feel they offer a lot more and simpler than using descrete components. I'll keep plugging away and see what I come up with.

I assume that using a 100 Hz frequency for the PWM would be ideal... what PIC did you use, and is having an internal clock an issue (I'm using a 12F675 for experimential use)

I've ran a heater blower motor on a car at ~4khz and unless I strained to hear it, there wasn't much to hear. I know it's a different motor, but still, quite a current draw and I switched the power with MOSFETs. Initially, I ran it with somewhere around 62hz...lots of noise! Both audible and almost a vibration...not to mention the noise coming thru the stereo (which may have just been a bad ground somewhere).
The 12F675 can run 4mhz on the internal clock. You should be able to easy incorporate the TMR0 interrupt and make a software PWM output that'll run at 3.9khz (which should be plenty high enough) and use the A/D input to set the duty cycle on that PWM. I suppose the easy way to do it would be to take the 10bit A/D input, divide it by 4, giving you 8 bits and use that as the basis for the software PWM.
Are you familiar with doing software PWM based on interrupts?

Darrel Taylor
- 14th February 2007, 05:10
The 12F675 can run 4mhz on the internal clock. You should be able to easy incorporate the TMR0 interrupt and make a software PWM output that'll run at 3.9khz (which should be plenty high enough) and use the A/D input to set the duty cycle on that PWM. ... Are you familiar with doing software PWM based on interrupts?

I'd be interested to know how you could do that.
And since Malcolm was attempting to use MY software PWM routines based on interrupts, I guess you could say I'm familiar with them.

Let's see, 4 channels @ 3.9khz with 8-bit resolution.

That'll take (3900 *256) = 998,400 interrupts per second.
With a PIC running at 4mhz, it'll execute 1,000,000 intructions per second.
That leaves, 1.0016... instructions per interrupt.

You wouldn't have a code example for that would you?
<br>

skimask
- 14th February 2007, 05:45
I'd be interested to know how you could do that.
And since Malcolm was attempting to use MY software PWM routines based on interrupts, I guess you could say I'm familiar with them.

Let's see, 4 channels @ 3.9khz with 8-bit resolution.

That'll take (3900 *256) = 998,400 interrupts per second.
With a PIC running at 4mhz, it'll execute 1,000,000 intructions per second.
That leaves, 1.0016... instructions per interrupt.

You wouldn't have a code example for that would you?
<br>

Well, yes, I've seen your PWM routines, and fine routines they are, as are most of possibly 100% of the items you post...........ppppfffffffttttttt (that's me fizzling out)

AND I had a brain fart! I had a whole paragraph typed out explaining my position when I realized I forgot the final divide by 256 for the software PWM. Yep, 15.25hz is about the top for 4mhz. That is unless you start sacrificing resolution for speed...but it still doesn't get you up into the khz range, which is what I did to get a 4khz PWM signal in the blower motor project...then again, I only needed slow, fast and a few speeds in between for that one.

Darrel Taylor
- 14th February 2007, 06:28
skimask,

Aw rat's, gave you a chance, but you missed it. :)

You were supposed to say "BAM".

Bit Angle Modulation.

For devices that rely on the "Average Current" resulting from a PWM signal, the PWM signal doesn't need to be exactly symmetrical waveforms based on consecutive ON and OFF cycles.

With BAM, you only need 8 interrupts per cycle. Each time period is "weighted" by it's bit position in the DutyCycle variable.

This way, you could turn every pin on a PIC18F8720 (all 67 of them) into PWM (BAM) outputs (at pretty high frequencies).

And of course, with DT_INTS, it's a piece of cake. :)
<br>

Darrel Taylor
- 15th February 2007, 08:44
I assume that using a 100 Hz frequency for the PWM would be ideal... what PIC did you use, and is having an internal clock an issue (I'm using a 12F675 for experimential use)

Malcolm,

I was using a 16F877A, I guess it was really comparing Apples to Oranges.

I figured I better check with a 12F675, but didn't have one handy so I used a 12F683. It was close enough to figure out what was wrong.

This get's everyone, so I should have seen it right away, but nope.

CMCON = 7 ; disable the comparators
ANSEL = 1 ; AN0 is analog, rest digital

also, You have a PWM output on GPIO.0 ... The same pin as the POT is connected to on AN0. That'll cause problems with the A/D reading.

Hope you're still interested?

EDIT: 100hz is no problem. But you'll need a faster crystal/resonator
INTRC won't cut it.

HTH,

malc-c
- 15th February 2007, 10:51
Darrel,

Sorry I missed that... I've remmed out the PWM line fro GPIO.0 and have got a reasonable result, especially for slow speed - The crawling speed of an 18 year old tank loco is really amaizing !!

Here's the code



DEFINE OSC 20
CLEAR

DEFINE ADC_BITS 8 ' Set number of bits in result
DEFINE ADC_CLOCK 3 ' Set clock source (rc = 3)
DEFINE ADC_SAMPLEUS 50 ' Set sampling time in microseconds

INCLUDE "DT_INTS-14.bas" ; Base Interrupt System
INCLUDE "SPWM_INT.bas" ; Software PWM module

DEFINE SPWM_FREQ 100 ; SPWM Frequency
DEFINE SPWM_RES 256 ; SPWM Resolution

D var byte

DutyVars VAR BYTE[3] ; DutyCycle Variables
;DutyVar1 VAR DutyVars[0] ; group them in an array for easy access
;DutyVar2 VAR DutyVars[1] ; with FOR loops etc.
DutyVar3 VAR DutyVars[2]

ASM
SPWM_LIST macro ; Define Pin's to use for SPWM
;SPWM_PIN GPIO, 0, _DutyVar1 ; and the associated DutyCycle variables
; SPWM_PIN GPIO, 1, _DutyVar2 ; Notice the underscore before variables
SPWM_PIN GPIO, 2, _DutyVar3
endm
SPWM_INIT SPWM_LIST ; Initialize the Pins
ENDASM

ASM
INT_LIST macro ; IntSource, Label, Type, ResetFlag?
INT_Handler TMR1_INT, SPWMhandler, ASM, yes
endm
INT_CREATE ; Creates the interrupt processor
ENDASM

@ INT_ENABLE TMR1_INT ; enable Timer 1 interrupts

;_________________________________________________ ____________________________

Main:
ADCIN 0, D
DutyVar3 = D
GOTO Main



Using a close loop fedback output stage and a 12v regulated supply for the track as per the diagram attached, I get a nice smooth slow speed control. This is using the 12F675 with its internal osc.

The loco does growl a bit when at really slow speed... and at maximum speed its fine for a goods train, but not an express. I susspect that using a higher track supply voltage will resolve the speed issue (my DVM reads 6.5v across the track at full speed), but wondered if there was anything I could do to reduce the growling at slow speed.

Please bear in mind that I'm still somewhat new to PICs and programming.. so If I've still overlooked something in the settings then please advise what I did wrong and how to correct it.

Darrel Taylor
- 15th February 2007, 11:59
Hmm, I don't see the CMCON and ANSEL in your program.

There's a R-M-W (Read-Modify-Write) problem when OUTPUTting to a pin set to Analog. It adds a high frequency component to the PWM signal.

I don't know if that's what is causing the growling or not.

6.5V at full speed? That doesn't sound right. The current is getting limited somewhere. Maybe if you increased the value of R4 ????
<br>

malc-c
- 15th February 2007, 12:49
Hmm, I don't see the CMCON and ANSEL in your program.

There's a R-M-W (Read-Modify-Write) problem when OUTPUTting to a pin set to Analog. It adds a high frequency component to the PWM signal.


Would the following be correct


TRISIO.2 = 0 'Set GPIO.2 to output.
ANSEL.2 = 0 'Set GPIO.2 to digital
GPIO.0 = 1 'gpio.0 set to input
VRCON = 0 ' Voltage reference disabled
OPTION_REG.7 = 0



6.5V at full speed? That doesn't sound right. The current is getting limited somewhere. Maybe if you increased the value of R4 ????


I'll try that and see what happens, thanks for the suggestion

Acetronics2
- 15th February 2007, 13:22
Hi, Malc

I do not know where you found R4 and D1 ... but your problems come from there.

No real use for them ... so, back to their drawer will be the best.

... or use another Pic pin if you want to do something with the freewheel emf !!!

a simpler output stage would be welcome ( your NPN Emitter to ground and a series 1 k in the base connection i.e. )

Alain

malc-c
- 15th February 2007, 13:46
Alain,

Thanks for the suggestion... the output circuit was taken from a book and is actually a cloose-loop feedback controller... I just fed the output from the PIC directly to the base of the NPN tranny... but I'll try your suggestions and see if it improves the max speed settings. However in its current state it makes for an excellent branch line controller where slower trains would run...

To give you some idea of the excellent slow speed the PWM gives have a look at this video I've uploaded http://www.micro-heli.co.uk/controller.avi (9mb DIVx format)

malc-c
- 15th February 2007, 14:10
Omitting the feedback section (R4 and 1N4148), and adding a 1K base resistior I now get a good range of speed and excellent slow speed crawling. Just need to resolve the growling in the armature

Acetronics2
- 15th February 2007, 14:44
Hi, Malc,

The only way is to increase the PWM frequency ( 500 or 1000 Hz might be enough ).
also Think to the minimum PWM ratio zone to skip ( ~ 10 % )

you'll find a problem here : some motors do not like high frequencies ( > 3000 Hz ) due to their high inductance ... and might overheat.

Do you think I could make a test with my Big Boy, die cast "crocodile" or JEP 231 ... or some oldies ???

Hé,hé ... my father gave its life and brain to our national railway company ...and still builds custom models ( 84 years ...the papy !!! )

Alain

malc-c
- 15th February 2007, 15:59
Well I've been playing with the values for SPWM frequency and resolution and found the highest setting for the 12F675 using internal osc was around


DEFINE SPWM_FREQ 200 ; SPWM Frequency
DEFINE SPWM_RES 256 ; SPWM Resolution


Its not possible to up the resolution without using an external OSC. However I intend to use a different PIC and may opt to use it at is max xtal rating, especially if I use the one PIC to provide all 4 channels. Maybe the higher resolution will reduce the grumbling in the armature... mind you if this was on old 0-6-0 shunter it would look and sound just right :)

One thing I did notice is that when using the PWM version the power tranny runs cold, where with the close loop version it warmed up (slightly)

Anyway, I'm having fun learning ;)

malc-c
- 15th February 2007, 16:16
There's a R-M-W (Read-Modify-Write) problem when OUTPUTting to a pin set to Analog. It adds a high frequency component to the PWM signal.

That's interesting... whilst I was reading up on the use of your code I could hear this high pitched (estimated 4 - 8 Khz) faint sound like you often hear eminating from a TV... placed my ear near the loco (which is standing still on the track) and its singing away !!

I presume that this is due to the fact that GPIO.2 is still set to analogue and not digital ??

What config settings should I use for CMCON and ANSEL to resolve this ?

mister_e
- 15th February 2007, 17:46
in theory the right setting have to be


ANSEL=%00110001
CMCON=7
GPIO=0
TRISIO=1


and later i just change the main loop to...


Main:
ADCIN 0, DUTYVAR3
GOTO Main


AND NOW it's working pretty good and smooth... well here...

For once i found a use of the Left-Justified results... Never thought ADCIN handled it :D

Make sure your Pot impedance meet the maximum recommended on.. 2.5 k if my memory serves me well. 10K here (EasyPic 4) still work fine..

Also, as the ADC results is a 8 bit result, you should change the SPWM_RES to 255.

malc-c
- 15th February 2007, 18:59
Steve, Thanks for your input. I made the changes you suggested and the performance is still great and the growling sound produced by the PWM in the armature appears less noticable. The high pitched sound is still noticable, but nothing appears hot

mister_e
- 15th February 2007, 19:08
Unfortunately i don't have anything like that here to test, but Maybe the PWM have to be smooth first...

what happen if you place a big capacitor (470 & up) in parallel with the motors?

What happen if you place a capacitor (few uF) on the mosfet gate pin? (transistor base)

What happen if you use a variable voltage regulator (or PSU)? instead of PWM?

malc-c
- 15th February 2007, 20:02
Unfortunately i don't have anything like that here to test, but Maybe the PWM have to be smooth first...

what happen if you place a big capacitor (470 & up) in parallel with the motors?


Tried both high (1000uf) and low (100uf) - the loco won't move


What happen if you place a capacitor (few uF) on the mosfet gate pin? (transistor base)

Tried, 1uf to 10uf. with a 1uf the growling was less noticable, but the slow speed control became less. Increasing this to 10uf and the loco had almost no ability to crawl.


What happen if you use a variable voltage regulator (or PSU)? instead of PWM?

Don't know as I don't have a varible regulator to hand.. what would be the advantage of using one over using a pot accross the supply with the wiper connected to the base of the NPN tranny ?

mister_e
- 15th February 2007, 20:17
what's your actual schematic?

how much current your motor need?

malc-c
- 15th February 2007, 20:47
Typically these loco's draw around 300mA - 600mA ( a quick test showed mine drawing 380mA with no coaches at full throttle )

The schematic as it stands is attchaed

Darrel Taylor
- 16th February 2007, 06:29
Saw the video.

I've seen snails move faster than that, when it's raining. :)

Cool.

Hope someone can figure out the Growl.

malc-c
- 16th February 2007, 09:37
Saw the video.

I've seen snails move faster than that, when it's raining. :)

Cool.

Hope someone can figure out the Growl.

LOL - thanks !

I'm not too bothered about the noise the PWM makes, but as this will be used on a club lauout, other members might complain...

Acetronics2
- 16th February 2007, 09:44
Typically these loco's draw around 300mA - 600mA ( a quick test showed mine drawing 380mA with no coaches at full throttle )

The schematic as it stands is attchaed

Hi, Malc,

R3 is no use at all here ... short it !!!

... but a 1N 540x cathode at the + 12v, anode on the V+ output could be rather useful ...

Alain

PS ... for Growling, may be you could try to " unsharpen" the PWM to somewhat with increased rise and fall time ... by inserting a filtering coil in series in the output line ( a LITTLE smoothing capacitor too ??? )

malc-c
- 16th February 2007, 09:56
Hi,

Don't have that Diode suggested, have plenty of 1N4148's or 1N4001 to hand, would they do ?

Acetronics2
- 16th February 2007, 10:58
The 4001 will be a bit too weak ... for serious use.

try to find a 3A rated model ... or use a PNP Darlington with diode Built in !!! like BD678/680

Alain

Acetronics2
- 16th February 2007, 12:52
Hi, Malc

Some more food for your brain :

http://www.manhattancontrols.com/forums/circuit-ed/viewtopic.php?t=4

Alain

malc-c
- 16th February 2007, 12:59
OK I thought, lets move this on and use a PIC capable of providing all 4 seperate PWM outputs. So after consultation via a few PMs with Steve and Darrel I've opted for a 16F676.

I've used a 20Mhz xtal, with 22pf caps between pins 2 and 3, wiper from 10K pot goes to pin 13 and PWM output on pin 8.

I've modified the code used for the 12F675, and compiled - no errors or warning, and loaded it into the PIC.


@ __CONFIG _HS_OSC & _WDT_ON & _PWRTE_ON & _MCLRE_OFF

ANSEL=%00110001
CMCON=7
TRISA=%11111111 'set PORTA as all input
TRISC=%00000001 'set PORTC as all output apart from RC0


DEFINE OSC 20
CLEAR

DEFINE ADC_BITS 8 ' Set number of bits in result
DEFINE ADC_CLOCK 3 ' Set clock source (rc = 3)
DEFINE ADC_SAMPLEUS 50 ' Set sampling time in microseconds

INCLUDE "DT_INTS-14.bas" ; Base Interrupt System
INCLUDE "SPWM_INT.bas" ; Software PWM module

DEFINE SPWM_FREQ 100 ; SPWM Frequency
DEFINE SPWM_RES 255 ; SPWM Resolution

DutyVars VAR BYTE[3] ; DutyCycle Variables
DutyVar1 VAR DutyVars[0] ; group them in an array for easy access
DutyVar2 VAR DutyVars[1] ; with FOR loops etc.
DutyVar3 VAR DutyVars[2]
DutyVar4 VAR DutyVars[3]

ASM
SPWM_LIST macro ; Define Pin's to use for SPWM
SPWM_PIN PORTC, 2, _DutyVar1 ; and the associated DutyCycle variables
SPWM_PIN PORTC, 3, _DutyVar2 ; Notice the underscore before variables
SPWM_PIN PORTC, 4, _DutyVar3
SPWM_PIN PORTC, 5, _DutyVar4
endm
SPWM_INIT SPWM_LIST ; Initialize the Pins
ENDASM

ASM
INT_LIST macro ; IntSource, Label, Type, ResetFlag?
INT_Handler TMR1_INT, SPWMhandler, ASM, yes
endm
INT_CREATE ; Creates the interrupt processor
ENDASM

@ INT_ENABLE TMR1_INT ; enable Timer 1 interrupts

;_________________________________________________ ____________________________

Main:
ADCIN 0, DUTYVAR1
ADCIN 1, DUTYVAR2
ADCIN 2, DUTYVAR3
ADCIN 3, DUTYVAR4
GOTO Main



I then tested the code / hardware and I don't get the same performance as I did with the 12F. There is no responce from the loco until the pot is at mid point, at this stage the armature sings with a high pitch noise. Advancing the pot increases the speed, but I don't get anywhere like the slow crawl speeds I got with the 12F. I can also assume that the armature is warming as it smelt a little (carbon smell) after a short run.

I think its probably down to my poor understanding of Ansel etc.. so an constructive comments would be welcome.

Oh and I've not changed the driver stage yet as Alain suggested.

EDIT:: EDIT::
Changed the Xtal for a 4Mhz and the frequency of the noise has dropped.. but its still there and not the low growl that was produced by the 12F.. so it it a timing issue ??

malc-c
- 16th February 2007, 13:29
I've also tried the other channels, and get the same performance and noise from each one. (I've also reduced the frequency down to 100 to make sure I get 4 channels) - and I'm using the int osc to compare it against the 12F

I've noticed that the growling from the armature has a second resonating sound that I can only describe as the sound you get with a multi-engine prop plane when the engine is slightly out of sync. I can only assume this is due to the PIC having to work hard outputing to 4 channels rather than the 1 on the 12F.

If all else fails, I'll use a 12F675's to drive each of the 4 controllers... overkill I know, but the performance I was getting with the 12F was just what I was after.

I'm hoping the issue with the 16F676 is due to a conflict of configuring the ports to the correct analogue / a2d / digital combination, and with your help, will work as good as the 12F !

mister_e
- 16th February 2007, 13:40
There's something bad in the schematic indeed. R3 have it's use... but not at the good place. Should be in serie with the transistor base. If you short it, you'll burn the transistor...

I'm curious.. i'll try to find some 12V motor (1A or more) 'round here today, and test the whole thing. Sure it's possible.

I'll dig in the transistor datasheet... sure there's something bad in their HFe mathe here....

Anyways, i'll be back!

Acetronics2
- 16th February 2007, 13:48
There's something bad in the schematic indeed. R3 have it's use... but not at the good place. Should be in serie with the transistor base. If you short it, you'll burn the transistor...

Anyways, i'll be back!

Hi, Steve

Did you notice a 1K resistor had magically appeared in series with the trans. base ??? ...

Strong coffee needed ... Malc is a one not so easy to follow !!!

The output schematic can be enough for this time ... let's see one problem at a time !!!

Inserting some PAUSE ( 100-200 ms ) between inputs pollings might do something interesting here ... let's try that first

Alain

malc-c
- 16th February 2007, 14:16
Hi, Steve

Did you notice a 1K resistor had magically appeared in series with the trans. base ??? ...

Alain, the 1K base resistor was added way back after you suggested in post #46 that I removed the R4/D1 combo and and a series 1 k in the base connection

The nearest shematic I have is as detailed in post #57 - apart from the fact that I'm using a 16F676 rather than the 12F675 - the output stage is the same, I've not changed anything since, and wouldn't edit posts to suit...

Darrel Taylor
- 16th February 2007, 14:23
Malcolm,

I've got it running here on a 16F676. But...

You have a POT input on AN3, which is also the OSC2 for the crystal.

If I comment out the ADCIN 3, DUTYVAR4 then it seems to run fine.
But with that statement in there it goes wacko.
<br>
Added: ANSEL needs to be changed too, but I'll wait to see where you move the AN3 to.

malc-c
- 16th February 2007, 14:43
Whoops !

Thanks for spotting my deliberate ;) mistake !!!!

Thanks for the PM, I've created another copy of the code and downloaded the DT_int 18 file, the following compiles OK but I have to use a different programmer for pics with 18 pins or more and I've never had much luck with 18F2550's and this programmer as Steve will vouch !!

I'll try some changes for the 16F676 and see how I get on.. Thanks to everyone again for your assistance...

malc-c
- 16th February 2007, 14:48
Malcolm,

ANSEL needs to be changed too, but I'll wait to see where you move the AN3 to.

I actually marked it on the datasheet pinout to use AN4 (pin 10) on the 16F676 - I should pay more attention to what I plan !!

Acetronics2
- 16th February 2007, 15:02
Alain, the 1K base resistor was added way back after you suggested in post #46 that I removed the R4/D1 combo and and a series 1 k in the base connection

The nearest shematic I have is as detailed in post #57 - apart from the fact that I'm using a 16F676 rather than the 12F675 - the output stage is the same, I've not changed anything since, and wouldn't edit posts to suit...

We're in sync Malc ... just R3 NOT to be shorted !!! ... but placed in series with the NPN COLLECTOR ...

MEA Culpa ...

Alain

Darrel Taylor
- 16th February 2007, 15:03
AN4, ok.

Make ANSEL = %00010111
<br>

malc-c
- 16th February 2007, 15:45
AN4, ok.

Make ANSEL = %00010111


Darrel, can you confirm that I have understood the variables for SPWM_PIN right, and that I'm using the correct channels for a/d, as I only had 2 out of 4 outputs working right, and now made changes I get that high frequency noise from the armature (where as before it was a low growl, even with a 20 Mhz xtal)

I want to use the following pins on the 16F676 for inputs from 10K pots, and their corresponding PWM outputs

Pot 1 - Pin 13 - AN0 - controlling output on pin 8 - RC2
pot 2 - Pin 12 - AN1 - controlling output on pin 5 - RC5
pot 3 - Pin 11 - AN2 - controlling output on pin 6 - RC4
pot 4 - Pin 10 - AN4 - controlling output on pin 7 - RC3

so I've set up SPWM_PIN as


SPWM_LIST macro ; Define Pin's to use for SPWM
SPWM_PIN PORTC, 2, _DutyVar1 ; and the associated DutyCycle variables
SPWM_PIN PORTC, 5, _DutyVar2 ; Notice the underscore before variables
SPWM_PIN PORTC, 4, _DutyVar3
SPWM_PIN PORTC, 3, _DutyVar4


And have the main program as


Main:
ADCIN 0, DUTYVAR1
ADCIN 1, DUTYVAR2
ADCIN 2, DUTYVAR3
ADCIN 4, DUTYVAR4
GOTO Main


I'm assuming the value of ANSEL is incorrect as its ommitting that high frequency noise. Given the above info, which I hope is clear, what would be the correct value for ANSEL, or have I made another boo boo in assignig the pins ?

By the way, prior to the change I had it running really well on CH1 - you thought that on a 12F @ 4mhz the loco was slow.... wait to you see the video for it running on a 16F @ 20 mhz !! - its just amazing !!

malc-c
- 16th February 2007, 17:00
Darrel,

Here is that video - http://www.micro-heli.co.uk/controller2.avi

I've left the audio element in so you guys can hear the growling the loco makes, the downside is that this has made the file 24MB

Acetronics2
- 16th February 2007, 18:00
No secret, Malc ...

PWM freq too low.
( may be also a poor quality motor too ... but you can't choose which will be used.)

Alain

Archangel
- 16th February 2007, 18:41
Tried both high (1000uf) and low (100uf) - the loco won't move
Tried, 1uf to 10uf. with a 1uf the growling was less noticable, but the slow speed control became less. Increasing this to 10uf and the loco had almost no ability to crawl.

4 - 8 kc whine? have you tried going even smaller? say .1 or .01 uf ? There is an outside chance you are not hearing the direct frequency in those motor coils but rather a beat frequency from the difference between 2 frequencies in which case you may be looking at bypassing RF.<br> I would bypass the motor from each power lead to the case too.

malc-c
- 16th February 2007, 19:28
Thanks for the suggestion, a tad over my head, but I think I follow your drift.

Darrel / Steve,
I've noticed that if I advance the pot fully (thus taking the A/D input pin to supply) and then turn it back down the loco stays at full speed, and the only way to correct this is to disconecct and reconnect the supply. - any suggestions (could this be down to the wrong setting for ANSEL)

malc-c
- 16th February 2007, 19:32
No secret, Malc ...

PWM freq too low.
Alain

The max setting I can use seems to be 190 for freqency, 255 for resolution, with an OSC value of 20

malc-c
- 16th February 2007, 19:46
I've been trying to phathom out what I need to set ANSEL to or whats wrong with the code to get this to work 100%.

Referring to my post #74, I have three PWM outputs, but when I connect pot 4 to pin 10 and the corresponding output (pin 7 RC3) the loco just shoots off at full speed with no control - Here's the code



@ __CONFIG _HS_OSC & _WDT_ON & _PWRTE_ON & _MCLRE_OFF


;ANSEL = %00010111 - dt suggested value
ANSEL=%00110001 ; original
CMCON=7
TRISA=%11111111 'set PORTA as all input
TRISC=%00000001 'set PORTC as all output apart from RC0


DEFINE OSC 20
CLEAR

DEFINE ADC_BITS 8 ' Set number of bits in result
DEFINE ADC_CLOCK 3 ' Set clock source (rc = 3)
DEFINE ADC_SAMPLEUS 50 ' Set sampling time in microseconds

INCLUDE "DT_INTS-14.bas" ; Base Interrupt System
INCLUDE "SPWM_INT.bas" ; Software PWM module

DEFINE SPWM_FREQ 190 ; SPWM Frequency
DEFINE SPWM_RES 255 ; SPWM Resolution

DutyVars VAR BYTE[3] ; DutyCycle Variables
DutyVar1 VAR DutyVars[0] ; group them in an array for easy access
DutyVar2 VAR DutyVars[1] ; with FOR loops etc.
DutyVar3 VAR DutyVars[2]
DutyVar4 VAR DutyVars[3]

ASM
SPWM_LIST macro ; Define Pin's to use for SPWM
SPWM_PIN PORTC, 2, _DutyVar1 ; and the associated DutyCycle variables
SPWM_PIN PORTC, 5, _DutyVar2 ; Notice the underscore before variables
SPWM_PIN PORTC, 4, _DutyVar3
SPWM_PIN PORTC, 3, _DutyVar4
endm
SPWM_INIT SPWM_LIST ; Initialize the Pins
ENDASM

ASM
INT_LIST macro ; IntSource, Label, Type, ResetFlag?
INT_Handler TMR1_INT, SPWMhandler, ASM, yes
endm
INT_CREATE ; Creates the interrupt processor
ENDASM

@ INT_ENABLE TMR1_INT ; enable Timer 1 interrupts

;_________________________________________________ ____________________________

Main:
ADCIN 0, DUTYVAR1
ADCIN 1, DUTYVAR2
ADCIN 2, DUTYVAR3
ADCIN 4, DUTYVAR4
GOTO Main




Here's hoping someone can point e in the right direction

malc-c
- 16th February 2007, 20:42
Ok I think I now understand the settings for ANSEL. Reading the datasheet again


ANSEL — ANALOG SELECT REGISTER (ADRESS: 91h) (PIC16F676 ONLY)

ANS7 ANS6 ANS5 ANS4 ANS3 ANS2 ANS1 ANS0
bit 7 bit 0
bit 7-0: ANS<7:0>: Analog Select between analog or digital function on pins AN<7:0>, respectively.
1 = Analog input. Pin is assigned as analog input.(1)
0 = Digital I/O. Pin is assigned to port or special function.


So if I wanted all analogue I set ANSEL to 11111111 - all digital 00000000

Ergo to set AN0, AN1, AN2 and AN4 Ansel should = 00010111, which is exactly what Darrel suggested. However when compiled with this setting the 4th output still runs at full speed with no control.

Could it be that the issue is with the declaration of the array - as it has [3] and I would assume that there are 4 channels so maybe this should be [4] ??




Could it be that the issue is with the declaration of the array - as it has [3] and I would assume that there are 4 channels so maybe this should be [4] ??

Looked like that was teh cause - I now have 4 working channels... just need to resolve the issue of the PIC locking on at full throttle and I'm done !

Darrel Taylor
- 16th February 2007, 23:46
Boy. Try to get some sleep, and people start talking to themselves. :D

Looks like the guy you were talking to, helped figure a couple things out though. :)

Good catch on the array size. Didn't see that.

Heard the video. That's just nasty sounding.
Is it any better yet after the changes?

I know you were told to change SPWM_RES to 255, but it really should be 256 for 8-bit resolution. Maybe the cause of the "PIC locking on at full throttle". I'll play with it here too and see.
<br>

Darrel Taylor
- 17th February 2007, 01:41
After further playing.

I can't make it "Lock".

Tried all 4 channels, tried 255/256 RES.

Incidently, 255 does work better. It's not the way I thought I wrote it. But... :o

That way 0 is always off, and 255 is always on.
<br>

malc-c
- 17th February 2007, 09:49
Darrel,

If using an LED its hard to make it lock. I think its either related to the power supply I'm using, or some other factor within the circuit as it does it on several loco's. I have a 0.1uf spread accros the power pins of the PIC, and power rails in a bid to decouple the supply. I've also tried changing the 1K base resistor between the NPn and PIC output as I though that the driver circuit may be drawing more than the 25ma the port can take, but that made no difference :(

Is the PWM outout a square wave, sawtooth or just spikes that are increased in frequency? I would like to stick with PWM as there is less heat to dissapate in the circuit and it provides far better slow starts than varible voltage type controllers. Maybe I should look at using a PIC with hardware PWM, like the 16F690 ??

Darrel Taylor
- 17th February 2007, 12:59
Definately Squarewave. This is about a third of the way on the POT.
http://www.pbpgroup.com/files/PWM_Scope.jpg

Well, before you change pics. Can you give this program a quick try.
It's just a single channel, no interrupts. It runs at about 3.8khz

It should give an indication whether the higher frequencies of hardware PWM will help or not.
@ __CONFIG _HS_OSC & _WDT_ON & _PWRTE_ON & _MCLRE_OFF
DEFINE OSC 20
CLEAR
ANSEL=%00110001
CMCON=7
TRISA=%11111111 'set PORTA as all input
TRISC=%00000001 'set PORTC as all output apart from RC0

PWM1 VAR PORTC.2
DutyCycle1 VAR WORD
GoDone VAR ADCON0.1
ADCON1 = %00110000
ADCON0 = %00000011
while GoDone : wend

Main:
if ADRESH > 1 then
high PWM1
DutyCycle1 = ADRESH
GoDone = 1
pauseUS DutyCycle1
low PWM1
pauseUS 255 - DutyCycle1
while GoDone : wend
else
low PWM1
GoDone = 1
while GoDone : wend
endif
goto Main

mister_e
- 17th February 2007, 16:58
as long as the POT impedance meet the maximum recommended.. it shouldn't be much of a problem.

What happen to your supply when you plug your loco directly?

Now, If you add 1 or more?

Now do the same but add your transistor to drive them.. what happen?

i got my few motor here, i'll do some test later.

mister_e
- 17th February 2007, 19:10
Well well well... running 3 different Motor type from 500mA to 10A @12Vdc.. and a pretty messed up breadboard + Jumper :eek: it works

2 channel PWM... all square...

3 pwm ... still the same, life is good

BUT... when you add ADCIN 4, DutyVar4... somethings goes bad....

Do one test with anything matched with ADCIN 4... something go really bad... where it comes from... i don't know for now.

Same thing happen if you do something with DutyVar4...

scratch scratch scratch

mister_e
- 17th February 2007, 19:23
Everything just fine using...


@ __CONFIG _HS_OSC & _WDT_ON & _PWRTE_ON & _MCLRE_OFF


ANSEL = %00010111 ; - dt suggested value



DEFINE OSC 20
CMCON=7
TRISA=%11111111 'set PORTA as all input
TRISC=%00000001 'set PORTC as all output apart from RC0

DEFINE ADC_BITS 8 ' ADCIN resolution (Bits)
DEFINE ADC_CLOCK 2 ' ADC clock source (Fosc/32)
DEFINE ADC_SAMPLEUS 11 ' ADC sampling time (uSec)

INCLUDE "DT_INTS-14.bas" ; Base Interrupt System
INCLUDE "SPWM_INT.bas" ; Software PWM module

DEFINE SPWM_FREQ 150 ; SPWM Frequency
DEFINE SPWM_RES 255 ; SPWM Resolution

DutyVar VAR byte[4]

ASM
SPWM_LIST macro ; Define Pin's to use for SPWM
SPWM_PIN PORTC, 2, _DutyVar ; and the associated DutyCycle variables
SPWM_PIN PORTC, 5, _DutyVar+1 ; Notice the underscore before variables
SPWM_PIN PORTC, 4, _DutyVar+2
SPWM_PIN PORTC, 3, _DutyVar+3
endm
SPWM_INIT SPWM_LIST ; Initialize the Pins
ENDASM

ASM
INT_LIST macro ; IntSource, Label, Type, ResetFlag?
INT_Handler TMR1_INT, SPWMhandler, ASM, yes
endm
INT_CREATE ; Creates the interrupt processor
ENDASM

@ INT_ENABLE TMR1_INT ; enable Timer 1 interrupts

;_________________________________________________ ____________________________

Main:
ADCIN 0, DUTYVAR[0]
ADCIN 1, DUTYVAR[1]
ADCIN 2, DUTYVAR[2]
ADCIN 4, DUTYVAR[3]
GOTO Main

GO GO GO FIGURE IT ;)

malc-c
- 17th February 2007, 19:44
Well, before you change pics. Can you give this program a quick try.
It's just a single channel, no interrupts. It runs at about 3.8khz

It should give an indication whether the higher frequencies of hardware PWM will help or not.
@ __CONFIG _HS_OSC & _WDT_ON & _PWRTE_ON & _MCLRE_OFF
DEFINE OSC 20
CLEAR
ANSEL=%00110001
CMCON=7
TRISA=%11111111 'set PORTA as all input
TRISC=%00000001 'set PORTC as all output apart from RC0

PWM1 VAR PORTC.2
DutyCycle1 VAR WORD
GoDone VAR ADCON0.1
ADCON1 = %00110000
ADCON0 = %00000011
while GoDone : wend

Main:
if ADRESH > 1 then
high PWM1
DutyCycle1 = ADRESH
GoDone = 1
pauseUS DutyCycle1
low PWM1
pauseUS 255 - DutyCycle1
while GoDone : wend
else
low PWM1
GoDone = 1
while GoDone : wend
endif
goto Main


Interesting..... works fine, no drop out or locking up after 20 or so tests. However the noise from the armature when starting is very loud and high pitched, with harmonics as you increase the throttle.

I tried reming out the last two channels as Steve suggested with the original code and I still experienced problems... but this new code works.

mister_e
- 17th February 2007, 20:22
Malc,
it's little bit more than rem ADCIN line. i'll place all the changes i made in RED



@ __CONFIG _HS_OSC & _WDT_ON & _PWRTE_ON & _MCLRE_OFF


ANSEL = %00010111 ; - dt suggested value



DEFINE OSC 20
CMCON=7
TRISA=%11111111 'set PORTA as all input
TRISC=%00000001 'set PORTC as all output apart from RC0

DEFINE ADC_BITS 8 ' ADCIN resolution (Bits)
DEFINE ADC_CLOCK 2 ' ADC clock source (Fosc/32)
DEFINE ADC_SAMPLEUS 11 ' ADC sampling time (uSec)

INCLUDE "DT_INTS-14.bas" ; Base Interrupt System
INCLUDE "SPWM_INT.bas" ; Software PWM module

DEFINE SPWM_FREQ 150 ; SPWM Frequency
DEFINE SPWM_RES 255 ; SPWM Resolution

DutyVar VAR byte[4]

ASM
SPWM_LIST macro ; Define Pin's to use for SPWM
SPWM_PIN PORTC, 2, _DutyVar ; and the associated DutyCycle variables
SPWM_PIN PORTC, 5, _DutyVar+1 ; Notice the underscore before variables
SPWM_PIN PORTC, 4, _DutyVar+2
SPWM_PIN PORTC, 3, _DutyVar+3
endm
SPWM_INIT SPWM_LIST ; Initialize the Pins
ENDASM

ASM
INT_LIST macro ; IntSource, Label, Type, ResetFlag?
INT_Handler TMR1_INT, SPWMhandler, ASM, yes
endm
INT_CREATE ; Creates the interrupt processor
ENDASM

@ INT_ENABLE TMR1_INT ; enable Timer 1 interrupts

;_________________________________________________ ____________________________

Main:
ADCIN 0, DUTYVAR[0]
ADCIN 1, DUTYVAR[1]
ADCIN 2, DUTYVAR[2]
ADCIN 4, DUTYVAR[3]

GOTO Main

Now for the noise, to me, as i'm not a motor pro, there's something normal in that. Your motor have a comfort zone in which he can operate. So if you're under that (let's call it threshold, lower possible voltage or else), for sure he will yell. It has to fight the inertia.. (OK OK probably not the right term... but it's how i understand :D )

Now, is this louder using PWM or not? this is why i asked for a variable supply before.

If it's better, we could still redesign the whole thing... same thing if you find a PWM frequency which reduce the noise.

Time for few tests on your side... even if you use few battery in serie ;)

malc-c
- 17th February 2007, 21:41
Guys,

Firstly may I say that I admire both DT and Steve's skills in programming, and want to thank you both for staying with this. - I'm feeling way out of my depth here, and all I can do is test the code you offer, and report back.

Ok power supply:
240v primary - 12-0-12 secondry 500mA transformer. Rectified using 4 x 1N4004 diodes, regulated via 7812, 7912 1A regulators, with 1000uf capacitors to give smoothed +12 and -12v supply. Then a 7805 is used off the +12v to give +5 line. 0v taken from the centre tap. Actual voltages measured are +4.94v, +11.84 and -11.86.
+5v used for the PIC, +12v used for the motor supply - 0v commoned to both

Code.
I compiled Darrels code, and no matter what I tried I couldn't replicate the latching or drop out (ie the loco would just stop and not respond) when advancing and retarding the 10K lin pot in quick succession. However even with a 4 Mhz xtal the whine from the motor was loud

Compiling Steves code I got the low growl rather than a whine, but it was a lot less noticable than DT's original code. But advancing and retarding the pot as before still caused the lock up / drop outs.

Voltage measurements:
When advancing and retarding the pot quickly between min and max the voltage drop on the +5v line to the pic was less than 0.03v (4.94 - 4.93 was read), so its not enough to cause the PIC to stop running. The drop on the +12v line was a little more, but not drastic, with the lowest reading being 10.56, so the peak drop of around 1.4v.

To varify that it is the PIC that is locking up and not the output stage, I placed an LED on the output of the PIC, and this would stay illuminated when a lock up occured, even when the loco was removed. I also removed the connection between the PIC and the base of the NPN tranny to see if the LED would go out and it had no affect, so it would appear that the driver side isn't causing the issue.

Hope this feedback helps.

malc-c
- 17th February 2007, 22:37
I feel so embarrased... but I think the problem of the drop outs etc is down to the powersupply.

To rule the PSU out I've just used the previously described PSU to power the 12v driver circuit, but used a 5v regulated switch mode wall PSU for the PIC. This was running at 5.12v. I had to common up the ground lines to get the loco to move, which also caused a bit of pulsing in the armature even with the pot at zero, but I couldn't get the lock up or drop out no matter what I tried.

So a re-think on the design of the PSU is in order.

Darrel Taylor
- 17th February 2007, 22:55
Grreat!

One by one, knocking out the problems.

As for sticking with it, I'll stick with anyone that put's in the effort. Like you.
Thanks for making it fun.

Steve,
Do you hear the whining etc in your motors?
Just wondering if it's the type of motor that makes a difference.
<br>

mister_e
- 17th February 2007, 23:35
Yeah that's what i thought too, hence why i buy few different model.

Well, yes i hear some little noise which is more or less louder depending of the model... but there's always some noise when you play around the minimum low-voltage threshold.

I tried higher PWM frequencies and it may cure some part of the problem on some voltage range and on some motor model. but it's certainly not perfect on ALL motor i have here.

To me, in this specific case, a better choice could be to use some kind of linear regulation. Something around the following.

<img src="http://www.picbasic.co.uk/forum/attachment.php?attachmentid=1396&stc=1&d=1171755105">

it have some good point and some bad ones. But do you really a 0-100% regulation? mmm

Malc, don't worry... it's an interesting and funny thread.

An idea... we could skip the PWM and use some I2C DAC...

malc-c
- 18th February 2007, 00:38
Grreat!

One by one, knocking out the problems.

As for sticking with it, I'll stick with anyone that put's in the effort. Like you.
Thanks for making it fun.

Thanks Darrel,

I'm always willing to put effort in to these projects, and I've learnt a lot over the course of this thread. I just feel a tad embarrased that I didn't try two seperate power supplies earlier and kept pointing the finger at the code...

Mind you, hopefully the use of your PWM routines in this application may of hi-lighted some areas such as the armature noise, that you may want to look at for future verions.

As for the motors, I have four 2mm scale locos, two are circa 18 years old with an open frame 5 pole motors, the others are less than a year old and both have small can motors... guess which ones produce the better running... yup the older ones !!

As a side note, when I tried your last bit of code I was using a 4mhz Xtal, I then tried it with a 20mhz and it was quite painful, for my ears and the motor !!

Anyway, thanks once again to you and Steve for all your help. To everyone else who's been reading this, sorry if it bored you at times :)

Acetronics2
- 18th February 2007, 10:20
Yeah that's what i thought too, hence why i buy few different model.

Well, yes i hear some little noise which is more or less louder depending of the model... but there's always some noise when you play around the minimum low-voltage threshold.

I tried higher PWM frequencies and it may cure some part of the problem on some voltage range and on some motor model. but it's certainly not perfect on ALL motor i have here.

To me, in this specific case, a better choice could be to use some kind of linear regulation. Something around the following.

<img src="http://www.picbasic.co.uk/forum/attachment.php?attachmentid=1396&stc=1&d=1171755105">

it have some good point and some bad ones. But do you really a 0-100% regulation? mmm

Malc, don't worry... it's an interesting and funny thread.

An idea... we could skip the PWM and use some I2C DAC...

Hi, Steve

Your design is to try with a low input RC constant in order to produce some kind of trapezoidal wave ... instead of the beautiful square wave.

the problem lays in the slew-rate ... remember lentz's law ... the motor windings oppose an "electrical inertia" proportionnal to the slew-rate ...

that will create some dissipation in the ballast ... but make less noise and heat.

may be some "Mid freq" rectified sinus, used in burst mode could also do the job with minimal issues ( seen on the motor side ... LOL !!! )



Alain

mister_e
- 18th February 2007, 10:46
My motor theory is far far away... and never felt the need to understand it in the past :D

interesting... thanks.

Few interesting points in the followings ...
http://homepages.which.net/~paul.hills/SpeedControl/SpeedControllersBody.html ok ok it's talking about a starter but anyways..

http://ww1.microchip.com/downloads/en/AppNotes/00770b.pdf

malc-c
- 21st February 2007, 19:03
Guys,

Just thought you might want to see the prototype controler (only two channels)

http://www.micro-heli.co.uk/trainboard.jpg

The 10K pot and reversing switch is connected via the 6-pin header infront of the power transistors. I've also left room for a small heatsink, but in tests so far these don't get hot enough to warrant one !

The only problem is I'm still waiting on some 16F676's as I fried the only one i had in the breadboard... (got distracted by a phone call and connected the +12v to the PIC rather than the +5v !!! - it was glowing and had to cut short the call to pull the plug !!) - Tested the output stage and it works fine so can't see any reason for it not to work when the PIC's arrive.

mister_e
- 21st February 2007, 19:08
The only problem is I'm still waiting on some 16F676's as I fried the only one i had in the breadboard... (got distracted by a phone call and connected the +12v to the PIC rather than the +5v !!
http://www.mister-e.org/Pics/DOH.jpg

Looks good! Keep us posted!

Sean_Goddard
- 25th February 2007, 02:26
Why not talk to a PIC in the module using I2C?? After all, the track is two wires.

You could modulate this on top of a standing DC voltage then control a motor using hard coded addresses on the loco module PCB and an H bridge driven by the PWM from the PIC.

Just a thought. I tried it and it worked fine. Be careful of the need to filter the I2C signals HEAVILY but not so much that you lose them.

malc-c
- 25th February 2007, 10:46
Interesting concept, sort of a cross between modern DCC and traditional control. However, its not practical in this instance as the contoller is for a club layout and would mean that every member would have to have the same system installed on their own layaouts at home. Also with the scale, fiting modules to small loco's is a pain in the ***

Acetronics2
- 8th March 2007, 08:17
Hi Malc,

I Had my father home this week-end ...

We talked about supplies and it seems the today's "must" is to use switching supply during speed transitions ( or accelerations ) and DC during constant speed running ( of course for noize !!! ) ...

That meets one of Sougata's threads about signal generation with a Pic ... and opens interesting reflexion and work about what output stage to use !!!

new challenge for Darrel !!! ( He Looooooves !!!! )

Alain