Labels

Wednesday, 21 April 2021

6502: Progress on many fronts

 In the three weeks since my last 6502 blog I have been busy both with hardware improvements and software development.  On the hardware front, a more useful clock has been added, an LED and four buttons have been added to reflect Ben Eaters finished 6502 system and the LCD has been put on the board.  I have also developed a rudimentary hardware error diagnosis procedure.
I have enhanced the vasm/sketch/batch file so a single click can compile and download a new 6502 program and provided some subroutines to write to the screen and use the LED.
These are described in a little detail below.

Subroutines

So far we only have a couple of 6502 assembly programs: one that writes to the screen then accepts input and the other which writes an LCD message.  Assembler is a pain to write so we put everything into subroutines which we can easily re-use in other programs.  In due course we will put the most commonly used into ROM as library routines.  We can immediately add some subroutines based on code we already have:

  init_acia  setup the terminal for i/o   
  putc        write a character to the the terminal
  getc        read a chacter from the terminal
  putstr      write a string to the terminal

Simplified compilation

Previously (see 6502:serial console:software) I simplified my code development cycle to two steps: (1) compile a program and format the executable as input to a sketch; (2) upload the sketch.  Although this beats the pants off removing and replacing an EEPROM all the time it is still tedious.

I found that you can actually use many Arduino IDE functions from the command line using arduino-cli.  I installed it in a folder next to my assembler and tinkered with its configuration file (arduino-cli.yaml) to locate files in line with with my IDE (which uses the portable scheme).  My hardware wasn't recognised automatically in the Windows environment and I had to search a bit to work out that the required platform is arduino:avr:mega.

Once files are in the right place and a batch file links the commands together it is very easy to compile an assembly program and upload the executable in a sketch as a single operation.  This makes software development a lot easier as I forget about the environment and click on a compile icon to build and load a new program version.

I also arranged to save compiled sketches, including executables, as HEX files in the program folder so that I can easily load and run one using a batch file.  I have a batch file for each commonly used program so I can switch between programs easily.

TikTokClk

Ben's 555 clock is a very good learning project but I find it cumbersome in practice.  I set up an Arduino nano to provide a clock pulse on a GPIO output.  Initially I used the serial monitor and delayMicrosecond() function to control the output speed or single step mode.

Once this was working I made it much more useable by adding two buttons to the nano.  One button is used for single stepping.  The other switches between a selection of clock speeds (10Hz, 100Hz, 1kHz, 10kHz).  delay and microSecondDelay aren't very good so I used the micros() function to tell me how many microseconds since the last tick and transition the clock output at the end of an interval.

Button debounce is a nuisance so I used a simple Arduino ButtonDebounce library to control them.  I found this very effective.  You need to make sure your main loop executes quickly and include a button status update method for each button.  A callback then takes control when a valid press or release is identified leaving you to specify what happens next.

As I didn't want to connect the nano during operation I set up 3 LEDs to indicate the speed.  I used D13, which has the builtin LED attached, as my clock output so I can always see if the clock is running.  It is possible to see individual clock pulses at 10Hz, but after that the LED is continually lit.

Hardware Revision 5

Now that we have a more compact clock I can remove the Ben clock and add the LCD screen to the same breadboard segment.  I also added 4 buttons and an LED connected up to the remaining 5 VIA pins.  These are shown on Ben's 6502 photo but I haven't seen them discussed on his videos yet.

By the way I subscribed to Ben's patreon.  His tutorials have been massively informative and fun so I thought it only right to give something back.  He arranges it so you don't pay per week/month/quarter, you only contribute each time he releases a video, so I will continue to benefit as I contribute to his costs.

As I now have a good hardware build, I tidied up the wiring, to remove those long wires which always seem to get added as a design moves on.  I also purchased an FTDI cable so that I don't have my FTDI board sticking out.  With the buttons I use and the LCD and LEDs all at the bottom of the board I think Hardware rev 5 looks good.



What other hardware could I need?  Well an SD card would be good and some sort of integral graphics screen would help, but at the moment I feel they are luxuries.  I am happy I have a good environment with rev5 to write assembly programs with ample input / output facilities.

Diagnosis

When making changes to the hardware or even in normal use, it is possible that a bad connection will prevent the hardware from working.  There are proably 100 wires and 200 pin connections currently in the design.  A trial and error approach to fixing problems is often doomed to be a long and frustrating series of failures.

We keep the Arduino Mega attached to our 6502 system (primarily for downloading programs) and it is also vital for low level debugging.  Whith the 6502 clock stopped (i.e. in single step mode) we can use the eeprom-write sketch to test writing and reading the ROM, that is to say that we can check that ROM connections are working.
We also need to check the program in ROM is the one we expect.  If a different program is loaded, the 6502 may not be doing what we expect.  We can check the assembly listing output file against the executable loaded into ROM.

Next we check that 6502 boot sequence, stepping the processor and using the eeprom-monitor sketch.  This shows values loaded and after a reset it should be possible to see the reset vector FFFC and FFFD loading start address 8000.  Stepping a bit further will show us whether the stack is being used properly (i.e. RAM is working) as the first subroutine is executed. 

If the ROM, RAM and 6502 are ok the problem may lie with I/O.  Either a screen output program (using ACIA) or an LCD output (using VIA) should work so they can be checked independently.

This scheme should allow a failing component to be identified and individual pin signals can then be checked with an LED as necessary.

LED Flash

With a working 65C22 VIA, adding an LED output should be simple, it is only necessary to raise a VIA output pin high/low to turn on/off the LED.
In practice it is a little more difficult.  We have to write a byte to portA each time we change a bit, so if we are controlling the LCD with portA bits 5-7 we need to keep bit 0 as previously set so the LED is in the same state.  I thought that setting the pin as an input might preserve its state but the signal is turned off.  Consequently the LED bit has to be ORed with LCD bits before writing them.

Having worked this out it was an easy matter to set portA bit 0 to 1 or 0 for 255 clock cycles by decrementing an X register counter to zero in a loop and changing the LED pin state each time the value reached zero.  Unfortunately this ties up the processor so is very inefficient.  I will investigate a solution using interrupts, or perhaps a state machine.

TinyCAD

Having finished hardware rev 5 I should update the hardware schematic for Arduino Nano, LCD, LED and buttons.  I am learning the TinyCAD package so I can provide a better representation.  As the diagram becomes more complex the chances of errors increase.  As yet my skills have not advanced far enough for a complete schematic.

