simond

Western Thunderer
I doubt it’s beyond you or indeed any of us, but where I would agree is that inevitably there is a simple line of code an example of which one cannot find anywhere and on which everything depends.

Then, after much googling…
 

michael080

Western Thunderer
What I am trying to say is, when I wanted to add some new functionality for my own Arduino projects, and found that I had to write an interrupt handler and alter the PWM frequency to drive a motor, I met up with some cerebral end stops.
Fully understand what you mean. Arduinos are nice devices as long as you stay within its framework. If you need anything interrupt driven, it may be easier to download the microchip studio and program directly on bare silicon. The MC-studio has a nice library of examples. However, for interrupts, I recommend the corresponding atmega328P manual .
But then, this might be daunting for many of us.

Michael
 

76043

Western Thunderer
I successfully tried out the predecessor to DCC-EX, DCC++ as I had an Arduino kicking around. I recently looked at it again to see how I could make it work with an Android phone as a throttle and found I need to upgrade to an Arduino Mega, with a WiFi module. All well within my cheapskate budget, but then I realised I had a twin track panel mount Gaugemaster feedback controller and a power supply staring at me and thought, "use what I have in stock".

But DCC-EX if it works as easy as DCC++ is a no brainer and a fraction of the price of a bells and whistles DCC system. I'd definitely use this for my potential O gauge system.
Tony
 

Richard Gawler

Western Thunderer
Arduinos are nice devices as long as you stay within its framework.
This is a moot point, and I know now it is where I kept going wrong. I would find some example code, and try to add to it. The example code had invariably been created by someone who knew the limitations, and it was me who went blindly off to find myself floored by the string handling (in the C++), and the lack of floating point implementation (in the C) and so on.
 

Stuart Birks

Active Member
There is a trend among programmers that give code examples to give an example that demonstrates as many of the features of a function as possible, making it difficult to extract the simple bit of code that you really want. This is not limited to Arduino code but everything, C, Java, Python and everything else. Just trying to copy a bit of sample code without understanding what is going on is doomed to failure. You need to understand what is going on as there may be header files to include, variables to define and initialise and then know what variables to pass to a function.
This is NOT difficult and easilly witin the abilities of most people BUT it is essential to get an understanding of how things all fit together. Just getting a program to compile does not mean it will run. If it does run it does not mean it will do what you wanted and especially when working with an Arduino the code might be correct but there may be a problem with whatever you have connected it to. There is no quick fix to any of this and if you want to persue using an Arduino (or any of the other micro controllers, they will all have the same problem) then you have to be prepared to spend many frustrating hours puzzling through reference pages. The Arduino language reference Arduino Reference - Arduino Reference is very good at explaining functions but no good at all in helping you decide which one to use in the first place.
You will also find that if you buy various bits of electronics and especially shields (expansion boards that plug directly into an Arduino) then the vendor will often give a link to a library of code to operate their hardware.
That is a long winded way of saying an Arduino is not easy but very rewarding when you finally do get it to do what you want.
To try and reply to a few comments made.
Interrupt processing is straight forward but think hard about do you really need it. Most things can be handled within the normal code loop.
C is famous for its total absesce of string handling and anything to do with strings is difficult, usually ending up with indexing through a character array. Like everything else its ok when you understand it.
If you have a Pentroller or Gaugemaster controller that you like, go for creating an electronic interface. Then the output code from the Arduino is as simple as analogWrite(pin, value);
Personally I can see nothing that I would ever want to communicate with an Android device although I am sure many would disagree with me. Give me a mechanical switch or potentiometer any day.
Finally, understand what an Arduino can and cannot do so you can decide when it is an appropriate solution and when it isn't.
Stuart
 

Richard Gawler

Western Thunderer
Well, I bought an Arduino starter kit during the lockdown so I could have a go at making a self-driving car. Not quite as ambitious as it sounds because it was Magnorail-based, but I did want it to start and stop, accelerate and decelerate, and reproduce oversteer and understeer. I also wanted a dashboard display to show what was going on, with a speedometer and lap counter. And it all worked out fine in the end, sketch attached.

But (a very big but) I found it all incredibly wearying. I finished it feeling the dashboard display only existed for debugging, and the whole thing was really a very laborious script not a properly responsive and portable program. I think, the whole structure of the code should be based on a much smaller loop with interupts arriving from the position sensors (the four reed switches) telling the motor (moving the car) to change speed and the servo (over/understeer) to move the chain.

