Im a PLC engineer, so Im not a complete new guy, but Im making a controller to be used to control some functions in Lionel newer trains.
-
Operator cab light goes out when voltage is sensed on motor leads, so train in motion, LED goes OFF, train stopped LED is ON
-
A IR sensor reads a tape encoder, counts the pules then activates a relay. This is to turn on and off a blower motor to simulate chuffing smoke out of the smoke unit. When drive motor has no voltage then let the fan just run constantly.
-
Headlight LED dims when no voltage on motor and brightens when voltage at motor.
I managed to do some coding, please review it. I havent done any of #3 yet.
Thanks so much!!!
// Train Controller V1
// These constants won't change:
const int analogPin = A0; // Motor Voltage via 0-25vdc divider to 0-5vdc
const int ledPin = 2; // Cab Light LED
const int threshold = 400; // Motor Voltage at which the LED goes off
const int encoderPin = 3; // the pin that the encoder is attached to
const int relayPin = 3; // the pin that the Relay is attached to
// Variables will change:
int encoderCounter = 0; // counter for the number of encoder stripes
int encoderState = 0; // current state of the encoder
int lastEncoderState = 0; // previous state of the encoder
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the Encoder pin as an input:
pinMode(encoderPin, INPUT);
// initialize the Relay as an output:
pinMode(relayPin, OUTPUT);
// initialize serial communication:
Serial.begin(9600);
}
void loop() {
// Cab Light Logic
// read the voltage of the motor:
int analogValue = analogRead(analogPin);
// if the analog value is high enough, turn on the LED:
if (analogValue > threshold) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
// Chuff Logic
// read the encoder input pin:
encoderState = digitalRead(encoderPin);
// compare the encoderState to its previous state
if (encoderState != lastEncoderState) {
// if the state has changed, increment the counter
if (encoderState == HIGH) {
// if the current state is HIGH then the encoder went from off to on:
encoderCounter++;
Serial.println("on");
Serial.print("number of encoder pulses: ");
Serial.println(encoderCounter);
} else {
// if the current state is LOW then the encoder went from on to off:
Serial.println("off");
}
// Delay a little bit to avoid bouncing
delay(50);
}
// save the current state as the last state, for next time through the loop
lastEncoderState = encoderState;
// turns on the RELAY every four pulses by checking the modulo of the
// encoder counter. the modulo function gives you the remainder of the
// division of two numbers:
if (encoderCounter % 4 == 0) {
digitalWrite(relayPin, HIGH);
} else {
digitalWrite(relayPin, LOW);
}
}