AN216 - which pins to use

Discussion about the ZBasic language including the System Library. If you're not sure where to post your message, do it here. However, do not make test posts here; that's the purpose of the Sandbox.
Post Reply
FFMan
Posts: 502
Joined: 09 January 2010, 12:52 PM

AN216 - which pins to use

Post by FFMan »

I'd like to use a 328n to drive a single servo.

I found AN216 as a starting point and will give this go. Am i right in thinking the sample code (below) is using 16bit Timer1 and therefore the channels on a 328n are B.1 and B.2 ?

Code: Select all

Public Const pre_mask as Byte = &B0000_0111
Public Const pre_8 as Byte = &B0000_0010
Public Const oc1a_mask as Byte = &B1100_0000
Public Const oc1b_mask as Byte = &B0011_0000
Public Const oc1a_norm as Byte = &B1000_0000
Public Const oc1a_invert as Byte = &B1100_0000
Public Const oc1b_norm as Byte = &B0010_0000
Public Const oc1b_invert as Byte = &B0011_0000
Public Const t_mode_maska as Byte = &B0000_0011
Public Const t_mode_maskb as Byte = &B0001_1000
Public Const f_pwm_modea as Byte = &B0000_0010
Public Const f_pwm_modeb as Byte = &B0001_1000
Public Const pc_pwm_modea as Byte = &B0000_0010
Public Const pc_pwm_modeb as Byte = &B0001_0000 


Sub Main()

	'clearing the prescaler will stop the timer 
	Call SetBits(Register.tccr1b, PRE_MASK, &B0000_0000) 

	'set the timer mode to F-PWM 
	Call SetBits(Register.tccr1a, t_mode_maska, f_pwm_modea)
	Call SetBits(Register.tccr1b, t_mode_maskb, f_pwm_modeb)

	'set the output compare modes to normal
	Call SetBits(Register.tccr1a, oc1a_mask, oc1a_norm)
	Call SetBits(Register.tccr1a, oc1b_mask, oc1b_norm)

	'set the top value to give 50 hz when combined with a prescale of 8
	Register.icr1 = 36863

	'set the timer count to zero
	Register.tcnt1 = 0

	'set OCR1a to place the servo at the middle position (1.5mS)
	'50Hz has a period of 20.0 milliseconds
	Register.ocr1a = CUInt(36863.0 * 1.5 / 20.0)

	'set OCR1b to place the servo to one extreme side
	Register.ocr1b = CUInt(36863.0 * 1.0 / 20.0)

	'LAST, set the prescaler to 8, and timing will commence
	Call SetBits(Register.tccr1b, PRE_MASK, PRE_8)

	'Once this is done, you can easily change the servo positions by just changing the OCR1A and OCR1B registers.
	'set OCR1a to place the servo at the 25% position (1.25mS)
	Register.ocr1a = CUInt(36863.0 * 1.25 / 20.0)
	'set OCR1b to place the servo at the 75% position (1.75mS)
	Register.ocr1b = CUInt(36863.0 * 1.75 / 20.0)
End Sub
thanks
dkinzer
Site Admin
Posts: 3120
Joined: 03 September 2005, 13:53 PM
Location: Portland, OR

Re: AN216 - which pins to use

Post by dkinzer »

FFMan wrote:Am i right in thinking the sample code (below) is using 16bit Timer1 and therefore the channels on a 328n are B.1 and B.2 ?
Yes. For reference, the page at the URL below lists the PWM output pins for various devices.

www.zbasic.net/doc/ZBasicSysLib.php?page=27
- Don Kinzer
Post Reply