Unique Servo Control Requirement

rob53

New Member
First a little background. I'm primarily a modeler, specifically, though not limited to, Star Trek ships, and because I wanted to light some of them...led me into hobby electronics and eventually Picaxe, mostly for the PWM aspect, as well as parallel-tasking without having to write dozens of lines of Arduino code, but I've never had the need to use a servo in my projects...until now. I recently watched a youtube video on how to motorize the 1/670 scale Voyager warp pylons using two HS-40 nano-servos. So, I googled to try to get info on how to go about using Picaxe to control them. What I need to do is have the servos turn only 40 degrees at the command of a momentary switch. I.E. at Case 1 turn the servos 40 degrees (pylons up), then Case 2 have the servos return to the starting point (pylons down). I ended up, if you can believe it, having a long conversation with the Google A.I. The darn thing wrote a Picaxe program for me, but I want to run it by you guys to make sure that AI is not leading me astray. Anyway, here is Google AI's code. Oh, and by the way, I haven't even put this in the Picaxe Editor to see if it would compile.

Code:
; PICAXE 08M2 Momentary Switch Servo Control
;
; --- Pin Assignments ---
; C.3 = Input for momentary switch
; C.2 = Output for HS-40 nano servo signal wire

; --- Variable Definitions ---
symbol switch_pin = C.3    ; Assign a friendly name to the switch pin
symbol servo_pin = C.2      ; Assign a friendly name to the servo pin
symbol servo_state = b0     ; Variable to hold the current servo state (0 = start, 1 = 40 deg)
symbol start_pos = 150      ; Initial servo position (adjust as needed for your specific servo)
symbol forty_degree_pos = 190 ; Position for 40 degrees (ADJUST THIS VALUE by experimenting)

; --- Main Program ---
init:
    ; Set the internal oscillator frequency to 16MHz for faster response
    setfreq m16
  
    ; Initialize the servo to the starting position
    servo servo_pin, start_pos
    pause 1000 ; Wait for the servo to settle
  
main:
    ; Check if the switch is pressed (pin goes high)
    if switch_pin = 1 then
        pause 50 ; Debounce delay to prevent multiple button press reads
      
        ; Wait for the button to be released before proceeding
        do while switch_pin = 1: loop
      
        ; Increment the state variable
        inc servo_state
      
        ; Handle the two servo states using SELECT CASE
        select case servo_state
            case 1
                ; First press: move servo to 40 degrees
                servopos servo_pin, forty_degree_pos
          
            case 2
                ; Second press: return servo to starting position
                servopos servo_pin, start_pos
              
                ; Reset the state for the next cycle
                servo_state = 0
              
        endselect
    endif
  
    goto main ; Loop back to check the button again
 
Hi,
symbol switch_pin = C.3 Correct syntax is: symbol switch_pin = pinC.3

It then compiles.
Good luck...........
 
Hi,

Sometimes, the "AI" produces interesting ideas or comments, but IMHO for a PICaxe it's a very poor "tutor" and often (as here) produces code that doesn't work. As The bear has said, it fails a syntax check, as the Program Editor Syntax Check will report. Generally the on-line Command Reference and/or the User Manual is a better reference source.

With that fixed, the program might work adequately, but there are many other issues that could/should be raised by a "real person". First, the PICaxe type is only noted in a "comment" (which might be overlooked or ignored), but if a #PICAXE 08M2 command is included, then there is a better chance of catching other errors. For example, if the Program Editor is set to any other PICaxe type, then there will be another syntax error, because C.2 is a valid Servo Output only for the 08M2 (all others must use port B). Incidentally, with an 08M2, the port may be named B or C, so naming the pin as B.2 is "portable" across most or all PICaxes. However, pin C.2 is such a "useful" pin on the 08M2 (e.g. for a PWM output or the I2C Bus, etc.) that I would normally allocate a Servo output to pin {c}.4 , to allow for possible "future development".

The "AI" specifies/assumes that the pushbutton pulls the input voltage High, but there are advantages in pulling it Low (to ground). There is less risk of accidentally short-circuiting the supply rail to ground (and less risk of damaging the PICaxe if the input is accidentally set as an Output), and it's possible to save the (necessary) external Pull-Down resistor, by using an internal "Weak Pullup Resistor" (via the PULLUP %.... command). Also, the "AI" cures "contact bounce" by waiting until the button is released, but it's not very intuitive that a button must be released before it does anything! Contact Bounce is not likely to occur until the button is touched, so it's better to act as soon as it is pressed. However, it is sensible to wait for the button to be released before proceeding with the remainder of the program, or certainly before testing the button again.

The "AI" assumes that a change in 1 of the Servo value gives 1 degree of rotation. However, the nominal range of the command is 75 to 225 or 150, but most servos will turn by more than 180 degrees for that range. A comment does say that the value needs to be set experimentally, but if the 40 degrees limit is required to prevent damage (or overload) in the system, then it's better to start with a value that will produce a movement of less than the 40 degrees.

Finally, the SELECT ... CASE structure is perfectly acceptable, but most Programmers would just use an IF ... THEN in that situation. Personally, I slightly dislike the SELECT ... CASE because it seems less intuitive as to what happens if the CASE condition is met twice, or not at all. Also, the program sets the Clock Rate to 16 MHz (SETFREQ m16) when the default 4 MHz would be perfectly acceptable, particularly as there is a PAUSE 50 (debounce), which of course is no longer 50 ms because of the SETFREQ !

Cheers, Alan.
 
Hi,
symbol switch_pin = C.3 Correct syntax is: symbol switch_pin = pinC.3

Thank you, Bear. I will change it when I put it in the editor, and see if there are any other syntax erorrs. The HS-40 servos are supposed to be here tomorrow, so I'll hook everything up to the breadboard

The "AI" assumes that a change in 1 of the Servo value gives 1 degree of rotation. However, the nominal range of the command is 75 to 225 or 150, but most servos will turn by more than 180 degrees for that range. A comment does say that the value needs to be set experimentally, but if the 40 degrees limit is required to prevent damage (or overload) in the system, then it's better to start with a value that will produce a movement of less than the 40 degrees.

Actual, in watching the voyager warp pylon tutorial again, something made more sense to me the second time around. The guy was using a 1.5mm brass rod from the servo to the pylon, with a short piece of 3mm brass tube glued the to the end of the brass rod where it ended inside the pylon.. This was to take up the space inside the pylon (i.e. have the 3mm tubing coming very close to, or actually making contact with the surface so that there is very little or no free play). He also had the rods bent at a 40 degree angle, because that is the range of motion of the pylons on the model. So having the requirement of the servo only turning 40 degrees was an error on my part. The servos actually need to turn 90 degrees, and the brass rod being bent at 40 degrees handles the movement of the pylons. I will experiment on my breadboard with the rom of the HS-40 servos to see if it operates at 180 degree rom or something different.

Since I am using two HS-40 nano servos to control both pylons, would I connect both servos to the same output pin? And yes, I agree using pin C.4 would be a better option, leaving C.2 available for pwm, as it is the only pwm output on the 08M2. I use M2 chips exclusively, by the way, because of their parallel tasking ability and their 4 pwm outputs. 08M2, 14M2 and 20M2 are my Picaxe smorgasbord. I have them in both through-hole and surface mount packages.

Generally the on-line Command Reference and/or the User Manual is a better reference source.

No doubt. I have found those manuals to be a very valuable source, as they are very comprehensive, but as I am a very inexperienced Picaxe programmer, I still need help on implementing what I've learned in the manuals. Most of my knowledge is self taught by researching and reading Picaxe programs others have written and modifying that to meet my project's needs. Many years ago, a user here on the forums named "Hippy" gave me an ingenious solution using the Suspend/Resume and Select Case statements. It was my idea, not the AI's, to use select case statements as it's always been the way I've done it ever since Hippy turned me on to it.

The "AI" specifies/assumes that the pushbutton pulls the input voltage High, but there are advantages in pulling it Low (to ground). There is less risk of accidentally short-circuiting the supply rail to ground (and less risk of damaging the PICaxe if the input is accidentally set as an Output), and it's possible to save the (necessary) external Pull-Down resistor, by using an internal "Weak Pullup Resistor" (via the PULLUP %.... command).

