# Arduino - First Light



## Susquatch (Oct 9, 2022)

Quite some time ago, I got introduced to the Arduino by reading a thread about @YYCHM adding an RPM Readout to his mill. Craig inspired me.

Microcontrollers are not new to me. I've spent a large part of my career using them and their sensors in the automotive world. I also spent time with PICS, the 8748, and the Basic Stamp. But the Arduino was new to me - I'd heard of it but never played with one.

On the strength of that thread and my desire for an RPM Readout on my mill, I bought an Arduino Nano and an LCD display. Sadly, I never actually used them. When I bought the DRO for my mill, it had a built in RPM display. So that was that. The Arduino started to gather dust just like so many other projects of mine.

Recently, I got covid and ended up in bed - bored out of my mind. Hey, says I to myself, what a great time to read up on the Arduino! And so I did.

Yesterday, I installed the new 2.0 IDE and connected my Arduino Nano to my desktop PC in the house and fired it up! Sooooo many problems. Can't connect, upload failed, etc etc. But one-by-one I clubbed them to death. Turns out the default comm port is wrong - easy fix. But still no joy. It turns out my Nano came with the old bootloader. Switched to the nano with original bootloader and problem solved. Last night I successfully uploaded my first program - blinking LED. Not exactly a huge program, but it worked! Then I played around with the blink timing and did a small program to play an "SOS" sequence of blinking.

Now I am hooked!  Just picture an old man smiling over a blinking LED..... I know, it's pathetic but hey, I'm not ashamed to admit it!

I think I will do an RPM display for my lathe..... This will be more challenging. Fortunately, @whydontu has already written some first rate code for that.

I could also plan to improve on whydontu's code by playing with direct processor and register access coding. But before I run, I gotta walk. So I'm gunna set that goal aside for a little while.

Perhaps first I should play around with a few other simpler projects. First some programs that just exercise the device without add-on electronics, and then maybe dig out my breadboards and fiddle around with some additional electronics and maybe even some relays for motor and device control.

I welcome fun suggestions.

Some good can even come from Covid.


----------



## phaxtris (Oct 9, 2022)

Do you remember when stamps were like 100$ +, and now you can buy a nano from China for 3$, oh the times we live in right!

OLED displays are pretty neat, I would buy one or two of them 

Check out Ali, they have all of the break out boards for the popular chips on there for dirt, temp sensors, gyros, magnetometers, accelerometers, relay boards, etc etc etc


----------



## Susquatch (Oct 9, 2022)

phaxtris said:


> OLED displays are pretty neat, I would buy one or two of them



I like OLED. Will do! 



phaxtris said:


> Check out Ali, they have all of the break out boards for the popular chips on there for dirt, temp sensors, gyros, magnetometers, accelerometers, relay boards, etc etc etc



Ya, exciting times. I have a drawer in my electronics loft full of unused stamps. I wonder what I could get for them now. 

I recently saw an Arduino board with a 3D accelerometer sensor and relays right on the main board!


----------



## phaxtris (Oct 9, 2022)

Susquatch said:


> I like OLED. Will do!
> 
> 
> 
> ...



Do they still make stamps ?  I don't know if you could even give them away, there has been so much development behind the Arduino ide, even schools use Arduino's

Seems like the have a board for just about anything you could imagine! and the code library's are free and easy to get, it was not this easy when I was in school that's for sure

But it's exciting how accessible this stuff is, then you add YouTube to the mix and the possibilities are endless


----------



## gerritv (Oct 9, 2022)

Sadly, using the Arduino IDE as a teaching tool leads to some truly terrible coding and sw design skills. Doesn't belong in schools besides tinkering.


----------



## whydontu (Oct 9, 2022)

Things I’ve learned using Arduino:

> My coding skills are stuck at 1972 BASIC
> some arduino boards are 3.3v. they die easily when connected to real-world stuff
> one set of the Arduino Uno socket connectors are offset by 0.05”, so they won’t plug into a regular strip board. 
> 0.1” pin headers suck in a vibration/heat/mist environment. Use the screw terminal adapters for gear intended for use in your shop.


----------



## Susquatch (Oct 9, 2022)

gerritv said:


> Sadly, using the Arduino IDE as a teaching tool leads to some truly terrible coding and sw design skills. Doesn't belong in schools besides tinkering.



This sounds like the voice of experience..... 

Can you provide some examples?


----------



## phaxtris (Oct 9, 2022)

gerritv said:


> Sadly, using the Arduino IDE as a teaching tool leads to some truly terrible coding and sw design skills. Doesn't belong in schools besides tinkering.



I was referring to highschool, I don't think anyone learns how to do anything well there...but it is exposure


----------



## whydontu (Oct 9, 2022)

Susquatch said:


> This sounds like the voice of experience.....
> 
> Can you provide some examples?


My code would be a good example…


----------



## jcdammeyer (Oct 9, 2022)

Decades ago Niklaus Wirth stated that people who learned Fortran as their first language were brain damaged for life.  I always found that quite funny even if it was a bit rude. 
He is the author of Pascal and other algorithmic languages on which even the Arduino is based.


			Niklaus E. Wirth - A.M. Turing Award Laureate
		


And I do use the Arduino for a small SD card logging application where I've had to modify it for my clients specific purposes.  Here you can see the sparkfun log card in red along with a wiznet Ethernet card.




I've also attempted a few other projects with the Arduino but eventually always go to something that is more robust.  
I used some strip LEDs and an Ardunio based library with Wifi to set the blinking sequences.  After about 6 hours it would crash.  There's nothing in the Arduino infrastructure that makes that easy (or maybe even possible) to debug.  My guess is that there is a memory leak and eventually the stack is corrupted.

And there's the problem with the Arduinio and Python world.  Random memory garbage collection that can adversely affect the application either for speed or reliability.