The code does set up the Arduino to drive a Magnorail motor, and new LCD characters with true descenders, and maybe these are reusable to folk here. It all works nicely, but it ended up too hardware-specific for my liking - it only works because I have arranged the time spent changing chain speed and moving the servo to not interfere with reading the next reed switch.

A part of me says, this would be a lot easier with multiple Arduinos, one for the motor, one for the servo, one checking for switch trips. A person with the necessary experience might see these as objects well within the processing capacity of a single Arduino; and there are I/O pins spare; but somehow the fun just seeped away and I never brought myself to do the scenics.

Clyde Humphries, the proprietor of Magnorail Oz, made some videos using my footage which are quite fun, for example:

Whether the Arduino was or wasn't the appropriate approach to this, well I'm not sure; but I suspect it could be, in more experienced hands. This was my first go with C and C++ . . . so I have had a go, but never again confused.png

Edited as underlined to try to clarify.
 

Attachments

  • MagnorailProcessor_v0.8.ino
    38.5 KB · Views: 7
Last edited:

Richard Gawler

Western Thunderer
Finally, understand what an Arduino can and cannot do so you can decide when it is an appropriate solution and when it isn't.

I think "ability" comes into the assessment too. I found it a doddle to find the code to make an Arduino move a servo, and straightforward to adapt the code to suit my own servo. The display was easy too. Controlling the motor speed while keeping the motor quiet was harder, as was detecting the various reed switches and the control button. But making the code non-blocking so it could respond to these five inputs and update its various outputs in a timely manner, while keeping track of everything which was going on, just felt like standing at the bottom of a vertical cliff looking upwards. Hence my thinking of my code as being like a rather lengthy script.

My gut feeling is, a microcontroller was a better choice than something with an operating system for me, because it took me back to the 6800 and the assembler I learnt about at university and I had something from there to build on. But maybe you would nudge the new user, especially the hobbyist wanting to make something original (not a rework of someone else's project), towards a different platform or a different language?
 
Last edited:

Stuart Birks

Active Member
That is very impressive and you clearly have some programming experience and ability. Near the start of this thread Timbersurf gave a link to Rudys Model Railway channel here Rudys Model Railway It is the best introduction to Arduino programming I have come across. You mention the problem with functions blocking the code. In episode 13 he describes the use of the timer function millis() which can be used to prevent functions locking the program. You also say you have problems with motor noise from the PWM signal which is very common. Did you try just running it on simple DC just varying the voltage. It might have been a simpler solution. If you want to move the servo in a gentler way there is a library providing a function for variable speed servo movement. I used this on my signal arm movement for the arm bounce movement.
An Arduino is a good platform for this type of work. I have zero experience of other platforms so I would not be able to suggest an alternative.
 

Paul_H

Active Member
I’d like to add to this very useful, but a bit old, resource thread;
Having fallen into the ‘wouldn’t it be nice to automate some things’ trap I’ve been looking at using an Arduino to control servos and stepper motors. Like others I’ve found that although the simple scripts making a LED blink etc pretty easy, the next step to writing your own more complex code is daunting.

What is new since this thread started is the ability to get AI generated code to your own requirements.
I’ve been using ChatGPT to generate code and it’s generally* been very successful.

Points to note;
I usually start with “Design circuit and write commented code and instructions for arduino uno r3 to control….” with that you get full instructions and the code commented help to understand the it.
You need to specify exactly what kit you’re using eg “28BYJ-48 stepper motor using a ULN2003 driver board, a potentiometer, an LCD1602 display (non-I2C)”
You need to be able to specify exactly what you want the code to do. (possibly the hard bit ;-) )

Anyone interested in having a play with the tech can find some cheap starter kits on Amazon for not a lot of money that have all the basics to try out circuits. I’ve got the Elegoo kit and it comes with some good tutorial to start off with.

<edit>
I've now spotted why I was getting an error with some of my first requests. I had only asked ChatGPT to write the code, not design the circuit. Obviously really, but adding "Design circuit and..." gets any extra components not directly related to the code specified eg resistors, capacitors etc
 
Last edited:

Paul_H

Active Member
I’ve now been experimenting with stepper motors for automation and I can add some more details to the use of ChatGPT.

For some tasks ChatGPT will deliver working code immediately, which is helpful.
However I’ve also found that the code can have flaws and might not work fully as expected. You then need to tell it what doesn’t work and it will rewrite and deliver new code.
What’s curious and frustrating is that it seems to know immediately what’s gone wrong and rewrite the code instantly. The problem may be fixed or the new code might not fully fix the issue or create new problems.
So far I’ve always been able to end up with finished code that works, but it has sometimes taken four goes to deliver what I expect.