The AI actually suggested the pullup command with the internal pullup resistor. It was me that wanted to use an external 10K pulldown resistor from input to ground, and the other side of the momentary switch to the 5V rail. Again, that's been the way I have always handled a momentary switch. I have used the Eagle PCB design software to design and have manufactured many of my circuit boards this way (or sometimes making them myself using a homemade process involving caustic chemicals!!). Having I been doing it wrong all this time?

By the way, I want to thank both of you very much for your time and efforts to help me.
 
Hi,

All of my comments were intended as "Points for discussion", perhaps even being a "Devil's Advocate", because there is absolutely no "Right" or "Wrong" here (just personal opinions). It is certainly possible to operate two Servos from the same Pulse source, but generally they don't have an exact "central" position for a nominal pulse (usually value 150 = 1.5ms pulse). Most Servos have a splined shaft so the "horns" can be fitted within about +/- 10 degrees of any desired position, but if the two Servo mechanisms are required to align more perfectly, then it's necessary to use either a mechanical or an electronic/software "trimming" solution. That might be by simply "bending" a linkage, but some people might prefer a "trimming" potentiometer (perhaps in a RC transmitter), or even a "software" option directly within the controlling Program. However, for an "electronic" trimming method, separate pulses from the PICaxe would be required. The choice is really down to which is the most "convenient" method for the designer/constructor.
Having I been doing it wrong all this time?

No certainly not "wrong", it is indeed very common to consider a "High" input voltage (e.g. into a PICaxe pin) to indicate a "Logical 1" or a "True" situation. Hence, if it is desired for something to "happen" (i.e. Command = True) then it is usual to connect the switch to a "1" or a "High" reference rail (and to be fair, that's usually shown in the PICaxe Manuals). It's easy to explain and to understand, but the "Active Low" (i.e. "0" / "Low" = "True") concept is quite common in electronics systems, and has some (arguable) advantages. It can be made easy to understand by defining something like "Symbol Pressed = 0", permitting familiar constructs such as IF c.3 = Pressed THEN... or ... CASE = Pressed ... , etc.. As already mentioned there are potential hardware savings possible (even if it's only one resistor), but there can be another advantage for Servo (or almost any motor-driven) systems:

Motors usually need much more current or power than (for example) a PICaxe chip, and their switching ON and OFF can "disturb" the supply rail, so it is common to separate their supply rails as "Dirty" (Motors) and "Clean"(for PICaxe, etc.). Also, a higher supply voltage (e.g. 6 volts for a Servo) may help to give the motor more Torque or "Power". Thus a common solution is to connect the Motor (Dirty) supply rail directly to a/the battery (or PSU) and operate the PICaxe from a Clean supply, via a voltage regulator (or perhaps just a R-C filter), which may drop the voltage to 5v or less. Here, the control switches should (and maybe must) be connected to the Clean supply rail, which might demand additional wiring for "remote" operations, for example a Limit Switch on a distant actuator. But this is probably irrelevant for your application, so again it's really just a matter of using whatever method you are most "comfortable" with.

Cheers, Alan.
 
I am all about simplicity, and I kinda have a rule of thumb that I've carried with me from the 25 years I spent of doing autobody repair. That rule of thumb is: *always try the simplest solution first*, but it always need to be a sound solution. I would never take a shortcut that was not a sound method. Anyway, this rule usually applies to solving a problem. For example, I came in to work one morning and. I was about 20 minutes late due to a traffic jam, and my boss had the right door trim panel off of a car that I had fixed and was investigating why the power window wasn't working. He was poking around the switch with a test light, and when I asked him what the problem was, he replied "the damned window ain't workin'" in a rather sharp tone, so I started processing that.... "what is the simplest solution" I said to myself. so I checked the rear door and that window wasn't working either (I hadn't touched the rear door doing my repairs). So I asked him "did you check the fuses" to which he replied "YES"!!, again with the aggravated tone. So right away I'm thinking "I know what's wrong with it" and with that, I walked around and opened the driver door and examined the master control panel and sure enough, there was a "lock out" switch for the windows *In case you have kids in the car that are playing with the power windows, making them go up and down*....you can just activate that switch and lock them out. So I push the button on that latching switch and say to Ronny "try it now". He pushes the switch and the power window is working. He asked me, "what the hell did you do"? I replied "simplest solution first, Ronny, the master control panel has a lock-out switch for the windows". As he's walking away he says "put that door back together". I wanted to tell him "you put it back together, you took it apart", but since I was late I figured I'd better keep my mouth shut, so I did. While I'm re-assembling the trim panel he brings the customer out there and shows him how his master control panel works. Had I been to work on time that morning I could've saved him an hour of wasted time and effort, and when one is working on commission, time is money.

I'm sorry for the long winded story, but I just wanted you to know how my mind works. My "simplest solution first" rule of thumb also applies to hobby electronics, but I want that solution to be a sound one. If an extra component is needed to make a circuit operated properly and within the operating specs of each components requirements to avoid potential problems, then that's the way I want to go. but I don't want to add parts or change methods that are already sound, tried and tested components and procedures. With that I mind, if you're willing, I want you to help me with the best and easiest solution to get these servos operating the way I need them to, without stressing them or any other part in the circuit. This model doesn't need very much torque at all to work the nacelle pylons up and down. If you're interested, you can watch the Youtube Video , it's only 6 minutes long. He has those nacelles operating very smoothly, no twitching or jerking. It's just like you see them moving on the show.

Firstly, he's using an Arduino Uno R3 to operate his servos. It looks like he's using the Arduino's 5V output, or perhaps 3.3V, I've forgotten the servo's power requirement. I'm also seeing two yellow leads connected to digital outputs (5 & 7??), these are obviously the servo's data lines. But those pylons/nacelles are operating as smoothly as silk. That's how I want mine to work. So if we use the 150 value in the Picaxe program, theoretically, that should be 90 degrees of movement, is that correct? So we count from 75 to 150, then back to 75 again to get the 90 degree range of motion. I want it to take approx. 2.5 to 3 seconds for the servos to reach 90 degrees of movement. I will study the AIs code (and the Picaxe manual) and see what changes need to be made aside from the obvious change from 40 degree of movement to a 90 degree movement. If you could nudge me along, that would be greatly appreciated, Mr. Allycat (or Miss Allycat), such as the case may be. :)
 
Last edited:
Hi,

AFAIK there is no absolute specification for the operation of Servos, but it is usually assumed that the pulse control range is about 0.75 to 2.25 ms (with PICaxe stepping in 0.01 ms increments) and the full sweep range is typically around 180 to 270 degrees. However, the Hitec Data Sheet for their version of the HS-40 does specify a "Target" of 40 degrees sweep with a 0.4 ms change in pulse width. Normally, one would arrange an approximately symmetrical movement each side of its middle position (i.e. a 1.5 ms pulse) so it appears that you need the pulse to sweep from around 1.05 to 1.95 ms, i.e. integer values of 105 to 195.

The servo normally sweeps much faster than you require (typically 60 degrees in 100 - 120 ms) so the program needs to repeatedly update the requested position at the desired speed (and therefore the AI program is much worse than I thought). The pulses are actually transmitted every 20 ms (i.e. 50Hz) so if you increment each pulse by one integer step then it would sweep 90 degrees in about 1.8 seconds (or 3.6 seconds if stepped on every other pulse). But it's not particularly easy to synchronise the program updates with the Servo pulses anyway, so the KISS solution is to simply update the position approximately every 30 ms and see if the speed and smoothness is satisfactory. Sometimes Servo Jitter can be a problem, but I don't believe the following program contains any "risky" instructions, so it should be fine, provided that the PICaxe supply rail is "clean".

So here is my (simulated only) version of a basic program that should work. You might want to temporarily change the limit values nearer to the middle, to speed up the simulation. ;)

Code:
#picaxe 08m2
#no_data                                  ; No need to download any Data values
; PICAXE 08M2 Momentary Switch Servo Control     AllyCat October 2025

; #define ACTIVELOW                       ; Uncomment for Alternative pushbutton operation (button to Ground)
; Control/Variables :
  symbol PushButton = pinC.3              ; Press to toggle Servo to move to opposite Endstop
  symbol Servo_Pin = C.4                  ; Control signal to the servo(s)
  symbol Servo_Pos = b1                   ; Just one variable to KISS
