Join the AMS - Registered Forum users can become members of the AMS and it's free ...... To join register on the forum first then follow the forum link to our membership form which is on our website

For further details of any events shown here also see the "Shows and Events" section on the forum

Let us know of your plans for 2018 and we will promote them on this Forum



. ,Alfold Charity Model Boat Show, Surrey, 2nd & 3rd June 2018

Exeter & District Model Boat Club, Sunday 10th June

.Norwich MBC Weekend 28,29 July 2018
.Model Boat Convention, Haydock Park, 25,26th August

.Barrow in Furness MBC, Sub Day and Regatta,Sunday 2nd September 2018.

.Bluewater, Dartford, Chantry Model Boat Club, Sunday 2nd September

. Bournville MBC, Birmingham, Sunday 2nd September

,The Model Show,Poynton, Stockport (with swimming pool) 15,16th September 2018

Who is online?

In total there are 5 users online :: 0 Registered, 0 Hidden and 5 Guests


Most users ever online was 37 on Sun Mar 13, 2011 11:27 am

Latest topics

» engle piston tank convert to servo control
Today at 5:48 pm by timgarrod

» model submarine test tank on the cheap
Yesterday at 7:27 pm by merriman

» "Shadow Divers"
Yesterday at 1:35 pm by david f

Tue May 15, 2018 7:46 pm by bwi

» Bournville May 2018
Tue May 15, 2018 8:55 am by david f

» small diameter static-diving type SubDriver
Fri May 11, 2018 2:10 am by merriman

» bournville in a couple of days
Tue May 08, 2018 9:13 pm by timgarrod

» For Sale almost new
Sat May 05, 2018 9:37 am by johnayre1

» For Sale almost new
Thu May 03, 2018 12:29 pm by johnayre1


Our users have posted a total of 10550 messages in 1727 subjects

We have 764 registered users