Having said that I have most of the parts to build an electric Kiln controller.  (Project #42).  I bought an add on board with CAN bus and was able to log messages from my car.  But I found that without a decent list of what the messages mean it was pretty difficult to diagnose the problem or clear the faults.  Eventually just bought a high end code reader.

I thought about using the Arduino for my Power Draw bar and coolant controller but in the end I used one of my dsPIC33F5011 modules since I could actually set break points and look at what was happening under the coveres.

I now have a couple of Leonardo Arduinos on the way from China.  They can apparently really easily become USB keyboard emulators so the idea of a specialty Pendant is really interesting.  

And there's the rub.  The infrastructure and the number of libraries for the Arduino is staggering.  I can't see not using it when the application begs for something that simple.  

Would I use it in a system where peoples lives are at risk?  Not a chance.

So you will see me reporting on things like the kiln controller or other projects that make things move.


----------



## Susquatch (Oct 9, 2022)

whydontu said:


> My code would be a good example…



Mine too. Which is why I asked. 

FWIW, I learned to throw away the programming rules very early on. It enabled me to write code that worked despite the fact that disciplined coders couldn't make their code work. 

I am a firm believer in truly understanding the hardware first and ditching the coding rules. I know lots on here will argue (correctly) with that, but I argue that if it works it works. I'll take one good programmer who ignores the rules and writes code that works over 10 who follow the rules but can't make it work. 

For example, a human modifies his thinking based on results. But it is considered horrid programming to mix data with code. Yet I used to routinely write programs that treated the program like data and actually changed the machine language program instructions themselves in memory to react to results. Of course, the reason for that was to be independent of compilers. So I would simply write code that could determine where it was so it could be modified on the fly. Often (but not always) this was way faster and more flexible than saving and restoring CPU status in subroutines. If you don't need it, why do it? 



jcdammeyer said:


> My guess is that there is a memory leak and eventually the stack is corrupted.



You might be right. My guess would be a timer or counter overflow or an interrupt gone AWOL. The AWOL interrupt might corrupt the stack too. Especially if it doesn't honour other Interrupts! 

I say that because my brief investigation of the Arduino language / ide provides no way to conveniently access the timers, counters, registers, or the Interrupts. I see this as a major bottleneck to efficient fast code and a potential memory leak. Any program that has to sit around doing nothing while it waits for a complete count is doomed to run at a snails pace. Good code should be able to go do other things while it waits. 

My guess is that some of the libraries out there don't do this correctly and as a result counter overflows are probably common. Same goes for Interrupts which are not even supported in the IDE let alone in any predefined way like the counters are. 

Hence my earlier stated desire to bypass that part of the IDE and directly control the hardware. 

For now, that's all just a lot of empty talk till I actually do it though! LOL!


----------



## gerritv (Oct 9, 2022)

To be honest, I started with Assembler on NCR315 using paper tape in 1965, then went to Fortran. More assmebler, Cobol, some APL and then C and php. I spent a bunch of years architecting medical imaging connectivity stuff at ISG.

One misconception though, Arduino is not a language, it is an eco system that is mostly written in C and C++ and an IDE that hid everything from the user while providing little to no contextextual help in writing code. As in one step above a Notepaad++ editor. To the point where you too often have one file (.ino) with global variables, hundreds/thousands of lines of code, no structure, no isolation and typically no design. The libraries are buried deep in your file system. Nothing in your code is reusable. The RELS code I am using in my electronic leadscrew is typical of that mess. Totally unportable to new hw.

The reason for no debug is a combination of no hw support on Atmel 328 chips (on which the early Arduino hw is based) and a penchant for *nix types to use printf's instead of an actual debugger. Printf's almost universally block execution while its output is spewed out over a slow serial interface, holding up you code from doing anything timed. To the point where you get something working, turn off the printf spewing oand now you code no longer works because the timing changed. AES Data in 1985 had ahw designer in Mtl who couldn't understand why I wanted dma driven serial IO to mitigate that on a 68k based board he was designing!

If you write your sw using Visual Studio Code and use Platformio as a build system then you can get much of this under control. And pio provides a way to use at least a simulator to test/trace/debug your code. Better chips such as SAM D21 etc support hw level tracing, which of course is even better.


----------



## gerritv (Oct 9, 2022)

Coding rules exist for a reason, you will know that when trying to fix someone else's code. Testable code is even more important. Tracelable code and design to requirements and regulatory stipulations are important. 


> I am a firm believer in truly understanding the hardware first and ditching the coding rules. I know lots on here will argue (correctly) with that, but I argue that if it works it works. I'll take one good programmer who ignores the rules and writes code that works over 10 who follow the rules but can't make it work.


That would get you fired by me in a heart beat. This has no place in sw development for an actual use, e.g. medical imaging. If its not maintanable it has no place in anything important. In fact I fired some 'expert/guru' like that who refused to let his team use source level debugging, insisted on printf's.

A major phone company in Canada got them selves in a heap of grief on one of their main offering's billing systems because a) no design, b) no design docs, c) no idea how subsytems were used, d) poor/terrible code. It took >2 years to upgrade to a new version due to this. Very costly.


----------



## jcdammeyer (Oct 9, 2022)

gerritv said:


> One misconception though, Arduino is not a language, it is an eco system that is mostly written in C and C++ and an IDE that hid everything from the user while providing little to no contextextual help in writing code. As in one step above a Notepaad++ editor. To the point where you too often have one file (.ino) with global variables, hundreds/thousands of lines of code, no structure, no isolation and typically no design. The libraries are buried deep in your file system. Nothing in your code is reusable. The RELS code I am using in my electronic leadscrew is typical of that mess. Totally unportable to new hw.


Which is why I tend to still use the PIC family with the ICD-3/4 debuggers.  

That photo I posted above is an M9S12DP512 based on the original 6809 but expanded to be closer to a 16 bit processor but really still just 8 bit.  All the code is C with a few places assembler because the compiler screws up with the paging.

My ELS uses a PIC18F series processor and can be debugged/programmed with the Microchip tools.  Even the LCD display code is set up as a Tree like data structure with 4 possible branches based on the soft keys in the row right under the display.  So I've used the platform for other projects just by changing that data structure.  And the code is all open source.

Still there are places where the Arduino is appropriate.


----------



## jcdammeyer (Oct 9, 2022)

gerritv said:


> Coding rules exist for a reason, you will know that when trying to fix someone else's code. Testable code is even more important. Tracelable code and design to requirements and regulatory stipulations are important.


A few decades ago I designed a product that could have been the forerunner of the Arduino.  The board had I/O, A/D, Serial. But the technology at the time was EPROMs so debugging had to be done with print statements.  Integrated IDEs didn't really exist yet.  But I wrote an RTOS for that processor and a colleague wrote the cross assembler and a Tiny Pascal Interpreter (the idea of Python).

The product was used in a few places but the EPROM need killed it.  We had 7 Segment displays, 3 axis quadrature encoder boards, D/A boards.  Serial was RS485 so we could network them.  The RTOS found all the modules in ROM which could be written in either assembler or Pascal.

Shortly after I moved to The Netherlands and worked on OS9 based embedded systems with EPROMs but firm rules on how to code so others could read it.  Again C code.  But now State Machine Based.  In the long run easier to debug than using an RTOS and for 99% of the control system fast enough.


----------



## jcdammeyer (Oct 9, 2022)

As I mentioned above the approach I use now is state machine based which allows both serial port debugging and even CAN bus debugging.  Back in 2000 I used a small module called a CANDIP which had an ATMEL processor that supported CAN bus.  I made a board for it that drives transistors for the spark coil and the PWM out to the furnace fan along with gas solenoid.

The main line looks like this and the key rule is no function is allowed to block preventing other threads or device drivers from running.

```
void
main(void) {

    // Init all variables and global hardware.
    InitMachine();

    while (1) {
        // First Run all device drivers
        Timer();
        SparkDevice();
        SerialDevice();
        MotorDevice();
        FlameDevice();
        KeySwitchDevice();
        MAPCAN_Device();
        
        switch (MachineState) {

        case INIT :
            ThreadsInitialized |= BurnerThreadInit();
            if (ThreadsInitialized == INITIALIZED_THREADS) {
                puts("READY");
                 MachineState = READY;
            }
            break;

        case READY :
            // Check all existing threads again.
            ThreadsRdy = 0;
            ThreadsRdy |= BurnerThreadRdy();
            ReportThread();
            if (ThreadsRdy == READY_THREADS) {
                puts("STARTING");
                MachineState = STARTING;
            }
            break;
            
        case STARTING :
            ThreadsRunning |= BurnerThreadRdy();
            if (ThreadsRunning == RUNNING_THREADS) {
                puts("RUNNING");
                MachineState = RUNNING;                     
            }
            break;
            
        case RUNNING :
            BurnerControl();
            ReportThread();
            if (ThreadsRunning == 0) {   // All threads stopped?
                puts("STOPPING");
                MachineState = STOPPING;
            }
            break;
        
        case STOPPING :
            if (fERROR) {
                fERROR = FALSE;
                puts("ERROR");
                MachineState = ERROR;
            }
            else {
                puts("READY");
                MachineState = READY;
            }
            break;

        case ERROR :
            ReportThread();
            break;
        }
    }
}
```

One of the key devices is the timer() device.  Here you can see the timer functions used in the make spark device.  The states return if the timer isn't done.  The timer counts ticks via an interrupt routine so it doesn't actually delay other than the time spent checking if a timer is finished.

```
// Spark Device for Crucible Furnace

//  By     John Dammeyer
//      Automation Artisans Inc,
//        PO Box 20002 Sidney BC
//        CANADA - V8L 5C9

//        1-205-544-4950
//        johnd@autoartisans.com
//
// Initial Version:

// Include constants and function definitions
#include <io8515v.h>
#include <stdio.h>
#include <eeprom.h>


#include "general.h"
#include "furnace.h"

//#include "WiCAN.h"

#include "Timer.h"

#include "mapcan_avr.h"
#include "ObEEROM.h"

#include "SparkDevice.h"

enum SPARK_STATES {
     SPARK_INIT,
     SPARK_WAIT,
     SPARK_ON,
     SPARK_OFF
};

BYTE SparkCmd = MAPCAN_DEV_INIT;     // Semaphore for control of device.
BYTE SparkMsg;

void SparkDevice(void) {
  static enum SPARK_STATES SparkState = SPARK_INIT;
    switch (SparkState) {

    case SPARK_INIT :
        SparkMsg = SPARK_STOP;
        SparkState = SPARK_WAIT;
        break;
        
    case SPARK_WAIT :
        if (SparkMsg == SPARK_START) {
            StartTimer( SPARK_TIMER, GetEEROM_Word(EE_SPARK_DWELL));
            PORT_ON(PORTB, SPARK_COIL);
            SparkState = SPARK_ON;
        }
        break;
        
    case SPARK_ON :
        if (TimerDone( SPARK_TIMER ) ) {
            PORT_OFF(PORTB, SPARK_COIL);
            StartTimer( SPARK_TIMER, GetEEROM_Word(EE_SPARK_DELAY) );
            SparkState = SPARK_OFF;
        }
        break;
        
    case SPARK_OFF :
        if (TimerDone( SPARK_TIMER ) ) {
           SparkState = SPARK_WAIT;
        }
        break;
    
    default :
        SparkState = SPARK_INIT;
        break;
    }
}
```

The above routine just pulses the ignition coil while the Spark_Msg remains set to SPARK_START.  

Either with the serial port, the CAN bus or from another thread the spark can be started.  I fake out the air flow detection here.  Just assume that if I get here the fan is spinning and there is airflow.


```
// FAN blowing at Ignition Speed or Manual control speed.
        case BURNER_FAN_ON :
            // Check Air Velocity Sensor for Blower Air.
            // MAPCAN_GetMessage()
            // if (Air is moving)
            if ( TimerDone(BURNER_TIMER) ) {
                // Cancel Start request.
                RunFlag &= ~fSTARTING;
                SendDeviceMsg( LAMP_DEVICE, MAPCAN_DEV_CMD, WARN_LAMP, LAMP_FLASH ); 
                if ( TRUE /*(PINB & AIR_FLOW) == 0*/ ) {    // Airflow exists
                    SendDeviceMsg( SPARK_DEVICE, MAPCAN_DEV_CMD, SPARK_START, 0 );
                    FlameThreshold = GetEEROM_Word(UV_SPARK_THRESHOLD);             // Low threshold for spark plug.
                    StartTimer(BURNER_TIMER, GetEEROM_Word(EE_SPARK_CHECK_DELAY));
//                    putchar('2');
                    puts("B:SPARK");
                    BurnerState = BURNER_SPARK;
                }
                else {
                    fERROR = TRUE;
//                    putchar('8');
                    puts("B:FAN_OFF");
                    BurnerState = BURNER_FAN_OFF;
                }
            }
            break;
```

The other states are similar.  We test parameters or fake them out if I didn't finish the hardware.  Wait the time interval and then speed up the fan from ignition speed to full speed and shut off the sparkplug.


----------



## jcdammeyer (Oct 9, 2022)

Connect a serial port on a laptop to the furnace controller and this is what I see.

```
Crucible Furnace Version 0.22a

READY
STARTING
RUNNING
B:ACTVE
B:FAN_ON
B:SPARK
B:GAS_ON
B:FLAME_ON
```
Now furnace is running and heating.  If I switch the run switch back to Center Position (OFF) then this is what happens.  A change of state to FLAME_OFF and the GAS Solenoid is switched off

```
B:FLAME_OFF
B:GAS_OFF
B:FAN_OFF
```
Here I switch the switch from OFF to FAN ONLY while it's coasting down from high speed.

```
B:BURNER_INIT
B:ACTVE
B:FAN_IDLE
```
And then Switch if OFF again and then once it's stopped switch it on again.

```
B:INIT
STOPPING
READY
STARTING
RUNNING
B:ACTVE
B:FAN_IDLE
B:INIT
STOPPING
READY
```

The fan idle state happens when the main switch is moved from the RUN position to the FAN position.  It sets the PWM slower than the initial slow fan speed for lighting the flame.  I have that to just move air through the furnace after it's been used for melting to cool it and spread the warm dry air around the shop in the winter..

the "B:" is the burner thread.  The interrupt driven output Q must be large enough to hold the max size message so the system doesn't hang waiting to fill the Queue.  There are ways around that with the co-operative multi-threading systems.

I did not include functions to set EEROM to new values or make it so EEROM values could enable/disable the air flow and flame detector modules.  And now it's unlikely I have the tools to reprogram this processor module without a lot of work. 

Hence the idea of using the Arduino instead.


----------



## Susquatch (Oct 9, 2022)

gerritv said:


> To be honest, I started with Assembler on NCR315 using paper tape in 1965, then went to Fortran. More assmebler, Cobol, some APL and then C and php. I spent a bunch of years architecting medical imaging connectivity stuff at ISG.



I started with machine language on a 4004 and then an 8080. There was no assembler yet because there were no computers (other than mainframes) to run them on! At first code had to be entered one byte at a time each time a program was run. No tape, no cassettes, no key punch yet for microprocessors. But I quickly adopted assembly language as soon as it arrived. 

I too learned Fortran on a mainframe with punch cards. 

My early years were spent designing electronic control systems for cars and trucks and then microprocessor based control systems for engine, body, and transmission control.

On my own time I designed and built many different kinds of what we call personal computers today. I did several from my own boards and chips, wrote my own OS, and then wrote user type programs from Word processors to spreadsheets. Then along came CP/M and it was love at first sight. After that I built mainly specialty boards like ADA and I focussed on writing drivers and applications at the assembler level. I didn't like the higher level compiler based languages of the time. They were way too slow (I think they still are). I wrote and sold quite a few programs like that because mine were always so much faster than my competition could write. 



gerritv said:


> That would get you fired by me in a heart beat. This has no place in sw development for an actual use, e.g. medical imaging. If its not maintanable it has no place in anything important. In fact I fired some 'expert/guru' like that who refused to let his team use source level debugging, insisted on printf's.



So we are even then Gerrit! LOL! 

Adherence to rules like you describe would get you fired in the auto industry! Everyone documented and everyone worked in a team. Everyone knew what everyone else was doing and anybody could be (and was) replaced. But anybody spending time adhering to rules got canned. We broke rules and did it intentionally. It was encouraged. Very few problems occurred because of software. Those tended to get worked out during prototype testing. The primary problems we encountered after production were related to humans messing where they shouldn't. It was a constant problem - and as far as I know it still is today. I used to get frequently challenged by the so-called high tech sector who criticized the industry for being slow to adopt technology. My standard response was to suggest they take their latest gizmo, pound it down a gravel road at every temperature and precipitation mother nature can throw at it, cover it in salt spray, blast it with high powered RFI, and then let's see how well their gizmo still works. It always shut them up. Even so called industrial equipment can't stand up to what a car endures day in and day out. Although I am not positive of the outcomes, I did participate in various military exchanges and I have good reason to believe that they are heavily based on automotive methods. 

There are many reasons why the automotive software was done so differently. Here are three of the primary reasons: The first is corporate espionage - most code was written so it couldn't be reverse engineered. The second reason was performance competition in terms of function, cost, and manufacturability. Do more with less was always the order of the day. The third was the need for speed. A lot of things happen in a car engine in just a few CPU clock cycles. Just three or 4 functions would be easy to do. But it gets complicated real fast as additional mapping covered more dimensions. It doesn't take long and that CPU can't keep up. So we were always optimizing software and rules had to be broken to do it. 

In many ways, the auto industry is the mirror image of what most of us assume it is. 

Ya, you would fire me and I would fire you. But man would we ever have fun debating it! 

Btw, I had a buddy who worked in information systems. We spent many awesome hours together arguing the pros and cons of the two paradigms. We always ended up agreeing to disagree. I expect that is where you and I will land too. 

I wrote diagnostic imaging software too! But not connectivity software. I wrote diagnostic imaging software. We had a partnership with a university to develop 3D ultrasonic imaging hardware. We used it for non-destructive testing of car parts and they used it for medical diagnostics. That was a long time ago, but we used the same kind of software techniques for that as we did for car controllers and nobody suggested firing me. 

I suspect our different approaches come from different segments of software development. You said you wrote connectivity software. I wrote device software. Connectivity and information systems software is totally different in many ways. Your world requires portability, upgradability, constant change, and even global conpatability. The product world is only rarely subject to those requirements. In fact as described above, it's often deliberately different. 



jcdammeyer said:


> Which is why I tend to still use the PIC family with the ICD-3/4 debuggers.



Boy do we agree on that! But I'm all done designing circuit boards. If I never do that again for the rest of my life it will be too soon! And I never did learn to like any of the complete pic based systems out there. WAY too expensive for personal use. They might be better now though. It's been 15 years since I last looked at what was available. Lots of things change in 15 years. 



jcdammeyer said:


> Still there are places where the Arduino is appropriate.



We agree on that too or I wouldn't be trying to learn how to use one. There is something to be said for a complete standalone controller system that can be programmed in a few days that only costs a few dollars with so much freeware available. I'm also planning to have some fun breaking the rules! 

About debuggers. I've seen the odd article that mentions a replaceable boot strap with integrated debugging capabilities. But I can't find any solid links. Know anything about that?


----------



## jcdammeyer (Oct 9, 2022)

Susquatch said:


> We agree on that too or I wouldn't be trying to learn how to use one. There is something to be said for a complete standalone controller system that can be programmed in a few days that only costs a few dollars with so much freeware available. I'm also planning to have some fun breaking the rules!
> 
> About debuggers. I've seen the odd article that mentions a replaceable boot strap with integrated debugging capabilities. But I can't find any solid links. Know anything about that?


I recall reading about that.   Apparently you have to do something to prevent the IDE from deleting files.  Apparently while it's compiling it puts all the compiled C and assembler files in one spot and then once the final code is complete for downloading erases the works.  For the TRS80 basic type programmers (Or Arduino or Python) this is probably a good thing because over time their system would have tons of files with no structure or trackability.  

But for embedded systems where it's important to look at what the compiler did the Arduino fails miserably.

And for small modules to do simple things (sometimes even complex) it succeeds tremendously.


----------



## jcdammeyer (Oct 9, 2022)

So just to hijack this thread a bit more.  Here's a photo of the electronics that runs my foundry furnace.  To be precise only the middle board with the rust and corrosion is in use.  The little DIP board with the two crystals is called a CANDIP and has an Atmel 8515 processor and a CAN chip on board.  The software written in C does PWM to a transistor that runs the PA surplus motor which turns a fan.   It does that spark coil on/off pulsing.  (There's a story behind that for another time).  And it opens/closes the gas solenoid.