Sunday, 28 March 2021

6502 : Add RAM and VIA

 My 6502 system now has a working screen but as yet no RAM.  I find the idea of a working computer with no RAM strangely intruiging, but it is time to move on.  On the face of it, adding RAM is easy as I have done it before following the Ben Eater tutorial and its setup is very similar to the ROM.

RAM

Indeed 62256 memory connection is mostly straightforward.  The chip is located adjacent to the ROM and address/data pin connections are the same.  I rewired two existing NAND gates so they were in the same configuration as Ben's tutorial and used an extra NAND for RAM address wire setup as Ben did.

All worked well, with the proviso that it took a long time.  I found it vital to update the wiring schematic (now Hardware revison 3) before starting and to list out all the changes to existing wiring before I started.  As the circuit becomes more complex, any faults introduced can be very hard to identify.  Loose wires coming out are quite difficult to diagnose but an incorrect wiring change is even harder.

Initially I just added the RAM and wrote a small program to test reading/writing addresses and using the stack in a subroutine call.  I then moved theACIA serial chip from address $0000 where it conflicted with RAM to $6000, which Bens tutorial had previously made accessible for the VIA chip.

It feels very good indeed to have a computer with RAM, ROM, screen input / output which I can program easily in assembler language.  

VIA

To complete my basic computer I need to connect the Versatile Interface Adapter (VIA) so that I can access other peripherals.  I am hoping that this will be my last device attached to the 6502 directly as I have concerns I could mess it up or break it if I do too much tweaking.

Although Ben's initial LCD connection to VIA is not required, it does provide a useful test and confirm whether VIA is working so I connect / test the LCD as previously.

VIA connections are not complex, 8 data pins, 6 address related and 4 control pins.  I need an extra logic gate, and I connected a HCF4069 hex invertor for this.  I moved the A13 address pin from ACIA to VIA so that it uses address $6000.  I then inverted A13 as input to ACIA which is now at $4000.

I found that updating my schematic was vital before making connections as it is VERY easy to confuse yourself.  It is also sensible to write down each connection you need to make beforehand.  Thirdly, testing regularly that the original functions still work provides confidence that important existing pins have not been dislodged by the work.

On completion of the connections I could check that ACIA worked at its new address and then connect an LCD to the VIA as per Ben's instructions and check it work.  All is good, our computer now has RAM and I/O capabilities :) :) :)



Monday, 22 March 2021

6502 : Serial Terminal

 In my previous Ben Eater: 6502 post I set up a 6502 + EEPROM board with a Mega attached which enabled me to download programs with the ROM in situ.  As a second major enhancement, I need it have keyboard input and display output.  Ben does a diy video controller board but that looks painful.  Much more practical for me is to use a serial port with an emulated terminal.  I guess this isn't a pure solution, however I could make it one if I went on ebay to buy an old terminal.  In fact I did consider buying a real DEC VT100 as I used one for much of my (short) programming career but that would be overkill.

My objective is to provide a serial terminal input and output on my 6502 board using hardware compatible with the 6502 and EEPROM.  The best solution used by 6502 afficionados is an  ACIA (Asynchronous Communication Interface Adapter) W65C51 which interfaces to an FTDI chip and provides serial transmit / receive upto 19200bps.  An excellent example circuit and associated program is provided by Dirk Grappendorf.  I particularly liked that the program doesn't use RAM so I could proceed with the program before adding RAM to my computer (I never thought I would be able to say that).

Hardware

W65C51 chips are available on ebay for about £5, and they also require a 1.8432MHz oscillator (HC49) for another £1.




To check my understanding of the hardware I added the W65C51 to my board and connected up power, address, data and control pins (output-enable, chip-enable, write-enable).  I was then able to set pins in a sketch to control ACIA.  ACIA was setup with RS0=A0, RS1=A1 and /CS1=/A15 so that ACIA registers can be accessed at addresses 0000, 0001, 0002, 0003. 

I could then send a character to the serial port at 19200baud with 3 commands:
  Write 0B to address 0002             (for no parity, no echo, no interrupt)
  Write 1F to address 0003              (1 stop bit, 8 data bits, 19200 baud)
  Write characters to address 0000
 

6502 Connection

Once I knew the hardware was connected properly and working I could write a program.  For the previous test 6502 and EEPROM were turned off, so I turned them on and tried saving the simplest possible program to EEPROM and running it from the 6502.

loop:
  8000 LDA #0B             A9 0B    
  8002 STA $0002          85 02   store COMMAND byte
  8004 LDA #1F              A9 1F   store CONTROL byte
  8006 STA $0003          85 03
  8008 LDA #6A             A9 6A   write letter "j" on terminal
  800a STA $0000          85 00
  800c JMP loop           4C 00 80 start from the beginning

I used the monitor sketch to debug the program.  It was easy to have a bad or incorrect connection so I spent some time producing and checking the schematic above to ensure my hardware was set up as expected.  I used a couple of NAND gates to get the ROM and ACIA addressing signals as I wanted them.  In the listing below you can see the three write commands at lines 59,64 and 69.


Software

With a simple program working I could concentrate on providing a working programming environment. Initially I used VASM to compile a simple program and then manually transcribed the bytes into an array in a sketch for download to the EEPROM.  However this quickly became painful and I wrote a small utility program in C to read the VASM hex output file and format it into a text file which was included in my sketch as progdata.h.

Initially I had lots of manual intervention to stop the clock, download data, start clock and reset the 6502/ACIA.  It was easy to get the mega to sketch control the reset and clock pins during EEPROM download. 


I now have an easy programming environment which only requires two steps (1) compile program and format output into a sketch (2) download the sketch with clock paused, then reset the processor.

In the test program I used screen codes to erase and colour text to give a nicer result.











Sunday, 21 March 2021

C graphics programs

 For some reason I had a sudden urge to work out how to write graphics programs.  The natural place to start is on Windows.  I have Mingw installed so I can run X11 programs, in particular X11 programs written under WSL can be run in a window.  The Xeyes sample is shown in the screen shot below.