; Constants depending on the Hardware configuration/requirements :
  symbol LIMIT_CCW = 105                  ; Endstop for Counter-Clockwise rotation (adjust as required)
  symbol LIMIT_CW = 195                   ; Endstop for Clockwise rotation (adjust as required)
  symbol SWEEP_RATE = 30                  ; 30ms step rate. Increase this number to move Slower (adjust as required)
; Calculate threshold which determines whether to move CW or CCW :
  symbol MIDDLE_I = LIMIT_CCW + LIMIT_CW  ; [Symbol declarations permit only one maths operator]
  symbol MIDDLE = MIDDLE_I / 2            ; Average (Middle) Servo position
 
#IFDEF ACTIVELOW                          ; Pushbutton connected to Ground (0v)
  symbol PRESSED = 0                      ; Logic value when button is pressed
  Pullup %001000                          ; Activate Pushbutton PullUp resistor
#ELSE                                     ; Pushbutton connected to Supply (Vdd)
  symbol PRESSED = 1                      ; Logic value when button is pressed [Use only this line if button is connected to supply rail]
#ENDIF

init:
  Servo_Pos = LIMIT_CCW
  Servo Servo_Pin , Servo_Pos             ; Starting position (assumed fully CCW)
  Pause 1000                              ; Allow time for system to stabilise
main:
  Do : Loop Until PushButton = PRESSED    ; Wait for button to be pressed
  If Servo_Pos <= MIDDLE then             ; Position should be at LIMIT_CCW, so can step immediately
     Do
        Inc Servo_Pos
        Servo Servo_Pin , Servo_Pos
        Pause SWEEP_RATE
     Loop Until Servo_Pos => LIMIT_CW
  Else                                   ; Position should be at LIMIT_CW, so can step immediately  
     Do
        Dec Servo_Pos
        Servo Servo_Pin , Servo_Pos
        Pause SWEEP_RATE
     Loop Until Servo_Pos <= LIMIT_CCW
  Endif
  Do : Loop Until PushButton <> PRESSED    ; Ensure button has been released
Goto main        ; Or a purist would close a DO : LOOP here

ADDENDUM: Having watched the video, it appears that you might need the two Servos to move in Opposite directions. In that case you would need to use two Servo Output pins and add to the Program code accordingly (probably almost totally duplicated so that the End Stops can be trimmed individually within the Program). BTW, nothing has been said about the power supply and PICaxe board (which can be MUCH smaller than an Arduino :) ), but this might be a contender for one of my "AA-sized PICaxe Boards", with examples shown later at post #23 there. FWIW, I'm planning to post an Updated version of that soon, which happens to include a Servo Socket (and much, much more) and use the internal Weak Pullup resistors (on almost all of the pins), so keep a watch on the Active Forum. ;)

Cheers, Alan.
 
Last edited:
Having watched the video, it appears that you might need the two Servos to move in Opposite directions.

I think you're right. The servo operating the right pylon (your right watching the video, but actually left side on the model) is turning clockwise, and the other one must turn counter-clockwise. I totally missed that. Sorry

BTW, nothing has been said about the power supply and PICaxe board

The power supply will be an AC/DC adapter, 12V @ 2A, using an LM340MPX 5V 1.5A regulator ( i also have this in the T/H variety). The board will be one of my own design using KiCad or Fritzing PCB design software. I also have some sripboard and solderable beadboard that I could use, and positive pre-sensetized single layer board for homemade PCB.

I put your program to a real world test. It turns the servo 90 degrees with 1st button press, and then back again with 2nd button press. The movement itself is very smooth and at just the right speed. However, it has a slight jerky motion at start position and at 90 degree position. I tried putting a 2n2222 transistor between C4 and the data pin, but then it didn't work at all. I had Emitter to GND, Base to C.4 via 3k resistor, and collector to servo Data pin. Wiring it directly from C.4 to the data pin works, but with the slight jerky motion. I am using a bench-top power supply set at 5.0V. Both servo and Picaxe are connected to the same 5V and Gnd rails on the breadboard. I'm also noticing a brief indicator of a short circuit on my benchtop power supply when the twitching occurs (quich red flash on the short indicator) Do you think I should give the servo it's own separate power supply? I'll have to get some AA battery holder cases. I am using rechareable AA batteries, so they are 1.2V instead of 1.5V. Should I go with a 4X AA battery holder for 4.8V, or a 5X for 6V?
 
Last edited:
Hi,

The Servo control signals (Yellow wires) require only a low power, so there should be no need for an amplifier or buffer stage. But if one is used, then, first the collector needs a pullup resistor to the supply rail, and secondly driving the base gives an inverting stage; so the driving pulse would be about 18.5 ms, which won't work. It would need either a non-inverting amplifier (e.g. driving the emitter) or two inverting stages in series.

The starting (surge) current of many d.c. motors can be an issue, but the Hitec Servos' data sheet quotes the Stall (stopped) current at only 460mA, which isn't very high. However, there should be some supply decoupling included, for example at least 100 uF across the supply near to the Servos and 10uF directly across the PICaxe. The power supply should be connected directly to the servos/motors, and to prevent spikes/surges getting to the PIcaxe, insert typically 100 ohms (in the positive supply rail) to the PICaxe supply/board. But the PICaxe requires so little current that up to 1k should be suitable, and two separate supplies not be necessary.

A NiMH cell directly after removal from its charger can be up to 1.4 volts, so 5 in series would be too much. Also, if a surge current from the motors is an issue, then it will be reduced by using a lower supply voltage. If there are still problems and two separate drive pulses prove necessary anyway, then try introducing a small delay in the Program, between the two starting events (perhaps some tens of ms), and/or restart the Servo drives at their (expected) existing positions, before beginning to sweep their values. Or of course there might be some backlash in the gear train?

Cheers, Alan.
 
to prevent spikes/surges getting to the PIcaxe, insert typically 100 ohms (in the positive supply rail) to the PICaxe supply/board. But the PICaxe requires so little current that up to 1k should be suitable, and two separate supplies not be necessary.
There is no picaxe supply board. I am using a breadboard. I removed the jumper wire connecting the picaxe to the 5V rail, and replaced it with a 1K resistor, but no joy. The jitter persists.

The starting (surge) current of many d.c. motors can be an issue


It's not a starting surge. The "jitter" is happening while the servo is at rest (about every two seconds), at both the staring point, and the 90 degree point. When the servo is moving, it is as smooth as silk.

there should be some supply decoupling included, for example at least 100 uF across the supply near to the Servos and 10uF directly across the PICaxe.

I installed the capacitors (10uF right in front of where the picaxe is connected to the 5V rail, and 100uF right next where the servo is connected to the 5V rail), but the jitter is still there. Could it be in the programming? In the video the guy has the yellow data wires going directly from the arduino to the servos. I watched some of his other videos, and he's using a Samsung tablet to run all of his effects on this model. That's why there's no switch on the arduino. He has a USB cable attached to it, and apparently the tablet is where he's switching it from.

If there are still problems and two separate drive pulses prove necessary anyway, then try introducing a small delay in the Program, between the two starting events (perhaps some tens of ms), and/or restart the Servo drives at their (expected) existing positions, before beginning to sweep their values. Or of course there might be some backlash in the gear train?

You're talking over my head, Alan. I'm not an electrical engineer or a computer programmer. I thought this would be relatively easy, but this is getting way too complicated. Please don't get me wrong, I am SO grateful for your help. Can we approach this with my "simplest solution first" , or KISS as you call it? The guy in the video didn't have all of these capacitors and resistors in his circuit, just arduino outputs directly to the servos.

I also have to figure out how to run the other servo CW simultaneously to this one running CCW. I would be using C.1 for the other servo, so there would need to be "symbol servo_pin2 = C.1", Would I need another variable i.e. "symbol servo_pos2 = b2" ?

When you reply, please go easy on me, brother.

**EDIT**
This servo is turning CW 90 degrees, then CCW back to the starting point, yes? If I turn off the power when the servo is at 90 degrees, then power back on, it jumps back to the starting point. If I turn power off and back on when the servo is at the starting point, it jitters a little harder, but doesn"t go anywhere. So this program is for the left pylon servo (right in the video).
 