Now the other board interfaces to that little glass tube driven with about 300V to detect ultraviolet light.  If the flame is on there is UV.  If the flame goes off it might be white hot inside the furnace (which would relight the gas) but no UV.  And if the sensor was connected and the software enabled it would close the gas valve.

The other sensor, not visible because I moved the ribbon cable over it, is a hot wire anemometer.  Two Thermocouples, one heated by a resistor and one in ambient air.  The difference in temperature tells if there is air flowing since the resistor beside the thermocouple warms it up unless there is air flowing.  Simple and we don't really care for an absolute air speed.  Just did the fan stop turning?

I also painted the back of the fan with black and white paint and have a reflective sensor to determine fan speed but never even wrote software nor have pins for it.


----------



## PaulL (Oct 9, 2022)

Hi, Jack.  Here's the tiny "arduino" I built a few years ago, a wildlife tracker.  AVR Microcontroller and and accelerometer at the bottom end, discrete VHF transmitter in the middle (not popuated on this debug unit), and a break-away 6 pin header for programming at the top.  Fully populated and with a battery could keep the weight under 2 grams for a two year battery life and 2-4 KM range.  The worst part was dealing with the real-time clock installed on the back-side of the board.  But with it the device can reliably wake up after months of hibernation and correctly choose to broadcast during night or day as need be - different species are tracked at different times of day.


