Need help with train horn for model railway

i am trying to setup a code so that when i hold down a momentary push button it will activate a horn and when i release the button it it will stop

your help would be much appreciated

What are the voltage, current, frequency demands of the horn? Can you post a data sheet?

Is it passive (only needs an on/off signal) or active (needs pulses)?

if ( button_pin == HIGH ) {

digitalWrite ( horn, HIGH);


I respectfully disagree. I would wire the momentary switch to ground and an input with its pinMode set to INPUT_PULLUP. In that case the input would read HIGH when the switch is not pressed and LOW when pressed, making the code more like:

if(digitalRead(buttonPin) == LOW)
   //sound horn

Hello ang good morning
It´s quite simple


With the asumption of pinMode(buttonPin,INPUT_PULLUP);

I fail to see the difference in outcome...Could you elaborate maybe?

Using pinMode(buttonPin, INPUT_PULLUP); makes use of the internal pullup resistor instead if an external pulldown resistor with the switch wired to Vcc and an input. Wiring the switch to ground and the input with internal pullup also means that you are not running a hot wire (carrying Vcc) to the switch.

Perhaps it would be good to provide an explanation of the use of the conditional or ternary operator.

Why ?

What else do you want to do with the Arduino ?

1 Like

Hello and good morning
Many thanks for providing the link to the explanation of the ternary operator. Good job.

1 Like

all i wanted to do was play a train horn through a micro sd shield and use arduino uno

i was gonna customize the below code but have no idea were to start

#include <SD.h>                           //include SD module library
#include <TMRpcm.h>                       //include speaker control library

#define SD_ChipSelectPin 4                //define CS pin

TMRpcm tmrpcm;                            //crete an object for speaker library

void setup(){
  tmrpcm.speakerPin = 9;                  //define speaker pin. 
                                          //you must use pin 9 of the Arduino Uno and Nano
                                          //the library is using this pin
  if (!SD.begin(SD_ChipSelectPin)) {      //see if the card is present and can be initialized
    return;                               //don't do anything more if not
  tmrpcm.setVolume(6);                    //0 to 7. Set volume level"1.wav");         //the sound file "1" will play each time the arduino powers up, or is reset

void loop(){}

anyway help would be good if someone could put me in the right direction of were i should start on this code

the horn is a mp3 or wav. file

That kind of information should have been in the original post. I have wasted enough time here.

But you didn't mention the SD shield nor the Uno in your posting, nor provide the code. The guidelines for how to post aren't a secret!

But the contents of the sketch is top secret.