Nice not to have to spend months learning coding, but it will still require a degree of effort to utilise the potential of automation for modelling.

<rant>
Also worth double checking connections. I’ve wasted days trying to drive a stepper with a DRV8825 driver only to discover, two blown boards later, the supplier’s data sheet has a printing error and all the pinouts were mirrored… :-(
 

simond

Western Thunderer
I’ve now been experimenting with stepper motors for automation and I can add some more details to the use of ChatGPT.

For some tasks ChatGPT will deliver working code immediately, which is helpful.
However I’ve also found that the code can have flaws and might not work fully as expected. You then need to tell it what doesn’t work and it will rewrite and deliver new code.
What’s curious and frustrating is that it seems to know immediately what’s gone wrong and rewrite the code instantly. The problem may be fixed or the new code might not fully fix the issue or create new problems.
So far I’ve always been able to end up with finished code that works, but it has sometimes taken four goes to deliver what I expect.

Nice not to have to spend months learning coding, but it will still require a degree of effort to utilise the potential of automation for modelling.

<rant>
Also worth double checking connections. I’ve wasted days trying to drive a stepper with a DRV8825 driver only to discover, two blown boards later, the supplier’s data sheet has a printing error and all the pinouts were mirrored… :-(
Good to know, I have just started doing some coding again, I might try doing it semi-automatically…

That said, I want to understand what I’m doing and why, so I guess getting AI to do it for me would be a different learning curve.

I have had a few frustrating evenings where stuff is not working at all, so I borrowed a scope from work this afternoon, and in five minutes eliminated a hundred possible issues - that’s a kind of progress!

Regarding mirrored pin-outs, are you sure you didn’t solder the headers to the other side of the board?
Easily done, and it will mirror the pinouts. Sometimes you actually want to do that.
 

Paul_H

Active Member
ChatGPT will give a description and explanation of the code it's produced, so there's the possibility of learning from it's comments. That will also allow you to do your own edits once you know what bit of code does what.

No, the pinouts are wrong on the PDF. They'd put the illustration of the board into the document upside down. It's a very small and packed board, so the printed idents are on the underside of the board, so unless you spot it's wrong before fitting you can't see it once fitted.
I'd also add that the printing, once you've found it, is so small you need a jeweller's loupe to read it.
It came to light when I found another web page about it with a different illustration. F'ing annoying
8825.jpg
 

simond

Western Thunderer
Ah, mirrored that way rather than as I imagined. Yes, annoying. Very.

which of your diagrams is correct btw? The photo on the right, I assume?

I‘ve used 4988s which are a bit crude but work fine. And are cheap :) (just as well, give the rate we got through them on a work project!)

I guess you can use the automated code as a learning resource. It’s certainly a potential solution when you’re running out of hair to pull out…

cheers
Simon
 

Paul_H

Active Member
The one on the left is the correct one.
A4988s seem to be less packed and the pinouts are visible once fitted. Mine should arrive next week :-/
 

John_B

Western Thunderer
That said, I want to understand what I’m doing and why, so I guess getting AI to do it for me would be a different learning curve.
It's some time since I tried ChatGPT for programming, but my experience was that you have to understand what you want, and how to do it, to be able to give clear instructions. Then when ChatGPT gets it wrong you have to be able to explain the error to it. Rather like an experienced manager who's got rusty with the finer points of the language giving work to a less experienced programmer who has good knowledge but is still learning. But unlike a human, it seemed to be very submissive, and didn't answer back!

I found it helpful because it saved me loads of time having to look up, and make sense of, the exact syntax, which I never remember because I don't do enough of it, and it writes the code much faster than I could. But I think it takes practice to be able to describe all the criteria for controlling a fairly simple layout. I seem to remember it assigned the wrong pins at times, so I had to tell it things like it had attached a PWM device to a non PWM pin, although it may have learned not to do that by now!

I must try it again to see if it's improved. I have a few ESP-32s on my desk that are intended for controlling several small layouts.
 

Paul_H

Active Member
my experience was that you have to understand what you want, and how to do it, to be able to give clear instructions. Then when ChatGPT gets it wrong you have to be able to explain the error to it.
Having a clear idea of what you need a program to do is applicable to any programming, whether it's typing in the code yourself or getting AI to do the heavy lifting.
The 'how to do it' is where AI saves those of us without much programming expertise from having to design the code structures, logic and correct syntax.
I've found explaining errors very straight forward using plain language; eg "sketch runs once, but won't run again without resetting Arduino" that got an immediate working correction to the code. It's just frustrating that it didn't get it right first time.
 

simond

Western Thunderer
As I mentioned, I’ve been doing a bit of Arduino over the last couple of weeks.

My layout is still awaiting a home so I content myself with the first module, the loco shed, on which the points, turntable and scenic lighting are all controlled by a small control box which contains an Arduino Mega (a real one, not a clone!) and an HW184 CAN interface.

image.jpg

The CAN bus connects to three more HW184s, each connected to a Nano, which in turn control:-
The points - 8 channels but only use 5 - which handle the Tortoises, my own driver board. Over on the right of the photo below - the bi-colour leds indicate the point state.
The turntable which is stepper driven, using an A4988, it has a phototransistor which is used to reset the step count every rev. That’s the nearer board with the green led on it.
The lights, using PWM & MOSFETs - whilst it works, this is the least satisfactory and will get some attention at some point. The lighting Nano also controls a relay which switches the front siding between DCC and programming track / this is interlocked with the points so you can’t inadvertently bridge the gap.

image.jpg

I now have two lovely lever frames that my pal John Matthews built from his own kits for his garden railway, the Leigh & North Whitton, on which we spent many happy hours.

John was a proponent of working rodding for points, signals were operated by whipping twine “wires” with under baseboard weights to return them to danger. This does not float my boat, so I have converted the first frame to digital operation, there is a microswitch to detect the position of each lever, and these feed a Mega clone (this will easily accept 50-odd inputs, the larger frame has 31 levers) and the Mega transmits its status via ubiquitous HW184. John had implemented mechanical locking on his frames. I will update this when I build the layout, can’t really do it before! I will probably connect the Block instrument, Tapper and Bell to spare Arduino pins.

IMG_1534.jpeg

IMG_1533.jpeg

The slave units comprise a Nano and a CAN interface and will control 12 servos which can be signals or points, of course. These are mounted on a stripboard panel.

IMG_1535.jpeg

The three servos are mounted on a 3DP (FDM, not resin) signal base which drops into a 3DP “socket” which is intended to be glued/screwed to the baseboard, allowing signals to be simply dropped in and plugged in, servicing them off-layout is much easier. It’s upside down in the photo.

IMG_1536.jpeg

I got a large bag of surplus 5-way plugs & sockets which I have standardised on as the CAN bus connection, whilst the CAN itself needs only two wires (High & Low), it’s normal to have a common ground for all units on the bus. I’ve included a 12V and 5V connection as well.

Servos take a bit of grunt so I will feed the slaves locally - 12 would need the capability to provide a few Amps, though arranging that they don’t stall is important. I’m going to add a chunky capacitor to each slave to minimise any tendency for current spikes caused by one servo to destabilise the others. I haven’t added the power connection or the capacitor yet.

The lever frame needs very little current, and runs happily off a USB charger, or off the 5V line from the CAN bus, though I’ve not wired that in as yet.

I can share code and circuit diagrams (though “as is”, no guarantees!) if anyone’s keen to go down this road.

atb
Simon
 
Last edited:

magmouse

Western Thunderer
The lights, using PWM & MOSFETs - whilst it works, this is the least satisfactory and will get some attention at some point.

This piqued my interest, Simon, as I am currently scouring the internet for components for a somewhat complicated lighting system for my forthcoming Basuto Quay layout. I'd love to know what it is about your Arduino/PWM/Mosfet setup you find unsatisfactory, as I am planning to use that methods for part of my scheme.

Nick.
 

simond

Western Thunderer
Hi Nick,

the main gripe is that I can adjust brightness levels on each channel, but I have not (yet) provided any means of saving the settings, so when I turn it all off, I lose them. This is not insurmountable. If you wanted to, you could run 15 PWM channels on a Mega, and it would be entirely feasible to have settings saved on an SD card if you wanted to. Equally, you could have a “mixer board” with a pot per channel, and simply use the Arduino as a simple multi channel dimmer.

Indeed, you could arrange for lights to come on in a sequence, in response to other things happening (room lights being dimmed, for example) and with some random effects too (eg bathroom or office light).

very versatile.

and time consuming. Which is why the w-iron etches haven’t been done…

cheers
Simon
 
Top