----------



## Susquatch (Oct 10, 2022)

PaulL said:


> Hi, Jack.  Here's the tiny "arduino" I built a few years ago, a wildlife tracker.  AVR Microcontroller and and accelerometer at the bottom end, discrete VHF transmitter in the middle (not popuated on this debug unit), and a break-away 6 pin header for programming at the top.  Fully populated and with a battery could keep the weight under 2 grams for a two year battery life and 2-4 KM range.  The worst part was dealing with the real-time clock installed on the back-side of the board.  But with it the device can reliably wake up after months of hibernation and correctly choose to broadcast during night or day as need be - different species are tracked at different times of day.



What a cool project! I love it! 

Do you actually attach it to wiidlife or does it monitor a trail?

Who is Jack?


----------



## PaulL (Oct 10, 2022)

Susquatch said:


> What a cool project! I love it!
> 
> Do you actually attach it to wiidlife or does it monitor a trail?
> 
> Who is Jack?


I didn't personally attach them, but yes, they are a commercial product.  You can get up to about 5% of an animal's weight before causing changes in behavior, so getting the weight down opens up many more species.  I did a smaller one that comes in at 0.22 grams, but that one can only fit a couple of capacitors and a pair of transistors to ping-pong the radio.  Much shorter battery life but you can put them on small bats and larger hummingbirds.