Last edited:
Hi,

Ah, I'd missed the significance of the "twitching" randomly about every two seconds from the later part of your description. I can't think why the PICaxe might do that, but the "Keep It SimpleS" solution could be to switch Off the servos when they are not required to move, i.e. a SERVO Servo_Pin , OFF after the ENDIF in the program (for each Servo pin if two are used). Then appropriate SERVO commands (to restart the Servos) and perhaps a short PAUSE immediately after the button is pressed.

The Arduino probably has plenty of decoupling (capacitors) and perhaps a voltage regulator designed into its Circuit Board, so might not be comparable with a "naked" PICaxe chip.

I'm also noticing a brief indicator of a short circuit on my benchtop power supply when the twitching occurs (quick red flash on the short indicator) Do you think I should give the servo it's own separate power supply?

Again, I can't think why that should be happening, but a common KISS recommendation for PICaxe issues is to use a simple battery supply (3 or 4 AA cells) instead of a mains PSU. If the twitching still occurs, then there might be a Programming issue, but I can't think what it might be, at least not without getting very technical: 2.1 seconds is approximately the "Watchdog" timeout (related to PICaxe's "Sleep" mode), but there's absolutely no reason why that might be activated (with the standard/default 4 MHz clock frequency).

No, there's probably no need for another variable if the two Servos have very similar rotational sweeps (which was assumed to be the case when both were driven by the same pulse). However, it might be the easiest modification: Just use a DEC Servo_Pos2 after the INC Servo_Pos in one loop and vice versa in the other. Alternatively, after the INC/DEC lines, you could add a Servo_Pos2 = MIDDLE_I - Servo_Pos from my original program (MIDDLE_I is the sum of the two Endstops).

Of course at the start of the program, one Servo needs to be set to LIMIT_CCW and the other to LIMIT_CW , or it might be worth introducing additional Constants LIMIT_CCW2 and LIMIT_CW2 , so that each servo can have its own Endstops set in the program (rather than needing to "bend" any mechanical linkages).

Cheers, Alan.
 
**EDIT**
This servo is turning CW 90 degrees, then CCW back to the starting point, yes? If I turn off the power when the servo is at 90 degrees, then power back on, it jumps back to the starting point. If I turn power off and back on when the servo is at the starting point, it jitters a little harder, but doesn"t go anywhere. So this program is for the left pylon servo (right in the video).
Hi,

At my last post I hadn't read your edit of 2.45am, but the Program only "understands" about CW and CCW rotation of the Servos, so their location needs to be documented in "comment" ( ; or ' ) lines, as appropriate. Also, when the program starts, it has no way of "knowing" where the Servos' shafts are pointing. It's probably where they were left when the power was removed, but Servos have a gear train that (usually) can be physically pushed to a different position by hand.

Off Topic: It's a reason why some modellers use Stepper Motors (with some form of Limit detection) in preference to Servos. Very small Stepper Motors are available (smaller than any Servo) but they are (much) more difficult to drive, needing more pins, more complex programming and/or additional hardware, amplifiers, etc., and usually a separate gear train. However, they usually have quite low torque so may not need End-Stop switches as such, but simply drive up to a physical End Stop (until a Time-Out in the program).

The PICaxe does have an internal "Non-Volatile" memory (the DATA/EEPROM) which can "remember" values previously set by the program, when restarting after a Power-Down, but unfortunately this memory may ultimately "Wear Out" if updated too often. This may take up to 100,000 or a million WRITE cycles, so it's necessary to estimate whether this will ever be reached (in maybe years of operation). The "Best" solution is to include a "Power Fail" detection in the program (and some energy storage to keep the program running for at least some milliseconds afterwards) to WRITE the present status (e.g. ServoPos values) to the memory. But this is certainly not a KISS solution.

Writing every servo position when it is updated during a "sweep" will almost certainly Wear Out the EEPROM, but it is perhaps reasonable to WRITE the servo position(s) each time that they complete their sweep. You will need to estimate a Ballpark figure for the possibility, and if it looks practical, then there are a few additional factors that we might need to consider. Of course there is no way that the servos/program can take into account any "externally-applied" movement of the motors between a Power-Down and subsequent Power-Up.

Cheers, Alan.
 
Last edited:
I am using a bench-top power supply set at 5.0V. Both servo and Picaxe are connected to the same 5V and Gnd rails on the breadboard. I'm also noticing a brief indicator of a short circuit on my benchtop power supply when the twitching occurs (quich red flash on the short indicator) Do you think I should give the servo it's own separate power supply? I'll have to get some AA battery holder cases. I am using rechareable AA batteries, so they are 1.2V instead of 1.5V. Should I go with a 4X AA battery holder for 4.8V, or a 5X for 6V?
Using a separate battery pack for the servos is a good test to do because it will help us to eliminate one possible source of the twitching:
- If you no longer have the twitching with a separate battery pack for the servos then it is caused by sharing the power supply with the PICAXE chip and we have identified the cause.
- If you still see the twitching with a separate battery pack for the servos then it is not caused by sharing the power supply with the PICAXE chip. We will have eliminated that as a possible cause and can focus on investigating other possible causes.

It will not effect this test if you use 4 x 1.2v batteries because 4.8v will be within the specified max and min range of voltages for an R/C servo.
- Using a higher voltage will give the servo greater torque and might make it move faster while a lower voltage will mean a lower torque.
- As long as the voltage is within the specified max and min range I do not believe that the voltage will cause the twitching.

You will need to connect the power supply ground and the battery pack ground to a common ground used by the servos and the PICAXE chip.

If I turn off the power when the servo is at 90 degrees, then power back on, it jumps back to the starting point. If I turn power off and back on when the servo is at the starting point, it jitters a little harder, but doesn"t go anywhere.
This is not a problem. It is what the program in post #7 is intended to do.
These commands in the "init:" section of the program always set the servo to the know start position LIMIT_CCW when power is turned back on to the PICAXE chip:
Code:
init:
  Servo_Pos = LIMIT_CCW
  Servo Servo_Pin , Servo_Pos             ; Starting position (assumed fully CCW)

This approach seems reasonable to me and you simply decide what you want the start position of the nacelles to be when you turn the power on to you model and set this in the "init:" section.

If you want the initial position of the nacelles to be wherever they were when you turned the power of then you will need to follow up AlleyCat's suggestion of saving this in the DATA/EEPROM in his post #12.

I suggest you go with your "simplest solution first" and investigate getting rid of the twitching first then, once that is resolved, you can proceed with adding other features.

I'm also noticing a brief indicator of a short circuit on my benchtop power supply when the twitching occurs (quich red flash on the short indicator)

This probably does not indicate a short, at least not in the sense that I think you mean.
Electric motors have a very low resistance when the are stopped that is just the resistance of the copper wire in the motor's coils.
So if the servo glitches when it is stopped at either end of the range then the full 5.0V will be applied to the motor to make it start and it will try to draw a current only limited by the resistance of the copper windings and this is likely what is triggering the indicator on your power supply.
 
Last edited:
Rob53,

I tested the code in post #7 with an 08M2 on a breadboard powered by my laptops USB-A port.
I used a standard size Futable servo as well as a cheap chinese 4g servo, which is about the same size as your HS-40, and I get no twiching at all.

The USB-A port only provides 0.5A which I expect would be much less than most benchtop power supplies.

This led me to reconsider what I said about the brief indicataor flash you see on your power supply being due to the startup current of the servo motor. This was an assumption on my part. I have no proof that this is the case but it is something that we can test.

Hook up evertying powered by your benchtop power supply and after you see servo twich and power supply indicator flash begin every 2 sec disconnect the servo to see if the power supply indicator continues to flash.

From what you have said the indicator flashes every time that the servo twitches so if the indicator continues to flash when the servo is disconnected then we have eliminated the servo as a possible cause.

If the indicator stops flashing then connect the 2nd servo you have to test the twitching and flashing occurs with both servos.

Edit: Corrected the servo model to HS-40.
 
Last edited:
Of course at the start of the program, one Servo needs to be set to LIMIT_CCW and the other to LIMIT_CW , or it might be worth introducing additional Constants LIMIT_CCW2 and LIMIT_CW2 , so that each servo can have its own Endstops set in the program (rather than needing to "bend" any mechanical linkages).