I also have code::blocks installed so I had a quick look at whether it could do anything for me.  C::B includes a number of openGL related templates.  I tried the openGL template first, it compiled cleanly and gave me a lovely rotating triangle.  I then tried to use GLUT which is mentioned in a number of Google articles on the subject.  GLUT is obsolete and replaced by freeglut which needs some tweaking to get working under C::B (directions provided by GeekforGeeks). Again it provides a lovely demo, in this case some pretty wire frame demos.

In summary I have some great tools at my finger tips when I get an urge to actually write graphics programs.


Shortly after finishing this little investigation on how to write C graphics programs, I stumbled across HTML5 Canvas which provides you with space in your web page where you can put graphics.  The graphics commands themselves are written in javascript.  This is definitely an easier way of doing simple graphics.  A bit of cutting and pasting and I could do a sample on my website.




Tuesday, 16 March 2021

Uprooting a Galaxy S7 Edge

 Two years ago Annette had paid for her lovely Saumsung Galaxy S7 Edge and wanted to unlock it so she could move to another provider.  At the Sutton high street phone provider they suggested the quickest solution would be to pop in to a local phone shop to unlock it.  The (dodgy?) shop failed to unlock it and needed to keep it for someone to look at it, which in the end took two weeks.  When it came back all was not well, it wouldn't accept software updates or allow phone payments to work.  Annette took it to Samsung who said it had been rooted, would have to be rebuilt and might cost a lot of money with no guarantee of repair.  Eventually Annette purchased a new phone and the old one languished in a drawer.

I opened the drawer recently, saw the phone and thought that we should either sell, use or give it to a worthy cause.  There is also a possibility I could do something "techical" with it - use it as a display, an IOT box or may be run Android / linux natively.  The phone is still worth about £130.   It doesn't have a SIM card but I could run apps, browse the net etc.

I saw that it still has some of Annettes information stored so I decided a factory reset would be a good start.  The phone whinged loudly about doing this wanting repeated confirmation of Google and Samsung account passwords which didn't seem to exist.  Eventually Annette managed to delete her Samsung account from the phone and we were able to complete factory reset.  Unfortunately the phone was now effectively dead, it said "custom binary blocked by FRP lock" and wouldn't boot up.  Oh dear!

I googled solutions and it became clear that we needed to replace the firmware.  It appears that a tool called Odin is used to replace firmware and various firmware versions are available on line.  I tried various sites and in the end found an excellent one, sammobile with up-to-date software and firmware.The firmware download is about 2.3GB and they have a very slow throttled free download available (24 hours).  You have to make sure the firmware is for your specific phone model and country.  I thought it totally fair to pay a small amount (€6.5) for a faster download (10 minutes).  You need to install Samsung drivers and Odin software on your PC and unzip the download files.  You then put the phone into download mode, connect it to the PC which then installs it on the phone in a couple of minutes.


After that it is simply a matter of  restarting and signing on with your Google account (which must have been used to sync with the device previously).  The phone now appears totally fine and useable, altogether a wonderfully uplifting experience.  It is a shame that Samsung were unable to do this.  I believe Odin originated within Samsung and they use it themselves so they should have been able to do what I did in a few minutes.




Maixduino : AI meets Arduino

 I read an article in Elektor about an amazing Maixduino hardware board which provides an AI system in an Arduino compatible package.

The board is packed full of juicy hardware, including an ESP32 for ancilliary processing, a camera, SD card, audio and an LCD screen.  At its heart is a Sipeed Maix 64 bit RISC-V module which processes AI.  It can be programmed through the Arduino IDE which avoids a steep learning curve.

I purchased one from Mouser and started to follow Elektor article to set it up.  If you follow detailed instructions and an installation works first time you have an immensely satisfying experience but you tend to learn a little.  When events dont go as planned and issues need to be investigated by looking around different sites and articles, it can be frustrating but you learn a lot more.  Needless to say my installation experience was a struggle.

After some unsuccessful attempts at installing the Arduino software I tried the PC based micropython environment which is described well at icircuit.net and I was soon able to flash Maixduino using the kflash command line tool.  The documentation provided by sipeed also provides good detailed explanations.  Maixduino uses two COM ports one for the Maix processor and the other for the ESP32.  It was exciting to see them both communicating properly, giving me more confidence with the hardware setup and PC connection.  The test program I ran was great, it showed a camera image on the LCD screen.
Returning to the Arduino environment, with my hardware setup validated, I looked a bit more closely at the software environment.  The Elektor article had described a simple Arduino installation which obviously worked for the author.  I was pleased when I found out how to setup multiple Arduino environments on the same PC. Some of the software included in Maixduino libraries has been used by me on other projects, in particular Adafruit graphics libraries.  I set up a "portable" Arduino IDE environment which uses a separate copy of libraries and configuration files.  I then repeated the installation process.  The portable environment is nice as you can see everything relating to libraries you have installed, sketches you have written etc in sub folders of the portable folder.

Using the new environment I could compile a sketch (with a number of warning messages)  but still not "upload" to the board.  I saw two flags in preferences.txt for compile.debug and upload.debug, both set to False.  I turned them on and could see the detailed commands the IDE uses to create and upload a program to a board.   I could see kflash running and failing so I lowered the upload speed from 1,500,000  to 1,000,000bps.  Rebooting and resetting the board now allowed the upload to proceed. 

I tried a few demo programs to verify the environment. Using the Kendryte K210 AI module you declare the ST7789 screen and use the Adafruit GFX library to draw shapes, lines, text etc.  Using th ESP32 I started with a "Hello World" serial monitor display.

I was now able to return to the Elektor article and try the "selfie" program which shows a camera image on the LCD display.  I still had some minor problems, there were duplicate Adafruit GFX libraries (I deleted the one not provided by Maixduino) and a typo in a Maixduino library(googling provided me with a correction to apply).  Finally I was able to complete the first experiment and take a picture, as shown below it is a picture of a rock.
The second example described by Elektor is to run a demo which is a  real image recognition program.  It isn't practical to "train" the AI system oneself without a lot of effort and thousands of images but the sipeed demo provides you with a pre-prepared "neural net" which is copied to the SD card.  A simple sketch reads in the net then analyses a video image before guessing what it shows.

Bella was the first subject.  The program is incredibly fast, it analyses the picture in about a second then guesses.  Bella isn't a very good subject as she moves around and takes whatever position she wants in front of the camera.  The best guess is shown below, the AI top answer is "Fur coat" - very funny, but actually accurate, after that it suggests she is a German Shepherd or police dog! Wow.