Jack, of course, is who I greet when I "Hi, Jack" a thread.

A bit back to the programming topic - the original software I wrote for this thing tried to avoid using a separate clock, and used a fairly complicated event loop to manage a countdown timer and wakeups to reset the timer.  Drifted like nobody's business.  It was much smarter to add an external clock chip with alarm features to use.  Very small, very cheap.  Just used up too much real estate on the board and caused the design to go to 4 layers instead of just two sided.  Added almost 30 cents to the bill of materials and another step in manufacturing :-(. But in exchange, tripled battery life and greatly increased software reliability.


----------



## Susquatch (Oct 10, 2022)

PaulL said:


> I didn't personally attach them, but yes, they are a commercial product.  You can get up to about 5% of an animal's weight before causing changes in behavior, so getting the weight down opens up many more species.  I did a smaller one that comes in at 0.22 grams, but that one can only fit a couple of capacitors and a pair of transistors to ping-pong the radio.  Much shorter battery life but you can put them on small bats and larger hummingbirds.
> 
> Jack, of course, is who I greet when I "Hi, Jack" a thread.
> 
> A bit back to the programming topic - the original software I wrote for this thing tried to avoid using a separate clock, and used a fairly complicated event loop to manage a countdown timer and wakeups to reset the timer.  Drifted like nobody's business.  It was much smarter to add an external clock chip with alarm features to use.  Very small, very cheap.  Just used up too much real estate on the board and caused the design to go to 4 layers instead of just two sided.  Added almost 30 cents to the bill of materials and another step in manufacturing :-(. But in exchange, tripled battery life and greatly increased software reliability.



Very Cool! And definitely a nice device. There are a few critters around here I'd like to track..... 

I get the Hi Jack now. But since it's my thread and since it's very appropriate to the subject and since I like it, it's not really a Hi-Jack at all. 

I'm not about to try something like that just yet....


----------



## jcdammeyer (Oct 10, 2022)