I don't know what you meant by that last parenthesis. The 1.5mm brass rods have to be bent at a 40 degree angle to move the pylons. I just want each servo to turn 90 degrees simultaneously at first button press. CW for the starboard pylon, and CCW for the port pylon, and then both return to the start position at the second button press. Right now the task ahead of me is to figure out how to introduce code for the port pylon (CCW up, then CW down) into your style of programming. I'm sure I'll figure it out eventually. Working on things like this is always good for the brain.
 
I suggest you go with your "simplest solution first" and investigate getting rid of the twitching first then, once that is resolved, you can proceed with adding other features.

I ordered some 4X AA battery packs from Amazon, they came in today. Connected servo to battery pack positive, then connected the negative side of the battery pack to the same ground the picaxe is using. then turned on the power (benchtop and battery pack). The twitch is still there. I also tried disconnecting the DATA line, where the servo receives instructions from the Picaxe. The twitching stopped, reconnected it, twitching starts again. I tried using my other HS-40 servo (I have two of them), the twitching occurs with it as well.

Hook up evertying powered by your benchtop power supply and after you see servo twich and power supply indicator flash begin every 2 sec disconnect the servo to see if the power supply indicator continues to flash.

No, it didn't continue to flash, whatever is causing the twitch, is also causing the short indicator to flash. All I have to disconnect to stop the twitching is the data line from pin C.4 to servo--yellow. The twitching stops, the flashing indicator stops, but the 5V and GND are still connected to the servo. I also tried disconnecting the servo from the 5V rail (leaving the data line connected). Of course the twitching stops, as does the short indicator.

By isolating the servo from the 5V rail on the breadboard, and powering it with only the 4x battery pack (sharing the GND rail), while maybe not totally conclusive, it's certainly compelling evidence that the power supply is not blame.

****EDIT***

I should also mention that powering the servo from the battery pack, the twitching continues, but the bench-top power supply short circuit indicator no longer comes on at all.
 
Hook up evertying powered by your benchtop power supply and after you see servo twich and power supply indicator flash begin every 2 sec disconnect the servo to see if the power supply indicator continues to flash.

No, it didn't continue to flash, whatever is causing the twitch, is also causing the short indicator to flash.

As you've said, this confirms that whatever is causing the servo twitch and the indicator flash only occurs when both the servo and the power supply are being used with the Picaxe chip.

Connected servo to battery pack positive, then connected the negative side of the battery pack to the same ground the picaxe is using. then turned on the power (benchtop and battery pack). The twitch is still there.

Confirms that the twitch is not caused by the servo getting it's power from the power supply.
- i..e. in this test the twitch must be coming in through the servo data line.
-
You also confirm that the twitch is coming in through the servo data line with your test "All I have to disconnect to stop the twitching is the data line from pin C.4 to servo--yellow. The twitching stops,"

I tried using my other HS-40 servo (I have two of them), the twitching occurs with it as well.

Hitek is a premium brand so as the twitching did not occur with just the first servo I will take this test to indicate that there is nothing wrong with the servos.

This leads to my next two tests:

Repeat the test: "Connected servo to battery pack positive, then connected the negative side of the battery pack to the same ground the picaxe is using. then turned on the power (benchtop and battery pack)."
- You said that the twitch is still there.
- Does the indicator still flash on the power supply when the servo is being powered by the battery pack?

Disconnect the power supply, use the battery pack to power the Picaxe chip and the servo to see if the servo still twitches when not using the power supply.

and some questions about your bench power supply:
- Is there a label on the flashing indicator?
- So that I can look up the manual online, what is the brand and model number?
 
Does the indicator still flash on the power supply when the servo is being powered by the battery pack?

Good morning, Flenser. Apparently you didn't see my edit, but to answer your question, no, it does not continue to flash while powering the servo independently with the battery pack, sharing the ground with the Picaxe of course.
Disconnect the power supply, use the battery pack to power the Picaxe chip and the servo to see if the servo still twitches when not using the power supply.

and some questions about your bench power supply:
- Is there a label on the flashing indicator?
- So that I can look up the manual online, what is the brand and model number?

Yes, the twitching is still there when powering the whole circuit with the battery pack. The red indicator LED is labelled "CC". It may also come on during other conditions, but in my experience, it always comes on when there is a short circuit.

The bench-top PSU is a Tekpower TP1803D

Anyway, I'm pretty sure we have proven the PSU is not to blame for the anomalous behavior in the servo.
 
Hi,

For absolute certainty, does the twitching happen with the PSU totally disconnected (including the earth line) from the Project (and PSU preferably switched Off)? Also for clarification, do the twitches occur repetitively with a consistent period of "approximately two seconds" or are they truly random (e.g. sometimes <1 or >3 seconds apart)? Do you have a spare PICaxe that can be easily substituted (i.e. in an IC socket), because as Flenser has shown, the twitching is not intrinsic to the operation of the PICaxe program (always).

A few more simple tests: Does the twitching still happen if you Hold IN the pushbutton (this is a check that the Button-Release code is working correctly anyway)? Is it cured with just a "SERVO Servo_Pin , OFF after the ENDIF in the program" (post #11), it certainly should (and we can worry about restarting the Servos cleanly later, if necessary)? A further test I would try is inserting a PAUSE 5000 at various positions in the program and see if the twitching stops for the 5 second periods.

Cheers, Alan.
 
Rob43,

Yes, the twitching is still there when powering the whole circuit with the battery pack. The red indicator LED is labelled "CC". It may also come on during other conditions, but in my experience, it always comes on when there is a short circuit.

I may not have made myself clear enough.
When I say "the battery is powering the whole circuit" I mean that the batteries are powering the Picaxe and the servo and the power supply is not connected to the circuit at all.
- Are you saying her that the power supply indicator is flashing when it turned on but is not connected to any part of the circuit?

Your benchtop power supply has two settings.
- The maximum voltage, which you have set to 5v
- The maximum current.

So long as the current you circuit draws is below the maximum current setting the power supply will output the voltage you have set. This is operating in Constant Voltage (CV) mode.

If you circuit will draw more than the max current setting then the power supply will restrict the current to that max setting. This is operating in Constant Current (CC) mode. The power supply does this by dropping the voltage so that it only has to deliver your max current setting.
- When the power supply starts operating in CC mode it turns on the CC indicator light to inform you that your circuit is drawing more current than the max you have set.
- As the CC indicator was flashing very briefly I would expect that the events when the power supply was operating in CC mode are probably too short for the voltage display to be updated with the voltage that had to be dropped.

When the power supply is turned on what is the current setting?

Good morning, Flenser. Apparently you didn't see my edit, but to answer your question, no, it does not continue to flash while powering the servo independently with the battery pack, sharing the ground with the Picaxe of course.

What you wrote in post #16 was
"I ordered some 4X AA battery packs from Amazon, they came in today. Connected servo to battery pack positive, then connected the negative side of the battery pack to the same ground the picaxe is using. then turned on the power (benchtop and battery pack). The twitch is still there."

You do not say above whether or not the indicator was flashing when the servo was twitching in this test.
- Up until now the indicator has always flashed when the servo was twitching so I'd like to confirm if the indicator was not flashing in this test because that would break this relationship I thought we had spotted.

You continued on in post #16 to write:
"I also tried disconnecting the DATA line, where the servo receives instructions from the Picaxe. The twitching stopped, reconnected it, twitching starts again. I tried using my other HS-40 servo (I have two of them), the twitching occurs with it as well."

This was a different test with the servo connected to the battery but the data line disconnected. I'm eager to confirm whether the indicator flashes when the servo twitches while powered with the batteries and the data line connected.
 
I may not have made myself clear enough.
When I say "the battery is powering the whole circuit" I mean that the batteries are powering the Picaxe and the servo and the power supply is not connected to the circuit at all.

The twitching is still happening when the entire circuit is being powered by the battery pack. The bench-top power supply is not connected to anything.
Are you saying her that the power supply indicator is flashing when it turned on but is not connected to any part of the circuit?

No, that is not what I'm saying. The short indicator flashes in conjunction with the twitching, but only when the power supply is providing power to the picaxe and the servo. When the servo is being powered by the battery pack, and the picaxe is being powered by bench-top PSU, then there is no activity from the short indicator (it does not come on at all). It does not come on at all, but the twitching is still happening.

When the power supply is turned on what is the current setting?

It only displays current that is being drawn. During the twitch, the current draw is from 100 to 130 mA. When the servo is moving, it's draw is around 40mA.

What you wrote in post #16 was
"I ordered some 4X AA battery packs from Amazon, they came in today. Connected servo to battery pack positive, then connected the negative side of the battery pack to the same ground the picaxe is using. then turned on the power (benchtop and battery pack). The twitch is still there."

You do not say above whether or not the indicator was flashing when the servo was twitching in this test.
- Up until now the indicator has always flashed when the servo was twitching so I'd like to confirm if the indicator was not flashing in this test because that would break this relationship I thought we had spotted.

You apparently did not see my ***EDIT***. The indicator does not flash when the servo is being powered by the battery pack and the picaxe is still being powered by the PSU.
 
For absolute certainty, does the twitching happen with the PSU totally disconnected (including the earth line) from the Project (and PSU preferably switched Off)? Also for clarification, do the twitches occur repetitively with a consistent period of "approximately two seconds" or are they truly random (e.g. sometimes <1 or >3 seconds apart)? Do you have a spare PICaxe that can be easily substituted (i.e. in an IC socket), because as Flenser has shown, the twitching is not intrinsic to the operation of the PICaxe program (always).

1.) Hi Alan, the twitching occurs regardless of where the servo gets it's power. With the PSU totally disconnecting (and switched off) and the whole circuit is being run by the battery pack, the twitching still happens.