I found this a stunning result.  AI hardware, costing £20 can actually identify a dog and have a good guess at the breed within a second.  It shows how real AI technology is and indicates that practical systems are within our reach.  Another stunning Elektor article which is the start of a short series, so there should be more to blog about soon.

Thursday, 4 March 2021

Ben Eater : Arduino EEPROM Programmer

 Having substantially completed Ben's 6502 Hello World project I can start to think what to progress myself.  My priority is to see if I can avoid the need to remove the EEPROM, burn new code in a programmer, and replace it each time I write, amend or correct a 6502 assembly program.

I have a Mega 2560 attached to the 6502 board connected to the address and data buses and therefore connected to most pins on the AT28C256 EEPROM.  The TLS EEPROM programmer I have been using doesn't require special hardware capabilities so providing I connect the Mega to the three EEPROM control pins (Output Enable, Write Enable, Chip Enable) I should be able to write programs to it.

Prototype EEPROM write sketch

I started with a separate breadboard EEPROM with digital I/O pins on an Arduino Mega 2560 connected to each I/O pin.  I firstly wrote a sketch to read data from the EEPROM and display on the Arduino serial monitor.  Functionally this program was very similar to the 6502 video program to read from memory, so it was easy to implement in a sketch.

Ben has an Arduino EEPROM programmer as a separate video tutorial.  It uses a nano and shift registers instead of a Mega to read/write the EEPROM but it provided useful hints for me to write to the EEPROM.  In fact the write process is very simple: disable the output pins, set address and data values on the bus then pulse Write Enable low for 1 microsecond to write data.  To test the program I took the EEPROM which previously displayed "Goodbye, Cruel W" and changed the letter "l" (0x68" to "t" (0x74).  I replaced the EEPROM in the 6502 board and checked that the message displayed was updated. 


John65-02

Originally it was my intention to retrofit this change to the BenEater circuit but instead I have started a new circuit which I will call John65-02.  Leaving the mega connected to ROM I also connected up a 6502 CPU on the board.  CPU and ROM share the same address and data bus so I simply added chip enable, output enable, write enable logic from 6502 as previously.  I connected Bens clock circuit for a testing clock signal.  With the mega connected to 6502 read-write bus, clock and reset I was able to run the Mega monitor program to watch what was happening on the processor.  Importantly, without changing any connections I can also run a sketch to re-program the ROM.  I thought I might have to turn off the 6502 using its ready or bus enable pins but it turned out that , as long as I stopped the clock I could run the ROM update.

This is great progress, I can avoid removing chips to change a program.  It was becoming a liability inserting/removing the chip on a crowded board.  Eventually wires would be dislodged causing a difficult debugging exercise.

In addition to being able to write to the ROM, I have more work to do.  I need to be able to move the raw data from a PC file into a sketch so that I can download it to the ROM.  I am considering using X/Y/ZMODEM to do this, as I did for the RPI bare metal programs.  Alternatively I have ordered a wide 28 pin ZIF socket, which I could put into the circuit to make ROM extraction / replacement easier.

Ben Eater : 6502 : Clock and Loop

 We now have our hello world program using Ben's home made clock and all looks good.  The clock has been really helpful in allowing us to step through programs and run them slowly but we should really run more quickly using an oscillator.  In previous tutorials we looked at a number of timing considerations relating to our chipset.  Now (video #8) Ben guides us through clock considerations for our breadboard circuit. 

All circuits have inductance and capacitance from wires and physical geometry of the system, breadboard circuits suffer more than PCBs.  The unwanted effects include spikes and sluggish changes and they increase with frequency. Looking at the 6502 data sheet we need our rising or falling pulse to transition within 5ns.  Ben checks the diy clock and 5ns response is fine.

The 1mhz clock chip is then connected to the circuit.  Again 5ns response is fine so the 6502 should be fine. However the circuit doesn’t work.  The LCD is reacting more slowly than it should. In fact if you add 750 NOP instructions to commands the circuit works!

Our problem (video #9) is that we don’t check the LCD busy flag before sending the next command to it.  Ben guides through branching, looping and reading LCD values so that we can check LCD status and send commands in an orderly fashion. Our LCD happily displays text with the 6502 working at 1MHz.

Now we have the ability to loop we can tidy up our assembly program to send a message, we store the message characters as data in a block of memory and loop to read through upto a null byte.

Our Hello World is now fully working and we have learnt a huge amount about building basic 6502 systems along the way.





  


Tuesday, 16 February 2021

Ben Eater : 6502 : Using RAM and providing LCD output

 By the end of the previous tutorials Ben had arranged for us to write assembler programs which can be stored in an EEPROM so that the 6502 can run the program.  We also have a "Virtual Interface Adapter" which gives us the ability to latch output from the data bus and initially we arranged to set LED patterns.

LCD

Displaying output on LEDs becomes very dull very quickly so our next mission is to display a message on an LCD panel (video #4).  I am quite familiar with the HD44780 LCD controller from other projects so I found this quite easy.
The LCD has three control signals RS RW EN which we attach to VIA PORTA and 8 data pins which we attach to PORTB.  Register select switches between the instruction register and data register in the controller and RW determines whether data is being written to or read from the controller.  The Enable signal is pulsed to actually execute the command.  We program the LCD by putting a character or instruction in port B, setting RS and RW in Port A then briefly enabling the EN pin.  It takes about four command instructions to setup the LCD and we can then send characters in subsequent commands.  Each display command takes 8 assembler instructions so our program is about 160 lines long.
Finally we can display our message

Stack

It is a real pain duplicating 8 assembler instructions each time we want to send a character so we use a subroutine mechanism.  Define the character to be displayed then call a subroutine to control the LCD. At the end of the subroutine return to define / process the next character.  This removes the repeated code and our program is reduced to 75 lines.

 Unfortunately this program doesn't work!  The 6502 needs to save a return address when it jumps into a subroutine (JSR) so that it can return to execute the next instruction when it is finished (RTS) (video#5).  The 6502 uses an area of memory called the stack 0100-01ff  where it pushes 2-byte addresses and pops or pulls them back on return.  256 bytes allows for upto 128 nested subroutines.

RAM

Previously we attached an EEPROM to the 6502 bus and read data from it.  We attach a 62256 32k x 8 bit RAM chip, which uses the same pin positions as the EEPROM.  We set it up so that we can address it at 0x0000 to 0x3FFF (16k). Our life then becomes rather complicated as we delve into the timing diagram (video #6).  A lot of patience and study of the 6502 and 62256 datasheets is required to get this right.  It turns out that we need to ensure that A15, the first address line is set before the others and we have to add a little bit of circuitry to achieve this.

Finally we can run our subroutine (video #7) and stepping through we see data written to the stack as part of each JSR and retrieved/moved to the PC (program counter) when executing RTS.  It works a treat and our subroutines do their job.

Tuesday, 9 February 2021

Ben Eater : 6502 : Writing in Machine Code

 In my  previous 6502 post Ben showed (video #1) how to connect up the microprocessor with a few inputs so that it would run through its boot sequence.  We used an Arduino Mega to monitor address and data lines so that we can see what is happening.

We now need to write a program (video #2).  We know that the 6502 reads the program start address from the reset vector at 0xfffc and 0xfffd so we have to provide some hardware (memory) which is addressable.  By that I mean we attach the address/data lines on the 6502 to address/data lines on a memory chip and when requested the memory chip will look at the address lines and respond with the bits at that address on the data lines.  

For the program memory we use an AT28C256 32KB EEPROM.  This has to be configured with a special programmer, we use a TL866II Plus programmer to write our information on to the EEPROM.  The first step is to define a machine code program which the 6502 will understand.  We then need to create a file containing the program and, using the programmer copy it across to the EEPROM.  Ben uses Python to write a file called rom.bin which is exactly 0x8000=32KB long.  The programmer copies this to the EEPROM which can then be attached to the 6502.

In order to see some results we need the 6502 to produce some output.  Using a cunning scheme Ben arranges for the EEPROM input to use memory addresses 0x8000-FFFF leaving addresses 0x0000-0x7FFF for output.  A multipurpose output chip called a W65C22 Versatile Interface Adapter is attached to address/data lines (lets call them busses from now on).  We will use it to latch information from the data bus to an output port.   We attach LEDs to the output port so that we can see the results.  Another cunning scheme is required so that the W65C22 reacts when the 6502 sends to addresses 0x6000..... 

Now we have hardware attached where we can store our program and we can control an output device.  A short machine code program is written to configure the W65C22 for output, write output patterns to the LEDs and loop around.  Awesome.

This is a packed hour long lesson, at the end of which we should understand programming an EEPROM, ROM addressing, latching output, using an output chip and writing machine code.  Wow.

After the steep learning curve of video #2 we consolidate our position in video #3.  Writing machine code quickly gives you a headache and it is much easier just to write the assembler code and ask an assembly program to convert it.  Video #3 shows you how to install and use vasm to create rom images which can be loaded into the eeprom.  This results in another LED program which is demoed below.


 

  




Monday, 8 February 2021

MacBook Air M1

 I wanted to buy a laptop, mainly because I am not happy sitting at my desk all the time whilst typing.  An iPad is fine for armchair computer use but not for typing.

A Windows laptop is the obvious choice but I am not enthusiastic about Windows software at the moment.  In particular a practical alternative to MS-Word for word processing would be welcome.  Previously I borrowed Harry's ancient MacBook Pro and found it quite usable despite being unfamiliar and 10 years old.  In addition macOs is linux-based and I see lots of Macs used in linux-related tutorials these days.  Although miscellaneous software is more likely to run on Windows, I don't expect the laptop to be used for everything and it doesn't need to replace Windows.

The new Apple MacBook Air M1 is based on an ARM chip which is faster than and uses less power than previous Intel-based processors which gives it a very long battery life and means it requires no fan so makes no noise.  It became available in the UK in November 2020 at John Lewis Partnership which is my preferred supplier as they combine competitive prices with excellent service.  The entry level model costs £999 has 8GB RAM, 256GB SSD and 13.1" display.  It looks excellent value compared with older MacBooks or the M1 with larger SSD.  It is also apparently possible to use App Store iPhone/iPad apps, which haven't previously been available for MacBook users.

As you would hope and expect Apple set up is straightforward and it only takes a few minutes to be working on the Internet.  I was particularly impressed with the user guide and newbie guides which are specific to this model.  I shall perhaps blog later on getting used to MacOs. 


Sunday, 31 January 2021

Ben Eater : 6502

 Ben Eater is a remarkable electronics teacher and the 6502 video series continues to demonstrate the high quality he has brought to previous projects.  I am excited to get started with my new 6502 microprocessor kit.

The 6502 microprocessor comes from a simpler age, its data sheet has only 32 pages and it needs no ancilliary components; it conveniently uses 5V power.  We put the processor on a breadboard and connect a few pins to get started:

  • four inputs used for control purposes are set to high and a reset button which can be set low to reset the processor
  • for a clock input use the Ben Eater clock module; it allows us to run the processor slowly or single step it in the course of setting up and testing our hardware
  • connect a few LEDs to the first 5 address pins
When we apply power and start the clock ticking we see LEDs flashing showing that the processor is doing something, although we dont know what.

An effective way of finding out what is happening is to use an Arduino Mega to monitor the 16 address and 8 data pins.  We also want to check the status of the read/write pin.  A simple sketch, using interrupts reads each pin with the clock ticks and displays address/data values on the serial monitor.
As the data pins will be read at some stage we hardware values 11101010 (0xEA)  using resistors to the data pins.

In conjunction with the manual we see that on reset there is a 7 cycle initiation sequence which reads the reset vector from memory address FFFD and FFFE. Our read operations always return 0xEA so the reset vector read in is an address EAEA and we can see that the processor starts executing a program from that address.   Each instruction read in will also be 0xEA, which was conveniently chosen as it is the NOP instruction.  We can see from the Arduino serial monitor that the processor continuously reads and executes NOP instructions (which each take two cycles) and increments the program counter.


Amazingly without knowing very much at all we have an understanding of where we need to load our programs and we can see the simple NOP program running.  Good progress for our first hour.



Thursday, 28 January 2021

DIY Oscilloscope

Occasionally I need to use an oscilloscope to look at a wave form.  They cost about £200 which is quite expensive for something I would only use a couple of times a year.  They are also quite complicated and it is potentially difficult to find the view that you want.

A few years ago I used PC based software which worked in conjunction with a PC sound card to work as an oscilloscope.  The input is taken from signal and ground into the PC jack plug which is + or - 0.7V.  The sound card then provides 16 bit samples at 44,100Hz.  A quick look reveals that these programs are still available, for example Christian Zeitnitz or TorVergata.  A problem with using the PC sound card is that you have to make sure your input does not exceed 0.7V, otherwise you could damage the sound card or PC.

More recently I have seen Arduino based solutions and as soon as you start looking there are loads of them.  The first one I chose to look at is at electronicsforu. A simple sketch runs on an Arduino nano to capture a signal on an ADC (Analog to Digital Converter) pin and send it through the serial interface to the PC.  A simple program pcscope.exe runs on the PC to discover the arduino and display the serial data as a wave form.  This is about as simple as you can get and it works without other components on a 5V circuit and only requires a signal/ground connection to the circuit under test.  I may look at other more sophisticated solutions in due course. The pictures below show a bit of debuggin on my Ben Eater clock module flashing at about 1Hz.  The arduino nano takes its signal from the 555 timer output via the white wire and the PC displays the output wave form.


Of course once you start looking at these free solutions other ideas come up.  Oscilloscope for ipad costs £10 and looks good for audio signals but it is probably not suitable for electronics.  More fun would is a build your own JYE Tech oscilloscope, available from Amazon for £30.  It wouldn't be very accurate but it should do the basics.

A real oscilloscope would be worthwhile if I want to spend any time learning how to use it.  Probes and electronics need to be good quality to get results so spending £200 on something like a Hantek DSO5102P (reviewed by my heros Rui and Sara Santos at RandomNerdsTutorials) would be reasonable. 

 


Monday, 25 January 2021

Ben Eater : Clock

 Ben Eater is a wonderful teacher of digital electronics.  As I watch his youtube videos I am always amazed at how clearly and concisely he can explain and demonstrate circuits.  His big project was a set of videos explaining how to build an 8 bit microprocessor up from TTL components which I greatly enjoyed.  More recently he has shown how to make up a system based on the 6502 microprocessor.  Both sets of videos make me itch to follow his instructions to make my own system.  He has been kind enough to make available kits of parts containing everything needed to build his projects so I will do just that.  

Complete 8-bit CPU

It would be amazing to construct the 8-bit uproc but I don't know that I would have many uses for it once finished.  I have very fond memories of the 6502 from my youth, I used it at work around 1980 at British Aerospace and found its assembler language sensible and simple compared to other hardware languages I had to use at the time.  The 6502 was hugely successful and formed the basis of the Apple IIe, the BBC micro, Ataris and many others so I am looking forward to being reacquainted.  One of the many blessings of a daugher-in-law from California is that it makes it easier to purchase Ben Eater kits and get them back to England so I am now the proud possessor of 6502 kit and clock module.



The clock module is the first step of the 8-bit uproc project but is also useful for 6502 testing.  For a processor the actual clock speed will be 1MHz or greater, but when testing the system it is useful to be able to run the clock very slowly (c1Hz) or even single step it.  The 555 timer provides many different functions, it has been sold since 1972 in huge quantities. The Ben Eater clock circuit utilises three 555 chips to build our testing clock and demonstrate how it is configured.

There is a set of 4 videos, the first three going through configuring 555 as an astable, monostable and bistable device and the fourth one adds some simple logic gates so that we can produce a single tick or a regular tick-tock.  Ben describes how to choose ancillary resisters and capacitors to achieve the desired effect, how to connect the circuits and some additions to make the circuit more reliable by "debouncing".






Tuesday, 12 January 2021

Arduino MP3 Player : Talking Sums

Back in November I blogged about a tiny board, the size of a microSD card holder, which plays sounds and music.  Although I liked the idea, I ran into big problems using the weird AD4 format required for sound files on the SDcard.  I saw that the DFPlayer mini is newer and supposed to be much better (and cheaper) so I ordered some.  I am pleased to say it is wonderful; sound quality is impressive, Arduino support / compatibility is  fine; it permits lots of storage, has plenty of features and it is very, very cheap. 

For my purposes, spoken word sound files are more interesting than music for which I already have various solutions.  As a proof of concept I will write a simple Arduino calculator sketch which speaks the numbers, operators and result as you type.  This is probably very similar to a number of kiddies electronic toys.



The first steps are to find out how it works and  produce some sound.  The definitive reference is at the DF Robot product page  which includes specs and links to a manual and wiki. The wiki shows a simple setup requiring only 5 connections (VCC, GND, SPK1, SPK2 and IO 1) to play sounds.



 I put a few music tracks by the incomparable Ariane onto a 2GB FAT microSD card as /mp3/0000.mp3, /mp3/0001.mp3,......  I then connected a small speaker and power on a bread board.  When I touched pin 9 (IO 1) to GND music began to play.  Very impressive and pretty good quality!

There was some distortion in the music so I amended it in Audacity normalising it by -6db so that the peak values were reduced  and lowering the sample rate from 320kbps to 192kbps.  Sound quality is now very good, even on the dodgy speaker I am using for testing.  It is also possible to use the DAC outputs (DAC_L, DAC_R), but I didn't try that.


Next we want to connect an Arduino to DFPlayer which uses a serial command interface for full control.  It requires just two pins for serial transmission.  As we still want to use the Arduino RX/TX pins for the Serial Monitor we connect a couple of PWM GPIO pins and use the Arduino SoftwareSerial functions to program them.  




We also download the DFRobotDFPlayerMini library which gives us a set of functions to control the player.  Some articles (e.g. instructibles) use the command interface directly, but it is better and easier to use a library.  The samples provided aren't very exciting but they do show you how the sketch should be set up and the different functions which are available.  I was quickly able to provide a sketch to choose a track and start it playing.

Our objective is a talking calculator.
As the DFPlayer can store thousands of samples, a whole dictionary in fact, it is perfect for spoken instructions or feedback.  I couldn't find a good set of mp3 words on the internet so I set up some of my own.  It was easy to record the digits 0 to 9, and operators plus, minus, equals using a headset and Audacity software.  I recorded them as a single file with short pauses inbetween.  I could then select a snippet and save it as 0000.mp3, 0001.mp3 etc.

A simple function within the sketch speaks whatever you type and then the result.  For my POC I only dealt with single digits, non-negative numbers, addition and subtraction.  The result was very gratifying.

My verdict is that this is a great little tool.  Addition of a chip and a small speaker gives an extra dimension to your Arduino projects which can tell you what to do and describe results to you.










Thursday, 31 December 2020

Christmas lights : lightshowpi

 I have a very simple some coloured  5050 LED strips which provide a very colourful addition to Christmas.  Lightshowpi (LSPi) is wonderful Raspberry Pi (RPi) software which analyses music and allows you to configure lights accordingly.  I think most people use it with relays and big external displays but I prefer a small indoor spectacle when listening to Christmas songs.  My LSPi setup tends to change each year and this years effort works well.

The Raspberry Pi has rubbish sound quality through the headphone jack.  This year I attached a USB audio card which only cost about £5 and provides a signal quality which I can send through my hi-fi (is it still called that) to play pleasant sounding music.  It is possible to spend a more money (£60-£130) on an RPi DAC HAT or high quality USB audio but this is quite acceptable to me.

All my music is accessible using the venerable linux music player daemon (MPD) on an RPi which has a share to network attached storage (NAS) and can stream radio stations.  I use a web interface to mpd  so I can select, play and manage music from a browser.  LSPi is quite happy playing an http or icecast stream from MPD and I can direct its output to the USB audio card.

Previously I used bluetooth connection from RPi/MPD to my hifi but this makes synchronisation a little tricky as bluetooth introduces a selay of 2-3 seconds.  When playing sound through the USB card LSPi synchronisation is much better and I can see the colours changing in time with the notes.

The 4 colour LED strip runs at 12V and requires three GPIO pin signals to control Red, Green and Blue output.  The RPi can only provide 5V, limited current output so I have a simple setup with MOSFETs driving the LED strip with an external power supply.





Wednesday, 30 December 2020

Bash in full screen mode with colour

 I rarely use a linux GUI and I find that command line output is often dull and difficult to read.  It is easy and common to embellish the shell prompt with extra information and colours.  Also it is possible to amend colours for directory listings, editor entities etc. and I found a good list of ideas on stackexchange.  I would like to be able to do some simple formatting tasks on displayed screen output, such as putting text at a specific cursor position, in colour, perhaps surrounded by a box as shown below.


I can do this with a few escape codes in a script as shown below.


We start with a command to clear the screen \e[2J.  The \e causes the escape character to be sent, and the following three characters are a "vt100 escape code".  A VT100 (see below) was a screen introduced by Digital Equipment Corporation in 1978, one of the first to support escape codes.  I used vt100s in the early 1980s for programming and became very familiar with their capabilities.  DEC produced wonderful minicomputers in the 1970s and early 1980s but fell from grace and were consumed by Compaq, who in turn were digested into HP.  When working for HP in the 2010s I talked to a few of the engineers who had remained after the demise about the good old days and we lamented the passing of a great company.



Returning to the subject we can see the command to clear a screen in a list of VT100 escape codes which includes "esc[2J" to clear the screen and "esc[<v>;<h>H" to position the cursor. Thus "esc[6;20H" positions the cursor at row 6, column 20.  Note that the linux TERM variable does not need to be set to vt100 for this to work, it worked for me with TERM=xterm or TERM=xterm-256color.

For line drawing characters we use VT100 character codes. In the table we see that unicode characters 
\u2500, \u2502, \u250c,\u2510,\u2514,\u2518 are what we need to draw the box.  We need quite a few \u2500 characters to draw the horizontal box line.  What we have so far gives us a very presentable box around our title.

We now want to add a bit of colour to the text / box, which is easy.  I googled a simple reference at bluesock. Within a bash script it isa easier to use variables for colours and unicode characters and I changed my script so that it was a bit more understandable when colouring it in.  For example to set text to cyan I used the variable $COLOR_LIGHT_CYAN with value "\e[1;36m"

We now have the capability to control our ssh shell display layout.  Clearly it would be a real pain to format our screens like this in practice but I find it really useful to be able to understand how to do it at this level.  One could setup a standard bash script containing variables for all the options/colours you use or combine with other linux utilities, for example tput for clearing the screen and positioning the cursor.

I like the idea of a simple C program to do some of the work.  I find bash a bit painful for processing and it makes sense to use C for this.  As an exercise I redid the title box in C without any extra thought.

It is very simple, you just invoke gcc to compile it, and I saved it as /usr/local/bin/colourtitle.  I could then display the title putting colourtitle in a script.  Of course I need to accept a title as an argument and allow selection of colours but this provides an easy proof of concept.




Tuesday, 10 November 2020

Arduino MP3 Shield

 I saw a reference in an article to a small simple cheap mp3 shield for Arduino and it seemed like a fun and interesting idea.  The shield incorporates an SD card holder, and in fact is only slightly larger than a micro SD card in a 16 pin DIP format. I found that I could buy a couple on ebay for £5.



A quick look on the internet and I found a couple of useful tutorials at buildcircuit.com.  It turns out you don't even need an Arduino, you can wire up the mp3 player to 3V3 power and a speaker, put some music on an SD card and start playing.  There is a small catch - the player doesn't play MP3 or WAV files only an unusual format called AD4 so you have to convert them first.  I used some sample files which were available and copied them to the card as 0000.AD4, 0001.AD4.... etc.  Once the card was inserted I simulated play by grounding pin 9 and a snippet of music played.  It was only about a second but it was a great test to get started with.

Next came the Arduino setup.  The tutorial suggests an ESP8266 but any Arduino will work, you just need 4 digital pins, and I used a nano.  There is a simple WTV020 library available in the Arduino IDE Library Manager which I installed.  It only consists of a single C++ program and you can see what functions are available.  I used an article from electronoobs to help me a bit with the setup.  The sample sketch shown in the article is also provided in the Arduino library so you can simply use this sketch, amending pin numbers as necessary.  I compiled and downloaded the sketch to the Nano and it played a little music.

I found a text controlled by keyboard input via the serial monitor much easier to experiment and used a little sketch to test the functions.
 The results were excellent.  The music played is very reasonable qulaity and it is easy to change track, stop, pause etc.

Now I needed to use my own sounds/music.  AD4 format isn't well known or supported. There is a utility SOMO or UsbRecorder I downloaded from 4dsystems.com.au.  I first took an mp3 track and converted it in audacity (mix down to mono, Normalise to -6db, export Quality=16kbps).  I then used SOMO to convert it to AD4.  Converting the mp3 track to low quality mono decreases its size to about 5% but converting to AD4 increases its size about 5x.  The newly converted track, once copied to SD card works perfectly on the music player and sounds good.

Since we have a multitude of ways of playing high quality music files it isn't likely that in practice we will have a use for a low quality arduino controller music player.  However it will be much more useful for spoken words, we can get the arduino to speak!  The player has the ability to play up to 512 files (0000.AD4 to 0511.AD4) so we have a vocabulary of 512 words to play with.  Unsurprisingly I couldn't find a set of AD4 format words and even MP3 format words aren't that easy to come by.  I found shtooka.net which has a large collection of about 4000 English words in a female voice "Mary" I could use.






Tuesday, 13 October 2020

More Jongo Music

Objective

It is nearly two months since my last post.  Mostly tech time over that period has been spent looking at Jongo music.  The multiroom music server MuSe and album player aMuSe control what music is played on an mpd music server.  The sound is sent to a Jongo using bluetooth and distributed amongst other Jongos using caskeid - a bespoke Jongo program which shares and synchronises sound.

For some reason the bluetooth connection is not very reliable.  It could be that the RPi bluetooth device or configuration has issues or the Jongo firmware/hardware is not good enough.  For whatever reason it is not always possible to use our web applications to play music and sometimes the system cannot be restarted, evening by rebooting the Jongo and RPI.

There isn't much you can do to monitor control bluetooth devices.  On RPi bluetoothctl allows you to check the status of connections, but it doesn't always allow you to see, diagnose or correct problems.  There is a python bluetooth module (pybluez) but only has similar capabilities.  Jongos can tell you very little about their bluetooth connections.  

Consequently I decided to look again at setting up Jongos using the wireless interface.  If using the Pure app Pure Connect to control Jongos you are using wireless and can play multiple Jongos in synchronisation.  We don't have any specific documentation telling us how Pure Connect controls Jongos but we would like to achieve something similar.

Jongo Access

Our first task is to be able to access Jongos reliably.    Jongos setup a random port for wireless communication and keep the same number until rebooted.  The only way to find this port number is to use ssdp.discovery but an ssdp.discovery dialog takes about 30s and it is inconvenient to wait that long for each access.  Ellis Percival has provided a python upnp library which provides ssdp / upnp functions. His github page also provides a great tutorial on using the library to interrogate / control devices interactively with ipython. I wrote a simple program jongoPorts.py which runs a discover once a minute and stores results in a file.  All other programs just need to read the file contents to be able to access each jongo.  I also wrote a program jongocheck.py which looks out for any port changes or devices appearing / disappearing so that if testing goes wrong I can check whether device or network access issue occured.

I have been unhappy with VirginMedia wireless coverage for some time (in particular interference from the microwave) and recently purchased a cheap and cheerful router with, hopefully, a better wifi range.  Jongos only work at 2.4GHz so I setup a new 2.4GHz network and made sure that all Jongos are on that segment with DHCP allocated fixed IP addresses.  We now have our hardware and network configured and monitored to increase reliability.

Packet Capture for Reverse Engineering

Pure have discontinued their Jongo range and it never really caught on (Sonos captured the market) so there is very limited information available on how Jongos work.  The Pure Connect (PC) app does a pretty good job at allowing you to play albums or stream radio stations.  We have previously been able to instruct a Jongo to play a URL (song, album or radio stream).  However I wasn't able to work out how PC controls multiple Jongos in synchronisation.

I wrote a short python program which interrogates Jongos to find what they are doing.  This can be set up to run  and  provide frequent upates with the Bash watch command.  It shows us that we add an extra Jongo to PC, it synchronises to the first one using an RTSP stream as shown in the picture below where device Jon was running and Job was added as a second synchronised device.


It is difficult to guess the commands which PC issued to set this up so we need to capture them.  I used wireshark to monitor the wireless network 192.168.0.0/24 but it only shows ssdp multicast packets.  It  doesn't show any http packets, possibly because the packets are WPA encrypted when they circulate the network.   The subject appears to get quite complicated.  Firstly, the interface has to be in "monitor" mode not "promiscuous" mode.  Secondly, Windows does not support monitor mode and nor does the RPi built in wireless adapter.  Eventually I found that my WiPi wireless adapter does support monitor mode.  A utility airmon-ng allows you to set the adapter into monitor mode and it does show lots of information - for example you can see all devices attached to the neighbours wifi networks.  However it still didn't allow wireshark-linux to show me http dialogs.  

Close to despair, I made a breakthrough when I found fiddler which does http packet capture and allows you to look at packets in a variety of formats.   Much more significantly it allows you to set up a proxy for wireless devices on the network.  I set up my Windows computer on the wireless 2.4GHz network and setup Fiddler with port 8888 as a proxy.  I then told fiddler to configure itself for Windows and to decode https traffic.  I setup an old ipad on the 2.4GHz network and setup Windows port 8888 as a manual proxy.  Fiddle now showed all traffic through my windows computer including all ipad http traffic.

I captured Jongo related packets using fiddler, they are all xml formatted and they work with the upnp protocol.  It was very easy to see how Jongos achieve synchronisation.  The original Jongo (Jon in our example above) starts music with a SyncPlay command, it also creates a unique session id with CreateSession.  When you add another Jongo in the PureConnect client it issues a GetSession command to determine the session id.  It then tells Jon to AddUnitToSession for the second Jongo (Job).  Command RemoveUnitFromSession is used to stop playing on the second Jongo. Fiddler organises the output so it is simple to understand as shown below.


Once we know the commands to issue it is simple to implement the play/stop add/remove functions in python.

Using Synchronised Wifi


We can setup mpd to output icecast2 or http streaming and then load the stream URL to Jongo and can share it on multiple devices.   This allows us to play whatever we decide on the MuSe or aMuSe web pages on synchronised Jongos throughout the house.  There is a catch - streaming introduces an inherent delay so if you start or stop aMuSe you must wait 8s before it takes effect.  This makes it irritating using the apps interactively.  However when we want to listen to the radio or an album streaming is generally fine and we should be able to expand functionality and usefulness of JongoPanel.  MuSe and aMuSe will be targetted at playing on a single Jongo in the study.