The newest registered user is tally ho

    Arduino proportional control of a piston tank

    david f
    AMS Treasurer

    Posts : 1956
    Join date : 2010-11-10
    Age : 67
    Location : Cumbria

    Arduino proportional control of a piston tank

    Post  david f on Thu Dec 07, 2017 10:02 am

    Just done a bit more work on this inspired by Eric Weber's work on the SubCommittee Forum.

    Eric's hardware choice works nicely and it is ready built from an eBay supplier, so no need for a soldering iron!

    The software, as shown, works with a Hall Switch to count revs and has a failsafe. The piston tank is protected by limit switches - I prefer the separate circuit for this with diodes across the switches, as shown in Norbert Bruggen's book.

    I am quite a convert to the Arduino, by the way. My original routine using PICs took about a year to get going. This version on the Arduino - not much time spent over 2 months. It uses an Arduino Nano - my favourite.

    Some health warnings this version has only worked on the bench, so far, not yet in a model submarine. Use it at your own risk.

    A short video showing the controller working with a home made piston tank built for my Nordenfelt subs.


    The software is best downloaded from my site on Github (my first attempts at this!):


    The sketch follows but you are best going to the Github:

    Proportional Piston Tank Controller by David Forrest based on work by Eric Weber and Gabriel Staples. 24/10/2017
     My code changes are labelled RDF. This version New_Piston4e (5/12/2017)
     Hall switch (A1104 from Allegro) used to count revolutions and give proportional control.
     An error signal is generated from the Hall switch count and the r/c input pulse.
     This is fed to the H bridge and motor (It is a servo really)
     When the unit is switched on it has 35 seconds to empty the piston tank and set the switch counter to zero.
     Loss of r/c signal (Failsafe) empties the piston tank and resets the switch counter.
     The Hall effect sensor is switched on when the south pole of a magnet comes close to the front tapering face of the sensor.
     Hall switch needs +5v supply.
     Nov 2017 Put pullup in software this seems to eliminate the need for a pullup resistor.
     Nov 2017 Built In LED now shows forward & reverse
     AnalogSmooth routine not actually used.

     Notes by Gabriel Staples
     -read in any pulsing signal on Arduino pin INPUT_PIN (defined below), to get its period (us) & freq (Hz), with a time resolution of 0.5us
     --you can read in any pulse, including standard PWM signals, Radio Control (RC) PWM signals, etc.
     -I am using some low-level AVR code, which requires using some built-in Arduino macros to do pin-mapping.
     -this code only reads in a single channel at a time, though it could be expanded to read in signals on every Arduino pin, digital and analog, simultaneously.
     --this would be lots of work, so for now I'll leave that up to you.
     -this code should be able to read in any pulse between approximately 10~20us and 35.79 minutes; I'll let you experiment
     to find the actual shortest pulse you can measure with it

     By Gabriel Staples
     -My contact info is available by clicking the "Contact Me" tab at the top of my website.
     Written: 28 Nov. 2013
     Updated: 21 March 2015

     Some References:
     -to learn how to manipulate some of the low-level AVR code, pin change interrupts, etc, these links will help
     --ATmega328 datasheet: http://www.atmel.com/Images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet.pdf
     --See the *many* very helpful links at bottom of this article: http://www.electricrcaircraftguy.com/2014/01/the-power-of-arduino.html
     --reference the Arduino source code, ex:
     ---C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\Arduino.h
     ---C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\wiring_digital.c
     ---C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard\pins_arduino.h


     Option 1) To measure the pulses from an Arduino PWM pin, ex: pin 5 or 9, connect Pin 5 or 9 (a PWM output) to INPUT_PIN (the pulse reader input)
             -see the setup() function for commanding the PWM output to begin, so you can have something to read in

     Option 2) To measure an RC PWM servo-type signal coming from an RC Rx:
     -Power the Rx by connecting 5V to + on the Rx, and GND to - on the Rx
     -Connect the channel signal you want to measure on the Rx to the INPUT_PIN on the Arduino

    #include <AnalogSmooth.h>

     Smooths signal jitter on analog inputs by averaging
     concurrent readings. The number of readings averaged can
     range from 1 (no smooting) to 100.

     The more readings you average the more consistent the signal
     becomes. At the same time it takes longer to detect actual
     changes in the signal.

    #include <eRCaGuy_Timer2_Counter.h>

    //#include <avr/wdt.h>    // Include watch dog timer

    #define fastDigitalRead(p_inputRegister, bitMask) ((*p_inputRegister & bitMask) ? HIGH : LOW)

    //Global Variables & defines
    const byte INPUT_PIN = A5; //RDF changed to A5 .you can change this to ANY digital or analog pin, ex: 10, 8, A0, A5, etc,
    //EXCEPT A6 and A7 (which exists on the Nano and Pro Mini, for example, and are NOT capable of digital operations)
    byte input_pin_bitMask;
    volatile byte* p_input_pin_register;

    //volatile variables for use in the ISR (Interrupt Service Routine)
    volatile boolean output_data = false; //the main loop will try to output data each time a new pulse comes in, which is when this gets set true
    volatile unsigned long pulseCounts = 0; //units of 0.5us; the input signal high pulse time
    volatile unsigned int pd = 0; //units of 0.5us; the pulse period (ie: time from start of high pulse to start of next high pulse)

    // Simple counter from below (RDF)

    int ip_pulse = 0;  // Variable from TX pulse by RDF

    int errsig = 0; // Error signal for servo action (Hall count minus PWM input)


    int state = LOW;

    int lastState = LOW;

    int count = 0;

    int reverse = 15;

    int failsafe_count = 1;

    //Digital input pin 8 for Hall switch input.

    unsigned long duration;

    int analog = errsig ;

    float analogSmooth;

    // Defaults to window size 10
    AnalogSmooth as = AnalogSmooth();

    // Window size can range from 1 - 100
    AnalogSmooth as100 = AnalogSmooth(100);

    void setup() {
     // put your setup code here, to run once:

     pinMode(8, INPUT_PULLUP);// Put Pullup on Hall switch input

     state = digitalRead(8);

     pinMode(INPUT_PIN, INPUT_PULLUP); //use INPUT_PULLUP to keep the pin from floating and jumping around when nothing is connected

     //configure timer2

     //prepare for FAST digital reads on INPUT_PIN, by mapping to the input register (ex: PINB, PINC, or PIND), and creating a bitMask
     //using this method, I can do digital reads in approx. 0.148us/reading, rather than using digitalRead, which takes 4.623us/reading (31x speed increase)
     input_pin_bitMask = digitalPinToBitMask(INPUT_PIN);
     p_input_pin_register = portInputRegister(digitalPinToPort(INPUT_PIN));


     //start PWM output (to read in its pulses, for use in Circuit 1 as described above)
     pinMode(5, OUTPUT);
     pinMode(9, OUTPUT);
     analogWrite(5, 10); http://976.5625Hz, with high pulses of ~1/976.5625 x 10/256 = 40us; Connect pin 5 to INPUT_PIN and open serial monitor & you will see approximately this
     analogWrite(9, 128); http://490.20Hz, with high pulses of ~1/490.2 x 128/256 = ~1020us; Connect pin 9 to INPUT_PIN and open serial monitor & you will see approximately this
       PWM Notes:
       -PWM on pins 5 & 6 occurs at 976.5625Hz; see here: http://playground.arduino.cc/Main/TimerPWMCheatsheet
       -PWM on pins 9 & 10 occurs at 490.20Hz

     Serial.begin(9600);   //RDF changed from 115200
     Serial.print(F("Begin waiting for pulses on pin ")); Serial.print(INPUT_PIN);
     Serial.println(F(".\nData will be printed after each pulse is received."));

     // Test.connect motor controller pins to Arduino digital pins
     // motor one
     // https://tronixlabs.com.au/news/tutorial-l298n-dual-motor-controller-module-2a-and-arduino

     int enA = 3;
     int in1 = 2;
     int in2 = 4;

     // set all the motor control pins to outputs
     pinMode(enA, OUTPUT);
     pinMode(in1, OUTPUT);
     pinMode(in2, OUTPUT);

     //Test. This will be used for piston tank initial setup

     digitalWrite(in1, HIGH); //Swap in1 & in2 to reverse motor
     digitalWrite(in2, LOW);
     digitalWrite(enA, HIGH); //High runs motor

     delay(35000); //35 second delay to get piston tank empty from the start.

     //set rev counter to zero

     count = 0;

     // initialize digital pin LED_BUILTIN as an output.
     pinMode(LED_BUILTIN, OUTPUT);

     // Setup code finishes here

    void loop() {
     // put your main code here, to run repeatedly:

     //local variables
     static float pulseTime = 0; //us; the most recent input signal high pulse time
     static float pd_us = 0; //us; the most recent input signal period between pulses
     static float pulseFreq = 0; //Hz, the most recent input signal pulse frequency

     if (output_data == true) //if a pulse just came in
       //turn off interrupts, grab copies of volatile data, and re-enable interrupts
       output_data = false; //reset
       unsigned long pulseCountsCopy = pulseCounts; http://0.5us units
       unsigned long pdCopy = pd; http://0.5us units

       //do calculations
       pulseTime = pulseCountsCopy / 2.0; //us
       pd_us = pdCopy / 2.0; //us
       pulseFreq = 1000000.0 / pd_us; //Hz

       //failsafe_count = ++failsafe_count; //Increment failsafe count by RDF
       //if ( pulseTime > 1000 ) {
       //  failsafe_count = 0;  // set counter to zero if pulses are > 1000
       // }

       //print values
       //(optionally, add extra code here to not print after EVERY pulse is received, as this can result in serial data coming in excessively fast when pulses come in at a high freq)
       //Serial.print(F("pulsetime(us) = ")); Serial.print(pulseTime);
       //Serial.print(F(", pd_us(us) = ")); Serial.print(pd_us);
       //Serial.print(F(", pulseFreq(Hz) = ")); Serial.println(pulseFreq);

       Serial.print(F("  Hall Count=")); Serial.println(count);
       Serial.print(F("IP Pulse=")); Serial.print(ip_pulse);
       //Serial.print(F("Error signal = ")); Serial.print(errsig);
       //Serial.print(F("reverse = ")); Serial.print(reverse);
       //Serial.print(F("Failsafe = ")); Serial.print(failsafe_count);

       // Hall switch counter, with increment/decrement depending on direction of rotation by RDF

       int enA = 3;
       int in1 = 2;
       int in2 = 4;

       if (state == HIGH && lastState == LOW) {

         //  if (reverse > 0 ) { ++count; } else { --count; }
         if (reverse > 0 ) {
         } else {

       lastState = state;

       state = digitalRead(8);

     // Calculations here

     ip_pulse = (((pulseTime - 1005) / 7) - 20); // For a screw length of about 250 revs. 25 is stick trim factor

     //AnalogSmooth section not used and commented out

     //int analog = ip_pulse; // put ip_pulse into AnalogSmooth

     // Defaults to window size 10
     //AnalogSmooth as = AnalogSmooth();

     //int analogSmooth = as.smooth(analog);

     //ip_pulse = analogSmooth;

     errsig = count - ip_pulse;

     // Testing motor output pins

     int enA = 3;
     int in1 = 2;
     int in2 = 4;

     // If errsig is negative, reverse the motor

     if (errsig < 0) {
       digitalWrite(in1, LOW);   //Swap in1 & in2 to reverse motor
       digitalWrite(LED_BUILTIN, HIGH);   // turn the Built In LED on (HIGH is the voltage level)
       digitalWrite(in2, HIGH);
       digitalWrite(enA, HIGH);    //High runs motor
       reverse = -7;

     // If absolute value of errsig is less than 20, stop the motor

     if ((errsig < 10) && (errsig > -10))
       digitalWrite(in1, HIGH);   //Swap in1 & in2 to reverse motor
       digitalWrite(in2, LOW);
       digitalWrite(enA, LOW);    //High runs motor
       reverse = 2;

     //Set motor to forward
     if (errsig > 0) {
       digitalWrite(in1, HIGH);   //Swap in1 & in2 to reverse motor
       digitalWrite(LED_BUILTIN, LOW);   // turn the Built In LED off(HIGH is the voltage level)
       digitalWrite(in2, LOW);
       digitalWrite(enA, HIGH);    //High runs motor
       reverse = 8;

     // If Failsafe triggered - set piston to empty
     if ((pulseFreq > 53) || (pulseFreq < 49) && (failsafe_count > 1000))

       failsafe_count = ++failsafe_count; //Increment failsafe count by RDF

     //Failsafe routine (like piston tank initial setup.)

     digitalWrite(in1, HIGH); //Swap in1 & in2 to reverse motor
     digitalWrite(in2, LOW);
     digitalWrite(enA, HIGH); //High runs motor

     delay(35000); //35 second delay to get piston tank empty.

     //set rev counter to zero

     count = 0;

       digitalWrite(in1, HIGH);   //Swap in1 & in2 to reverse motor
       digitalWrite(in2, LOW);
       digitalWrite(enA, HIGH);    //High runs motor
       Serial.print(F("Failsafe = ")); Serial.print(pulseFreq);

     //else {failsafe_count  = 0;

    } //end of loop()

    ////Use macro instead
    //boolean fastDigitalRead(volatile byte* p_inputRegister,byte bitMask)
    //  return (*p_inputRegister & bitMask) ? HIGH : LOW;

    void pinChangeIntISR()
     //local variables
     static boolean pin_state_new = LOW; //initialize
     static boolean pin_state_old = LOW; //initialize
     static unsigned long t_start = 0; //units of 0.5us
     static unsigned long t_start_old = 0; //units of 0.5us

     pin_state_new = fastDigitalRead(p_input_pin_register, input_pin_bitMask);
     if (pin_state_old != pin_state_new)
       //if the pin state actualy changed, & it was not just noise lasting < ~2~4us
       pin_state_old = pin_state_new; //update the state
       if (pin_state_new == HIGH)

         t_start = timer2.get_count(); http://0.5us units
         pd = t_start - t_start_old; http://0.5us units, the incoming pulse period
         t_start_old = t_start; http://0.5us units; update
       else //pin_state_new == LOW
         unsigned long t_end = timer2.get_count(); http://0.5us units
         pulseCounts = t_end - t_start; http://0.5us units
         output_data = true;

    //Interrupt Service Routines (ISRs) for Pin Change Interrupts
    //see here: http://www.gammon.com.au/interrupts

    //PCINT0_vect is for pins D8 to D13

    //PCINT1_vect is for pins A0 to A5

    //PCINT2_vect is for pins D0 to D7

    void configurePinChangeInterrupts()
     //Pin Change Interrupt Configuration
     //see ATmega328 datasheet, ex: pgs. 73-75
     //also see: C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard\pins_arduino.h for the macros used here
     //1st, set flags on the proper Pin Change Mask Register (PCMSK)
     volatile byte* p_PCMSK = (volatile byte*)digitalPinToPCMSK(INPUT_PIN); //pointer to the proper PCMSK register
     *p_PCMSK = _BV(digitalPinToPCMSKbit(INPUT_PIN));
     //2nd, set flags in the Pin Change Interrupt Control Register (PCICR)
     volatile byte* p_PCICR = (volatile byte*)digitalPinToPCICR(INPUT_PIN); //pointer to PCICR
     *p_PCICR |= _BV(digitalPinToPCICRbit(INPUT_PIN));

     //  //ex: to use digital pin 8 as the INPUT_PIN:
     //  //turn on PCINT0_vect Pin Change Interrupts (for pins D8 to D13); see datasheet pg. 73-75.
     //  //1st, set flags on the proper Pin Change Mask Register
     //  PCMSK0 = 0b00000001; //here I am setting Bit0 to a 1, to mark pin D8's pin change register as on; for pin mapping see here: http://arduino.cc/en/Hacking/PinMapping168
     //  //2nd, set flags in the Pin Change Interrupt Control Register
     //  PCICR |= 0b00000001; //here I am turning on the pin change vector 0 interrupt, for PCINT0_vect, by setting the right-most bit to a 1

    AMS Website Webmaster

    Posts : 209
    Join date : 2013-04-23
    Age : 37

    Re: Arduino proportional control of a piston tank

    Post  timgarrod on Thu Dec 07, 2017 5:58 pm

    Cheers David,

    this was something i was planning to do but wasn't sure were to start.




    Posts : 97
    Join date : 2015-04-01

    Re: Arduino proportional control of a piston tank

    Post  tsenecal on Fri Dec 08, 2017 4:38 am

    looks very good... would it be possible to have a list of parts? I liked the youtube video as well... seems nice and stable, no "hunting" once the piston position is matched to the stick position.
    david f
    AMS Treasurer

    Posts : 1956
    Join date : 2010-11-10
    Age : 67
    Location : Cumbria

    Re: Arduino proportional control of a piston tank

    Post  david f on Fri Dec 08, 2017 9:20 am

    For hardware details I'm best just quoting Eric's words over on the SubCommittee:

    "Here is what you need:
    1x Arduino Nano Board - ~2 USD
    (purchase of ebay. Example: http://www.ebay.com/itm/1-2-5-10PCS-...o/282228063941 )

    Motor Speed Controller:

    Option 1 – H-Bridge (use the first code sample and wiring diagram below) – NOTE: current is limited with the below module to 2A. My tank pulled more amps so I want with the ESC instead.
    1x H-Bridge – L298N - ~2 USD
    (purchase of ebay. Example: http://www.ebay.com/itm/Stepper-Moto...o/170926726867 )"

    His full thread is here:


    There are not many other bits. The Allegro Hall switch (A1104 ) I got on eBay. I have a couple of ordinary diodes (but 10amp!) wired across the microswitches.

    You make an interesting point Tim T about the lack of "hunting".

    I used a 40Mhz receiver for most of the trials because it is more prone to interference and "glitching" than a 458 one.

    All the software has is a "deadband" of  +/- 10 counts. The original pic software had a low speed approach to the set point and a few other things as well.

    They are not really necessary as long as you have a fairly slow geared motor. The tank in the video uses a 30:1 geared motor. This also keeps the current down. (less than 0.2 amps for the one in the video)

    A slow speed tank is OK with proportional control, I think. You just set the stick and go and do something else.

    I really like piston tanks but the thing that still holds them back is making them. Probably impossible without a lathe.

    Many thanks for the interest!



    Posts : 97
    Join date : 2015-04-01

    Re: Arduino proportional control of a piston tank

    Post  tsenecal on Fri Dec 08, 2017 5:23 pm

    eric's words on subcommittee ring absent in my case.... even though i have an account on their forum, i am not a member of the subcommittee, and that thread is in their restricted "private" area, accessible to members only.

    that also explains why i never saw the original posting on subcommittee when it was first posted...

    Sponsored content

    Re: Arduino proportional control of a piston tank

    Post  Sponsored content

      Current date/time is Fri May 25, 2018 11:37 pm