2.) The twitching does not appear to be random. it occurs at frequent and consistent intervals (about every two seconds)

3.) I tried that, no joy. Twitching is still there.

A few more simple tests: Does the twitching still happen if you Hold IN the pushbutton (this is a check that the Button-Release code is working correctly anyway)? Is it cured with just a "SERVO Servo_Pin , OFF after the ENDIF in the program" (post #11), it certainly should (and we can worry about restarting the Servos cleanly later, if necessary)? A further test I would try is inserting a PAUSE 5000 at various positions in the program and see if the twitching stops for the 5 second periods.

When holding the button down, the twitch happens constantly. When I release the button, it goes back to the (approx) two second intervals. I am not sure where to put the pauses. If you could adjust the code the way you see fit, then I will load it in there. I really would appreciate it. I will study the picaxe manuals for everything related to servo control. I will also peruse the internet for information regarding servo control with picaxe. Then I'm sure I'll be more capable when it comes to writing and/or adjusting the code.
 
It might be hard to capture but I would like to see an oscilloscope trace of the signal line between the PICAXE and the servo. Obviously, including the bit pattern during one of these twitches. A question: is a SerTxd or SerOut command included in the code?
 
Hi,

Firstly, you do have the "recommended" (read "Mandatory", but the value is not too critical) 100nF (0.1 uF) capacitor directly across the PICaxe supply pins, don't you? I'm not clear what your "3." is referring to, was that changing the PICaxe chip? If not can this be done easily?

A few other things to try to eliminate "stupid" problems; change symbol Servo_Pos = b1 to another variable, say b21 and increase the first PAUSE 1000 to PAUSE 5000 (to make it more obvious if the PICaxe is spontaneously resetting). If (easily) possible, also change the switch input pin to another, probably C.2 (because C.3 has rather "unusual" hardware characteristics). Also try modifying the last few lines of the program as follows:
Code:
; .....
Endif
  Do : Loop Until PushButton <> PRESSED    ; If holding the Button IN makes the Jitter Worse the try commenting out this line with a ";"
  Pause 5000            ; Does it Jitter during this period?
  Servo Servo_Pin , OFF    ; Terminate the Servo Pulses (They will restart automatically at the next SERVO instruction)
Goto main
With this modification, the Jitter might occur for 5 seconds after sweeping the Servo and then Stop (or it might not ! ).

Oh, and BTW did you ever try the "AI" software, and if so, did that Jitter? Pete: I'm assuming that the program has been exactly as written in #7, and a 'scope is not available.

Cheers, Alan.
 
You apparently did not see my ***EDIT***. The indicator does not flash when the servo is being powered by the battery pack and the picaxe is still being powered by the PSU
You are correct. I did not read your post carefully enough. My apologies for causing the confusion

The twitching is still happening when the entire circuit is being powered by the battery pack. The bench-top power supply is not connected to anything.
Great. This confirms for me that the twitching is nothing to do with the power supply.

But I can't identify from the tests so far what is causing the twitching.
 
After AlleyCat's last post I realized that the 08M2 I used to try and reproduce the twitching was on a breadboard that had the recommended capacitors installed on the power lines.

So I have repeated my test using the code in post #7, my 08M2 and a 4g micro servo powered by my laptop's USB port with no filter capacitors and I got the same result. I do not get any twitching.

Rob53, would you post a picture of the breadboard you are using to do these tests with the battery and servo connected so we can explicitly see what you are using, rather than us making assumptions from your posts.
 
I'm not clear what your "3." is referring to, was that changing the PICaxe chip? If not can this be done easi

Yes, I tried a different 08M2. No change

I made the adjustments to the program, including moving the switch to C.1 and changing the "pause" value to 5000, and adding the code in post #17 to then end of the original code. When I first turn on the power, the servo will kick a little to the left (CCW) and then rest back to where it started. This happens every single time that I cycle the power off and back on again, regardless of how much time has elapsed between power off and power on. The "regular"twitching is still there, BUT, when I press the button to activate the servo's first 90 degree movement CW, the twitching stops ( probably because of the "Servo Servo_Pin , OFF" that was added to the code). There is no more twitching while the servo is at rest, but now it has some other strange behavior. Sometimes it will twitch in the middle of movement (CW and/or CCW), and sometimes it will twitch one single time while at rest. Then sometimes it doesn't do either of those things.

Here are your pictures....
 

Attachments

  • breadboard1.jpg
    breadboard1.jpg
    197.2 KB · Views: 9
  • breadboard2.jpg
    breadboard2.jpg
    194.8 KB · Views: 9
  • benchtopPSU.jpg
    benchtopPSU.jpg
    118.6 KB · Views: 9
Hi,

First, try temporarily changing the init: procedure (which I had just copied from the AI code) as follows:
Code:
init:
   Servo_Pos = LIMIT_CCW
   Pause 5000                              ; Do nothing yet
   Low Servo_Pin                           ; Make the Servo pin an Output (Off, Low)
   Pause 5000                              ; Wait another 5 seconds
   Servo Servo_Pin , Servo_Pos             ; Starting position (assumed fully CCW)
   Pause 5000                              ; Allow time for system to stabilise
main:
When you apply the power, observe the Servo and if it twitches in the first 5 seconds, then that is the basic characteristic of the Servo when power is applied and little can be done about this. After 5 seconds the PICaxe switches on its Servo output pin (to a zero level) and again little can be done about any twitch (a pull-down resistor of perhaps 10k across the pin to ground might help), but if the first PAUSE is deleted then these first two potential twitches will merge together.

After a further 5 seconds (i.e. 10 seconds after power is applied, the PICaxe will start sending pulses which should be the same width as when the system was powered Off (unless the Servo was at the opposite end-stop). However, an Analogue Servo may interpret the first pulse differently than a continuous stream of pulses (20 ms apart), which may cause it to twitch away and then (perhaps) return. Again this is really a function (and hazard) of almost any Analogue Servo; perhaps the only thing you can do is to trim the exact starting value (i.e. Servo_Pos = LIMIT_CCW +/- {a small test value} ) to reduce the twitch. Twitches like this would just be considered insignificant when preparing, for example, a model aircraft for flight.

Flenser reported that he hadn't needed to add any (power supply) decoupling capacitors to his test setup, but almost any "commercial" product will have generous decoupling already included. The recommendation for PICaxe is to connect a 100 nF capacitor (usually ceramic or plastic film) within about 1 cm (less than half an inch away) across the PICaxe's supply pins (Legs 1 - 8). On your photo, I can only see an Electrolytic capacitor (of perhaps 10uF ?) at the top-left corner of the breadboard ? If so, the two flyleads also represent a "common impedance" with the Servo power, that can produce an erratic (noisy) supply voltage to the PICaxe whenever the Servo operates. There's no certainty that putting a (preferably non-electrolytic) capacitor directly across the PICaxe pins will help, but the potential issue is not the resistance of the Wires and Electrolytic capacitor as such (which will be quite low), but their Inductance.

It might be that here we have an "exotic" problem such as Radio Frequency Interference or the PICaxe's method of interrupt generation for the Servo Pulses, but the KISS philosophy demands that we should consider the "Simple" possibilities first. ;)

Cheers, Alan.
 
Edited the code, and loaded it into the 08M2. Placed a .1uF (100nF) ceramic capacitor across Picaxe supply (legs 1 and 8). I had to flag down a passing car to get them to show me what you meant by "Picaxe supply pins". Anyways, I also removed the 10uF capacitor you saw in the picture. Then I switched off the power and switched it back on again. I'm happy to report no anomalous behavior from the servo. No kicks, no twitches, no nothing. Just a 90 degree sweep CW on first button press, then 90 sweep CCW, back to the starting point at the second button press. Success, Alan. You fixed it (or did the AI fix it)...just kidding. I am so very grateful to you and Flenser for your assistance :)

Now all I have to do is work the second servo into the code and my Voyager model will be ready to unbox and start building.
 
Hi,

Generally, the 10uF capacitor (or larger) would be best placed close to the Servo (connector). So now is the system now "Twitchless" using the original (post #7) code and the bench PSU , etc. ?

A modification to "remember" the Servo position(s) when power is removed (and restored) should be quite easy to add if you want any help with that. The "Wear Out" issue is unlikely to be a problem if the code is written sensibly, and we're still here to help if you have any difficulties with coding for two Servos, etc..

Thanks for the update, so often these threads just "die" without any satisfactory conclusion.

Cheers, Alan.
 
Kudos to AlleyCat for identifying the issue. My breadboard looks basically the same as Rob53's so it didn't occur to me to recommend moving the capacitor even after seeing his picture.

I have one more change to suggest.

When reading the manual 2 for the servo command I found this comment:
"The ‘servo’ command initialises the pin for servo operation and starts the timer.
Once a pin has been initialised, it is recommended to use the ‘servopos’ command to adjust position. This prevents resetting of the timer, which could cause ‘jitter’"

Implementing this would mean leaving the "servo servo_pin, start_pos" command in the init section unaltered
changing the two "Servo Servo_Pin , Servo_Pos" commands in the main section to be "Servopos Servo_Pin , Servo_Pos"
and then retesting to make sure it all still works without twitching when the servo is moving.
 
So now is the system now "Twitchless" using the original (post #7) code and the bench PSU , etc. ?

If we go back to where we started, then I'm sure the jitter would be back as well, unless you're thinking the addition of the 100nF capacitor is what actually fix it. However, I tried removing the capacitor, and there was no change, it is still "twitch free". I also changed back to the benchtop PSU and put the switch back to C.3 (as I need C.1 for the other servo). Still twitchless. Therefore, I think it's safe to say, the changes in the code is what fixed it.

Implementing this would mean leaving the "servo servo_pin, start_pos" command in the init section unaltered

Did you mean "servo_pos"?

changing the two "Servo Servo_Pin , Servo_Pos" commands in the main section to be "Servopos Servo_Pin , Servo_Pos"
and then retesting to make sure it all still works without twitching when the servo is moving.

This only moves the servo once (90 degrees CW), then after that, it doesn't work at all until I cycle the power switch, then after 5 seconds it expectedly jumps back to start position, then again, it only moves one CW sweep.
 
Hi,

Ah, that makes (more) sense; The SERVO .... OFF instruction certainly should fix the problem. One of the Golden Rules of Hardware and Software development is to "Change only one thing at a time". ;) The puzzle is still, what causes the twitching when the PICaxe program is not executing any Servo-related instructions (at the time) and there are no instructions in the program that are acknowledged to influence the ("background") Servo/Interrupt pulse generation?

"The ‘servo’ command initialises the pin for servo operation and starts the timer. ... it is recommended to use the ‘servopos’ command to adjust position. This prevents resetting of the timer, which could cause ‘jitter’" ...

A "complication" with PICaxe is that it is a "family" of different processors which do not all have the same characteristics. The "old" (pre M2 and X2) chips were much slower and less sensitive to "spikes" on their power supply rail. Thus, there was little emphasis on the need for a 100 nF filtering capacitor in the original documentation (including some circuit diagrams). But I believe all the "AXE" kits and diagrams do include such a capacitor now. Also, the quotation above actually may be incorrect for the M2 chips; The SERVO and "Time" variable use exactly the same Timer Interrupt and AFAIK the hardware timer always continues to run and is not changed, even after a DISABLETIME command (only by a SLEEP). This is confirmed in a statement that after an ENABLETIME, the delay to the next count is not constant or predictable. Although "Time" is a variable, it is documented in some detail in the on-line Command Syntax documentation. The X2 chips do have a capability to change the timing/period of their Servo pulses (so they have no "Time" variable).

A common problem with Servos (and many d.c. motors in general) is that when they are starting to move, they draw a considerable current from the power supply, which may lower the voltage to the PICaxe sufficiently to cause it to Reset (if there is inadequate supply decoupling/filtering). That was the reason for my extending the initial PAUSE instruction(s), to make it obvious if this was happening. But it appears that rob's servo was not even running at the time of the twitching and the PICaxe was executing only "Waiting" instructions (i.e. for a button push/release), so it seems irrelevant whether other parts of the program happen to contain SERVO or SERVOPOS instructions. Similarly, it is a puzzle why holding in the button appeared to make the twitching worse.

However, there are PICaxe instructions that can upset the Servo operation considerably, which is why Pete enquired (in #24) about any Serial commands (and I have avoided using them). This is shown clearly in a Logic Analyser Trace (attached to post #2) which I prepared for another thread some time ago. It shows one Servo pulse delayed by a few milliseconds (which would probably have little or no effect), but a second instruction extends the Servo Pulse for almost 20 ms. :(

Cheers, Alan.
 
the quotation above actually may be incorrect for the M2 chips; The SERVO and "Time" variable use exactly the same Timer Interrupt and AFAIK the hardware timer always continues to run and is not changed,

AllyCat, I agree that the timer generating the 20ms interrupt for the SERVO and "Time" variable is unlikely to be altered because this appears to be a fundamental part of the firmware architecture, one that operates whether or not you choose to use the SERVO command.

However, there also has to be some mechanism for generating the 0.5-1.5ms pulse width every time that 20ms interrupt occurs.
I haven't seen any description of how this is done and as these pulses do not seem to block the execution of the other commands generating the servo pulses doesn't seem to be a software loop, so this comment could still apply.

I chose to post this comment about the SERVO command as the alternative was to keep it to myself. If Rob53 is happy that his current program does not suffer any twitches then changing the code to use SERVOPOS and retesting is not required..
 
The servo is doing something different now. When I turn on the power (battery pack OR BT-PSU) it kicks a little to the left (CCW). It wasn't doing that before, right after I changed the "init" section of the code as per Alan's instructions, it was working perfectly. It didn't do anything when I cycled the power. Now it has that CCW kick when I cycle the power, and it kicks to the left each time I cycle the power. It does this each off/on cycle until it has moved a full 90 degrees to the left of the starting point, which is 4X off/on cycles, then after 10 seconds it jumps back, CW, to the starting point. If I press the button to have it sweep the initial 90 degrees CW, then cycle the power off/on, it will kick a little to the left for each off/on cycle until it has kicked a full 180 degrees, from 90 CW to negative 90 degrees CCW (or 90 degrees CCW from the starting point), which takes 9X off/on cycles. All I did was make the changes Flenser had suggested (Servo Servo_Pin , Servo_Pos to Servopos Servo_Pin , Servo_Pos) and then back again when those changes didn't work. Here is the entire code.......

Code:
#picaxe 08m2
#no_data                                  ; No need to download any Data values
; PICAXE 08M2 Momentary Switch Servo Control     AllyCat October 2025

; #define ACTIVELOW                       ; Uncomment for Alternative pushbutton operation (button to Ground)
; Control/Variables :
  symbol PushButton = pinC.3              ; Press to toggle Servo to move to opposite Endstop
  symbol Servo_Pin = C.4                  ; Control signal to the servo(s)
  symbol Servo_Pos = b21                   ; Just one variable to KISS
; Constants depending on the Hardware configuration/requirements :
  symbol LIMIT_CCW = 105                  ; Endstop for Counter-Clockwise rotation (adjust as required)
  symbol LIMIT_CW = 195                   ; Endstop for Clockwise rotation (adjust as required)
  symbol SWEEP_RATE = 30                  ; 30ms step rate. Increase this number to move Slower (adjust as required)
; Calculate threshold which determines whether to move CW or CCW :
  symbol MIDDLE_I = LIMIT_CCW + LIMIT_CW  ; [Symbol declarations permit only one maths operator]
  symbol MIDDLE = MIDDLE_I / 2            ; Average (Middle) Servo position
 
#IFDEF ACTIVELOW                          ; Pushbutton connected to Ground (0v)
  symbol PRESSED = 0                      ; Logic value when button is pressed
  Pullup %001000                          ; Activate Pushbutton PullUp resistor
#ELSE                                     ; Pushbutton connected to Supply (Vdd)
  symbol PRESSED = 1                      ; Logic value when button is pressed [Use only this line if button is connected to supply rail]
#ENDIF

   init:
   Servo_Pos = LIMIT_CCW
   Pause 5000                              ; Do nothing yet
   Low Servo_Pin                           ; Make the Servo pin an Output (Off, Low)
   Pause 5000                              ; Wait another 5 seconds
   Servo Servo_Pin , Servo_Pos             ; Starting position (assumed fully CCW)
   Pause 5000                              ; Allow time for system to stabilise
main:
  Do : Loop Until PushButton = PRESSED    ; Wait for button to be pressed
  If Servo_Pos <= MIDDLE then             ; Position should be at LIMIT_CCW, so can step immediately
     Do
        Inc Servo_Pos
        Servo Servo_Pin , Servo_Pos
        Pause SWEEP_RATE
     Loop Until Servo_Pos => LIMIT_CW
  Else                                   ; Position should be at LIMIT_CW, so can step immediately  
     Do
        Dec Servo_Pos
        Servo Servo_Pin , Servo_Pos
        Pause SWEEP_RATE
     Loop Until Servo_Pos <= LIMIT_CCW
  Endif
 Do : Loop Until PushButton <> PRESSED    ; If holding the Button IN makes the Jitter Worse the try commenting out this line with a ";"
  Pause 5000            ; Does it Jitter during this period?
  Servo Servo_Pin , OFF    ; Terminate the Servo Pulses (They will restart automatically at the next SERVO instruction)
GoTo main
 
Hi,

Basically, with that latest version of the program, anything that happens within the first ten seconds after switching on the power is a function of the Servo (and perhaps the power supply and supply decoupling arrangements), because the PICaxe has not started executing any "useful" instructions. More of interest is what happens in the first five seconds after the Servo reaches the first (or any) of its controlled sweeps (as I put in comments in the last few lines of the program).

The best suggestions that I can make (at the moment) is to ensure that you have 100 nF across the PICaxe supply pins, 10uF (or more) across the Servo connector, and perhaps some hundreds of ohms between their two "5 volt" rails (if a single supply is being used). Then reduce or remove the additional PAUSEs which were added only to try to isolate/identify the potential "starting" disturbances.
_____

More for Flenser and any others following the technical aspects of this issue, here is some background information that I was preparing:

Another uncertainty is whether SERVO .... OFF is exactly the same as SERVO ... 0 (zero) . They might be identical, or the latter might still be running some additional code, before generating a "zero width" pulse. The command syntax for SERVOPOS specifies that "A servo command on the same pin number must have been previously issued.", but does an OFF / zero parameter cancel that? Rob's comment below suggests that it does (assuming that an OFF was included at the end of the first pass):

"changing the two "Servo Servo_Pin , Servo_Pos" commands in the main section to be "Servopos Servo_Pin , Servo_Pos"..

This only moves the servo once (90 degrees CW), then after that, it doesn't work at all until I cycle the power switch, then after 5 seconds it expectedly jumps back to start position, then again, it only moves one CW sweep.

Appendix 4 in Manual 2, indicates that the SERVO command uses Timers 1 and 2, so presumably Timer 2 is used to time the width of the Servo Pulses (generated in sequence after the T1 interrupt pulse), leaving Timer 1 for the basic 20 ms timer interrupt (but I haven't checked this on real hardware)? Not directly related to this thread, but the PWMOUT command reference gives a clarification of some more generic statements made elsewhere:

"4) The servo command cannot generally be used at the same time as the pwmout command. On older PICAXE parts the same internal timer (timer2) is used for both pwmout and servo, so these commands cannot be used at the same time. However some newer parts have additional dedicated internal timers that allow pwmout and servo to work together. This applies to these pwmout channels:

14M2B.2, B.4 (C.0, C.2 share the servo timer)
18M2B.3, B.6
20M2B.1, C.2 (C.3, C.5 share the servo timer)
28X2B.0, B.5 (C.1, C.2 share the servo timer) "
Note that PWMDUTY ... is a very different command to PWMOUT ... and it can be important to use the correct one (IMHO usually PWMOUT). To expand on the details in Appendix 4, the M2 chips do not appear to have a "Timer3" and the 08M2 has only one PWM output pin (C.2). However, the larger M2s have 2 or 4 PWM output pins (with some more related to HPWM ) and hardware Timers 4 and 6. Unfortunately, these two timers are in "SFR Bank 8" which is not accessible via the PEEK/POKESFR commands. However, the four PWM/CCP silicon modules are "vectored" (via an accessible SFR, CCPTMRS = $BE) to the three timers 2 , 4 and 6, so in principle it appears possible to run up to 4 PWM outputs and 8 Servo outputs at the same time (slightly limited by the available pin capabilities), but not all with different base frequencies. ;)

Cheers, Alan.
 
Rob's comment below suggests that it does (assuming that an OFF was included at the end of the first pass):
This only moves the servo once (90 degrees CW), then after that, it doesn't work at all until I cycle the power switch, then after 5 seconds it expectedly jumps back to start position, then again, it only moves one CW sweep.

This is a red-herring.
This program was behaving exactly as it was coded to do and so you should ignore this. It does not represent any problem.

In my post #32, where I gave Rob the changes to make to use SERVO_POS in place of the SERVO command in the main section of the program, I had missed that the SERVO OFF command had been added at the end of the main section.
So
- The SERVO command in the init section moved it fully CCW
- The SERVO_POS command in the main section moved it fully CW when the button was first pushed
- The SERVO OFF command at the end of the main section disabled sending any pulses to the servo
- Then, whenever you push the button again, the SERVO_POS command in the main section does nothing because the SERVO function has been disabled.
 
Last edited:
Rob,

I suggest you go back to the program you were using in post #30, where it was working with no twitching.

That would only leave adding in code for the 2nd servo to do so you can proceed with the rest of your project.

Pls post that code here so that there is a record of it on the forum as the solution to your twitching issue and so that we can use it as the starting point for adding in the 2nd servo.
 
Last edited:
AllyCat,

Like you, I'm posting the link to this other thread "Servopos" Command : servo jerks! that discusses servo jitter so the people who get a hit to this thread will more easily find it.

In that thread Hippy makes these comments about the SERVO and SERVOPOS commands:
The SERVO and SERVOPOS commands are mostly there for those doing simple school projects and similar where a bit of jitter doesn't matter if it does occur.

For a simple level-crossing project say, where a servo may lift a hinged barrier, some bounce is to be expected anyway. Servo consistency isn't as important as allowing students and learners to easily control the servo.

Having the servo just do its thing automatically in the background while other commands execute makes things easier to code but can sometimes cause jitter when the main program affects the timing or the program itself wants to update I/O at exactly the same time the servo control task needs to. The chance of that should be incredibly low but Sod's Law has it that those who least want jitter will most likely experience it.

In this thread Hippy and MikeyBoo describe two alternative methods for driving servos with less risk of twiching than using the SERVO and SERVOPOS commands.
 
Back
Top