I went exploring last night till well into the early hours.
A couple of Teensy 2.1 on carriers to run the two RGB 32x32 panels running cool demo software.
Two Teensy 3.2 with one WIZ820&SD card adapter and two OCTO28 WS2811 RGB LED strip adapter
Two Teensy 3.5
One Teensy 3.6
One Adafruit HUZZAH ESP8266 module
Four Lua ModeMCU V3 WiFi Module ESP8266
Four NodeMCU-ESP32 modules
A single ESP8266 module
One Sparkfun Redboard (Arduino pin compatible) with CAN module and OBD-II connector cable.
On order I have 2 Arduino Leonardo clones and 15 arduino based SD card loggers.


Since I haven't touched any of these (except the Sparkfun) since I upgraded to this HP laptop I hadn't installed any of the Arduino libraries.  So I went through the process of installing the Teensy, EPS8266 and ESP32 libraries.  Then programmed one of each of the sets to blink the on board LED rapidly at 500ms ON, 250mS OFF.
Except for the NodeMCU-ESP32 which was programmed to report on the serial port the WiFi and CPU information.  

To get there I also had to download the CP210 USB serial port driver and the CH340 USB serial port driver.

All of the above are programmable via USB and the Arduino IDE 1.8.13.
I think I have a couple of other EPS8266 type modules in other boxes but by then it was 2:30AM.

Now to decide if I want to upgrade my Foundry Furnace to one of the Lua ModeMCU V3 WiFi Module ESP8266 modules.  This would give me WiFi access to the furnace operation and if I go ahead with the upgrade I'd finally add the air flow sensor and UV flame detector.


----------



## jcdammeyer (Oct 10, 2022)

Oh and now if I plug a Micro B USB into the NodeMCU-ESP32 and look at Serial port COM7 I get this once every 3 seconds.

ESP32 Chip model = ESP32-D0WDQ6 Rev 1
This chip has 2 cores
Chip ID: 13961200

The sample code to do this is really simple:

```
/* The true ESP32 chip ID is essentially its MAC address.
This sketch provides an alternate chip ID that matches
the output of the ESP.getChipId() function on ESP8266
(i.e. a 32-bit integer matching the last 3 bytes of
the MAC address. This is less unique than the
MAC address chip ID, but is helpful when you need
an identifier that can be no more than a 32-bit integer
(like for switch...case).

created 2020-06-07 by cweinhofer
with help from Cicicok */
   
uint32_t chipId = 0;

void setup() {
    Serial.begin(115200);
}

void loop() {
    for(int i=0; i<17; i=i+8) {
      chipId |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i;
    }

    Serial.printf("ESP32 Chip model = %s Rev %d\n", ESP.getChipModel(), ESP.getChipRevision());
    Serial.printf("This chip has %d cores\n", ESP.getChipCores());
  Serial.print("Chip ID: "); Serial.println(chipId);
 
    delay(3000);

}
```

Arduino's are incredibly easy to program with a huge set of libraries.
For example I then opened up the simple get time program, entered in my WiFi name and Password, built and downloaded it.  It goes out to the ntp server.

Monday, October 10 2022 18:54:15
Monday, October 10 2022 18:54:16
Monday, October 10 2022 18:54:17
Monday, October 10 2022 18:54:18
Monday, October 10 2022 18:54:19
Monday, October 10 2022 18:54:20


----------



## Susquatch (Oct 10, 2022)

jcdammeyer said:


> All of the above are programmable via USB and the Arduino IDE 1.8.13.
> I think I have a couple of other EPS8266 type modules in other boxes but by then it was 2:30AM.



You do know that the public release of the Arduino IDE 2.0.0 is out....... 

I feel for you on your moonlit adventures...... I can only do that when I can't sleep otherwise. Anymore lately, I fall asleep thinking about staying awake......


----------



## gerritv (Oct 10, 2022)

> Arduino's are incredibly easy to program with a huge set of libraries.


Just so the neophytes don't get confused: an ESP32 is an ESP32, not an Arduino  Arduino is a programming environment with IDE, libraries etc. There is also CMSIS for ARM, FreeRTOS and others. Arduino is also a set of pcbs with controllers, nmostly Atmel stuff but also ARM chips.

 The word Arduino is so overloaded it is almost meaningless, much like happened with Xerox.


----------



## gerritv (Oct 10, 2022)

Susquatch said:


> You do know that the public release of the Arduino IDE 2.0.0 is out.......
> 
> I feel for you on your moonlit adventures...... I can only do that when I can't sleep otherwise. Anymore lately, I fall asleep thinking about staying awake......


Just switch to Platformio and Visual Studio Code. Even runs on Mac's and Linux.


----------



## jcdammeyer (Oct 10, 2022)

gerritv said:


> Just so the neophytes don't get confused: an ESP32 is an ESP32, not an Arduino  Arduino is a programming environment with IDE, libraries etc. There is also CMSIS for ARM, FreeRTOS and others. Arduino is also a set of pcbs with controllers, nmostly Atmel stuff but also ARM chips.
> 
> The word Arduino is so overloaded it is almost meaningless, much like happened with Xerox.


Actually I disagree.  Arduino now means a processor module that is programmed with software through the Arduino Interactive Development Environment (IDE).  In that environment you can select which Arduino, Teensy, Feather, ESP8266, ESP32 and now even the RPi PICO.  In each case once the processor is selected the development environment remains the same but hidden under the covers for simplicity is which target compiler code generator is used.  

I'd say 99.9% of the computer science or computer engineering graduates nowadays haven't got a clue how compiler parsers work or peep hole optimizers etc.  The Arduino IDE and companion compilers just simplifies the job of running a standardized environment that is a tiny bit OOP and a tiny bit C.

As long as you can assign the pins for a specific SPI or I2C port the code to write out to a display like this doesn't really change.


----------



## jcdammeyer (Oct 10, 2022)

As I continue down the rabbit hole of upgrading my Foundry Furnace controller I first need to be able to program it.  The dongle I have, a Kanda ISPGOLD, is only supported on WIN-98 which I still have on a laptop.  I've been able to talk to the prototype so I know I can program but it's a pain to transfer software with the floppy from the WIN-XP system.

For the ATMEL side of things I also bought (Aliexpress I think) a USBTinyISP for a project a year or so ago.
https://www.aliexpress.com/item/32954431712.html which allows me to install the Ardunio Bootloader into a processor.  With the AVRDUDE program I should be able to program the foundry processor AT90S8515 with a WIN-10 system.

However, that's a pretty small micro nowadays with only 8K memory.  If I want to add the extra features I'll run out of room.  Perhaps one of the reasons way back that I didn't add the UV detection.  Don't remember.

So at this point it may well be better to start with an Arduino or one of the Teensy or ESP32 units and work to re-manufacturing the foundry system to have a window for the UV detection.  Only 23 years later.


----------



## Susquatch (Oct 10, 2022)

Hey @whydontu - do you know if I can power that 2 and 3 line LCD display that you used from the Arduino Nano via the USB port on it, or does that have to be done with its own supply? 

Alternatively, can I power the display to feed power back to the Nano? 

Basically, I don't want to use two power supplies. 

It would be nice if everything can be powered by the USB port on the Nano because then I could bring the whole unit to the computer for programming and testing. In case it matters, my Nano is a Canadian Solder Nano Clone with a USB-C port on it.


----------



## phaxtris (Oct 10, 2022)

Susquatch said:


> Hey @whydontu - do you know if I can power that 2 and 3 line LCD display that you used from the Arduino Nano via the USB port on it, or does that have to be done with its own supply?
> 
> Alternatively, can I power the display to feed power back to the Nano?
> 
> ...



i can answer this, yes you can, small oled's and 2 line lcds will run off the 5v regulated pin on the board

the on board 5v regulator gets pretty toasty however, i wouldn't plan on using that as the permanent solution


----------



## whydontu (Oct 10, 2022)

Susquatch said:


> Hey @whydontu - do you know if I can power that 2 and 3 line LCD display that you used from the Arduino Nano via the USB port on it, or does that have to be done with its own supply?
> 
> Alternatively, can I power the display to feed power back to the Nano?
> 
> ...


Yes, the LCD displays pull power from the 5v rail of the Nano. 

USB socket provides a 5v rail for everything. 

The LCD only pulls 2mA, at max the backlight pulls 40mA. At max backlight the LCD is completely illegible, for most of my applications I have the backlight turned down quite low, maybe only 5 to 10mA









						LCD 2004 20x4 Blue With White Backlight - Parallel Interface - Optional I2C
					

Blue LCD 2004 with 4x20 characters and bright white backlight. Optional available I2C interface and Acrylic enclosure (see our shop).




					universal-solder.ca
				












						How to Use I2C Serial LCD 20X4 (Yellow Backlight)
					

How to Use I2C Serial LCD 20X4 (Yellow Backlight): DescriptionNow, with only 3 pins from microcontroller, you can display message on this LCD. Compared to parallel LCD which required at least 6 pins of I/O, this LCD offer more cost effective solution. The LCD display is four lines by 20...




					www.instructables.com


----------



## Susquatch (Oct 10, 2022)

phaxtris said:


> i can answer this, yes you can, small oled's and 2 line lcds will run off the 5v regulated pin on the board
> 
> the on board 5v regulator gets pretty toasty however, i wouldn't plan on using that as the permanent solution



Thanks. That's perfect. I really don't want two supplies during development. 

That's interesting that the Regulator gets toasty. That makes sense if running off of a wall wart, but I would have thought that a PC usb output would be 5V so there shouldn't be any drop across the Regulator and it should not get hot no matter what the current draw is. But maybe USB-C is more than 5V.


----------



## Susquatch (Oct 10, 2022)

whydontu said:


> Yes, the LCD displays pull power from the 5v rail of the Nano.
> 
> USB socket provides a 5v rail for everything.
> 
> ...



Thanks @whydontu, you also read my mind by providing the links to the documentation. And yes, I'll be using the serial data adapter. In fact, I already soldered it to the back of the LCD.

Btw, what project boxes do you like? I plan to sit it on top of the gearbox on my lathe until I get a DRO for it. Then it will move to my surface grinder.


----------



## phaxtris (Oct 10, 2022)

Susquatch said:


> Thanks. That's perfect. I really don't want two supplies during development.
> 
> That's interesting that the Regulator gets toasty. That makes sense if running off of a wall wart, but I would have thought that a PC usb output would be 5V so there shouldn't be any drop across the Regulator and it should not get hot no matter what the current draw is. But maybe USB-C is more than 5V.



not sure why, maybe the couple random usb wall plugs i have are not in spec


----------



## Susquatch (Oct 10, 2022)

phaxtris said:


> not sure why, maybe the couple random usb wall plugs i have are not in spec



Oh, it makes sense if you are using a wall plug (wall wart). They are almost always higher than 5V. In fact, some are MUCH higher. Especially the so called Fast Chargers.

I was talking about using the computer port that is used for programming.


----------



## phaxtris (Oct 10, 2022)

Susquatch said:


> Oh, it makes sense if you are using a wall plug (wall wart). They are almost always higher than 5V. In fact, some are MUCH higher. Especially the so called Fast Chargers.
> 
> I was talking about using the computer port that is used for programming.



yea ive never noticed it off the pc...although i wouldn't be surprised if they were out of spec as well, this computer likes to corrupt flash drives.....its quite annoying


----------



## Susquatch (Oct 10, 2022)

phaxtris said:


> yea ive never noticed it off the pc...although i wouldn't be surprised if they were out of spec as well, this computer likes to corrupt flash drives.....its quite annoying



Most of the flash drive corruptions I've seen are caused by failing to correctly stop (eject) the flash drive. 

Most people just plug them in, use them, and then pull them out. However, that's a bad practice. If any data is buffered and hasnt been written to the device yet, it's a sure fire corrupted drive. 

You have to click on the shortcut in the tray and eject the device before pulling it out. It will display a message that its safe to remove the device when its ready. Sometimes you have to do it twice. If I don't get the safe to remove message, I shut my pc down and then remove it.


----------



## phaxtris (Oct 10, 2022)

ha yea that could be part of the problem for sure!


----------



## jcdammeyer (Oct 10, 2022)

Which nano do you have?


----------



## Susquatch (Oct 10, 2022)

jcdammeyer said:


> Which nano do you have?



I believe it is this one.









						CANADUINO® Arduino NANO V3 USB-C Atmega328P + CH340
					

CANADUINO® Arduino NANO V3 USB-C with Atmega328, 32kB flash memory and 16MHz clock speed. 100% compatible with Arduino IDE.




					universal-solder.ca
				




It has a USB-C port on it.


----------



## Susquatch (Oct 10, 2022)

I am 


jcdammeyer said:


> Which nano do you have?



Also using the screw terminal board for convenient pin access. 









						Arduino Screw Terminal Adapter For NANO Atmega328P
					

Arduino Screw Terminal, only 55 x 37mm small. It makes stationary installation of an Arduino NANO module much more reliable.




					universal-solder.ca


----------



## whydontu (Oct 10, 2022)

Susquatch said:


> Thanks @whydontu, you also read my mind by providing the links to the documentation. And yes, I'll be using the serial data adapter. In fact, I already soldered it to the back of the LCD.
> 
> Btw, what project boxes do you like? I plan to sit it on top of the gearbox on my lathe until I get a DRO for it. Then it will move to my surface grinder.


This is the perfect case for the 16x2 lcd display, and the nano screw terminal board fits nicely. The only tricky bit is the orientation of the I2C leads on the display need to be perpendicular to the board.

For my original tach, I bolted a hard drive magnet to the bottom of the case to keep it in place on my lathe gear cover









						PLASTIC BOX HF-255(3) 150X100X50
					

PLASTIC BOX HF-255(3) 150X100X55




					leeselectronic.com
				




For more involved builds I use these with a blank cover plate



			https://www.homedepot.ca/product/red-dot-2-gang-outdoor-box-3x1-2-in-hole-silver/1000407123


----------



## Susquatch (Oct 11, 2022)

Perfect. Thank you! 

I never considered using an outdoor wall box! I was thinking bigger than that. But why? It's just some teeny tiny boards! Maybe I was just subconsciously worried about getting big hands in there. 



whydontu said:


> The only tricky bit is the orientation of the I2C leads on the display need to be perpendicular to the board.



I confess that I don't understand this point. Was I supposed to put the I2C board on the display side of the display board? I put it on the back....... Does it matter? The pins all go in the same solder holes either way. Or maybe I just think they do..... Oh oh.


----------



## phaxtris (Oct 11, 2022)

It should look like this, I buy the displays with pre-installed i2c boards (the cost from china is about the same vs buying both boards seperate)


----------



## Susquatch (Oct 11, 2022)

phaxtris said:


> It should look like this, I buy the displays with pre-installed i2c boards (the cost from china is about the same vs buying both boards seperate)
> View attachment 27029View attachment 27030



Thanks for that. That's the way mine look too. 

I sorta like buying here. I get my order almost right away and the soldering is no big deal. I don't buy enough to be real concerned about the cost. The stuff is basically dirt cheap for what you get.


----------



## phaxtris (Oct 11, 2022)

Susquatch said:


> Thanks for that. That's the way mine look too.
> 
> I sorta like buying here. I get my order almost right away and the soldering is no big deal. I don't buy enough to be real concerned about the cost. The stuff is basically dirt cheap for what you get.



ive bought a few here as well, i agree getting it right away is sometimes worth that extra few bucks

although china is cheaper....im not sure i save any money, instead of buying just the one i need, i buy 5 and put 4 in a drawer to collect dust...because you know "they are so cheap" lol


----------



## whydontu (Oct 11, 2022)

Susquatch said:


> Perfect. Thank you!
> 
> I never considered using an outdoor wall box! I was thinking bigger than that. But why? It's just some teeny tiny boards! Maybe I was just subconsciously worried about getting big hands in there.
> 
> ...


the smaller case is quite close to the length of the 16x2 LCD. The typical I2C module has the four input pin parallel to the board. By the time you allow for the mating female wiring connector, it’s too wide to fit in the case. I try to get the modules without pins, or carefully bend the pins so the connector is perpendicular.









						I2C LCD Interface Module PCF8574 For Dot-Matrix Character Displays
					

I2C Adapter Board with PCF8574, fits right on the back of most LC display modules with Hitachi HD44780 or compatible display controller.




					universal-solder.ca


----------



## Susquatch (Oct 11, 2022)

whydontu said:


> the smaller case is quite close to the length of the 16x2 LCD. The typical I2C module has the four input pin parallel to the board. By the time you allow for the mating female wiring connector, it’s too wide to fit in the case. I try to get the modules without pins, or carefully bend the pins so the connector is perpendicular.



Ah, I see now. For some reason, my head was locked onto a display side issue. But it's really the overall length. 

I wonder if the connections could be unsoldered and redone...... 

But your approach is probably easier. If you can hold them one by one in a set of pliers that leaves the board floating in the air, you can probably put a right hand bend into all four of them with another pair of pliers.


----------



## Susquatch (Oct 15, 2022)

No idea how many others have encountered this, but just in case.....

I hooked up my blue 1602 LCD Display and wired it up. Then I wrote a short program to write to it.

It compiled ok and uploaded ok. But,...... It didn't work. Nothing but a blank screen.

I immediately began cursing about the lack of a debugging capability. None being readily available I started looking for possible explanations. The most obvious being a poor connection - all good. Wrong connections - all good.

Just for sh%t's n giggles I tried turning down the brightness.

Woah! What are those really dimm letters? Turned down the brightness some more and VOILA!






The camera over saturates so here is a compensated photo.


----------



## jcdammeyer (Oct 15, 2022)

Take a closer look at the data sheet for your display. They tend to have an input that adjusts contrast.
Quite often marked Vee.
See the lcd display section here:




__





						Electronic Lead Screw Main Page
					





					www.autoartisans.com
				




Click on the green box of the display section and you will get a pdf of the lcd interface section.
might help

Edit:  Noticed your I2C driver has a contrast adjustment.  Adjust that so the black behind the characters vanishes.


----------



## Susquatch (Oct 15, 2022)

jcdammeyer said:


> Noticed your I2C driver has a contrast adjustment. Adjust that so the black behind the characters vanishes.


That's exactly what I did to take the top photo. But then the camera oversaturates and you can't read it in the photo. In person, it looks just fine.

In the bottom photo I deliberately undersaturated the photo to be able to read the display. But that left the black boxes where the character matrix is.

In person, the display looks just great. The only reason for the post is in case someone else sets up an LCD display that doesn't appear to work. All it takes is to turn the pot on the back of the LCD.

Edit - if I zoom in on the display with the camera, it automatically adjusts the settings so the display looks great. I think the problem with the camera is the brightness of the LCD vs the rest of the scene. 

The phone camera has a manual mode that can be used to adjust settings when the overall scene is very different from what you want the picture to show. For example a face with the sun in the background. You can move in till the face is the majority of the screen, lock the settings, then go back to where you want to take the photo from and take the shot.


----------

