PIC+AVR: What affordable programmer to work with the most devices? - Page 1
Forum section: electronics / general

author: RedLion
author_rank: Regular Contributor
timestamp: April 03, 2022, 01:06:18 pm
content: Let me preface this with the fact that I have almost no experience with microcontrollers beyond the occasional Arduino project, I'm more of an FPGA man myself.So far I've been getting by with the Arduino as ISP and futzing with breadboards and flying leads, but I'd like something more convenient for a "semi-series" production.I'd like to get myself an affordable programmer that can program as many microchip devices as possible before I have to upgrade. What I absolutely need beyond AVR ISP is the TPI and HV programming, as I want to use the Attiny10 in an upcoming project. I'm thinking of usingThe IDE Formerly Known As ATMEL Studio, which I have used a few times, since it can also open Arduino projects if need be.The programmer that caught my eye is the PICKIT 4, as that is advertised as working with both AVR/Microchip Studio and PIC/MPLAB, should I need to change architecture. It is also fairly affordable for what it can do. Now conventional internet wisdom says that can't happen because the PICs and AVRs are in civil war for some reason, but the Microchip marketeers have me believe the PICKIT 4 can do both plus debugging plus TPI plus HV. All I would have to do is whip up a few adaptors. But the documentation is not clear on that beyond "yes it can do that".Should I get the PICKIT 4 or a specific third party AVR ISP, in which case, which one? There are so many to choose from.Thanks for any help guys!

author: JPortici
author_rank: Super Contributor
timestamp: April 03, 2022, 01:16:11 pm
content: PIC+AVR = Pickit4, period.the snap, too, if you don't need HV programming

author: RedLion
author_rank: Regular Contributor
timestamp: April 03, 2022, 01:22:03 pm
content: Quote from: JPortici on April 03, 2022, 01:16:11 pmI considered the Snap, and building a HV adaptor, but it doesn't support AVR Studio apparently

author: DavidAlfa
author_rank: Super Contributor
timestamp: April 03, 2022, 01:25:35 pm
content: Pickit4 is pretty expensive, unless for professional use or something that justifies that price, I'd take the cheapest.For PICs, an inexpensive Pickit3 clone.For AVR, a cheap CH341A + NeoProgrammer (Tested).

author: RedLion
author_rank: Regular Contributor
timestamp: April 03, 2022, 01:29:37 pm
content: I think the price is fair, if indeed it lives up to it's specs.

author: SiliconWizard
author_rank: Super Contributor
timestamp: April 03, 2022, 05:49:20 pm
content: The price of the Pickit4 has like doubled compared to the older Pickit versions, but it's still affordable. The ICD4 is another matter, and would be certainly overkill here.If the OP finds it affordable and it fulfills their requirements, then I'd suggest getting one and calling it a day. It does support HV, TPI and pretty much all Microchip MCUs. You can look at the manual if you haven't already:https://ww1.microchip.com/downloads/en/DeviceDoc/PICkit4%20In-Circuit%20DebuggerUG-DS50002751B.pdfThe problem with fiddling with clones and such is that, unless you have experience with this and are ready to spend some time figuring things out, or even take the risk of buying crap... using something that just works can be a lot less pain and worth the extra dollars.Now for sure if you want more options, Microchip is not the best out there, and you'd have more luck with anything ARM Cortex-based, but if you have zero experience with those, then the extra time needed for the learning curve would have to be factored in.

author: fchk
author_rank: Frequent Contributor
timestamp: April 04, 2022, 11:07:47 am
content: Quote from: RedLion on April 03, 2022, 01:06:18 pmJust have a look at the PIC10F2xx series, which are pincompatible. A cheap PICKIT3 clone would be enough for them.My feeling is that the *Studio is a dead end. Microchip ist heavily invensting in MPLABX and the XC compilers, and this is their future.fchk

author: tepalia02
author_rank: Regular Contributor
timestamp: April 18, 2022, 02:34:07 pm
content: Universal programmers are quite expensive in my opinion. For AVR chips, USBASP is reasonable. For PIC, I used this one:https://www.techshopbd.com/detail/212/PIC_Programmer_R1_techshop_bangladeshDon't know if there is something like this available where you live.

author: fchk
author_rank: Frequent Contributor
timestamp: April 18, 2022, 06:42:45 pm
content: Quote from: tepalia02 on April 18, 2022, 02:34:07 pmUSPASP only works for classic AVRs with ISP Programming. It does not work for XMega with PDI. It dows not work with small ATTinies with TPI. It does not work for the newer Microchip AVRs with UPDI. It can only program but not debug. Seems to be a rather mediocre suggestion to me.Quote from: tepalia02 on April 18, 2022, 02:34:07 pmThis is a PICKIT2 clone, and as such it can't be used with newer 8 bit PICs, most 16 and all 32 bit PICs. You are rather limited with that. Also not a very good suggestion, given that Chinese PICKIT3 clones cost nearly the same.fchk

author: Ian.M
author_rank: Super Contributor
timestamp: April 18, 2022, 07:18:11 pm
content: Many far east PICkit 2 'clones' are/were absolute crap with no target Vdd control and inadequate Vpp generation. If offered one free, say no!OTOH a genuine PICkit 2 (or accurate clone) can program just about all old FLASH PICs that need HV programming and with AVRDUDE, program most AVRs as well, so as a companion to a MPLAB SNAP (which has no HV programming support) it can still make sense to own one.A PICkit 3 supports more PICs and can be used in the same way with AVRDUDE, but (IIRC) needs to be put in PICkit 2 emulation mode using its standalone "PICkit 3 Programming App and Scripting Tool" for AVRDUDE to use it, then afterwards, reverted to MPLAB mode before MPLAB can use it.

author: T3sl4co1l
author_rank: Super Contributor
timestamp: April 18, 2022, 07:28:49 pm
content: Heh, even my ancient AVRISPMKII does PDI (XMEGA etc.); not debug though. I'm currently doing UPDI via serial adapter (via latest AVRDude build). Don't use PICs though.Yeah, for working with the whole Microchip spectrum, you're pretty much going to need a Microchip programmer (Pickit4). I don't know of any 3rd party tools that support everything; but again, I'm no PIC user, and there may be things out there and I'm just not aware of them. Or, eventually, someone will create free tools like that, but maybe that hasn't happened yet. Or also, particularly if you want integration with 1st-party tools, you're probably not going to have much range of selection.As an investment, if Pickit4 is relatively expensive, keep in mind it's replacing at least that many (two or three) separate dongles. Very easy to justify as a business decision, and not even that hard to justify if you're a hobbyist working with many platforms.Tim

author: westfw
author_rank: Super Contributor
timestamp: April 19, 2022, 02:07:03 am
content: QuoteHV programming is generally hard to find, largely because the 'general case' has a lot of different variations.I'd go with a SNAP for (everything except HV, including PIC, ARM, AVR, XMEGA), and something special-purpose for your ATtiny10s. (The tiny10 is very small, so "high speed programming" isn't needed. It's also relatively simple: "apply 12V to RESET instead of GND", whereas some other chips require switching the 12V during programming. There are several published designs for a HV Tiny10 programmer around.)QuoteAVR Studio doesn't support many of the other low-cost programmers, either, except through an "external application" like avrdude.

author: Doctorandus_P
author_rank: Super Contributor
timestamp: April 25, 2022, 08:37:30 pm
content: I approached it from another side.I've used USBasp for years, and am quite happy with that programmer.And then Atmel started inventing a new programming protocol every three years or so.I just ignored them all, and I only use the divices that can be programmed via the old protocol.This also circumvents some other problems. Atmel also kept on making both small and big changes to all sort of aspects of the included peripherals, and I have no interest in chasing all those changes though my self written libraries, so I just stick to the few devices that I know do work.If that means just using 4 I/O pins of a 28 pin device, or 2kB flash of 32kB, so what?Neither size nor shaving of a few dimes of the BOM is very important to me, but I'm not going to spend hours to fix software for small random hardware changes.Then I had some projects for which the good ol' AVR's were much too slow, and the Xmega's seemed to be the obvious way forward, so I started reading some datasheets.A bit later I realized they have not put in any effort to put in any kind of compatibility and I might as well look further to what else is in the world.I finally chose for Arm cortex, mostly STM32. The "Blue Pills" still had genuie STM32 back then, and programmers were cheap. It's also GCC compatible.Another thing I like a lot is the similarity of peripherals, not only between different microcontrollers, but also within the same device. There is for example an "advance motor timer" and a simple "system tick timer" but for the most part, you have a description of a timer and then a single line somewhere that says "there are 5 of this in this chip". With the AVR's this was quite horrible. Even if the chip has 4 timers, they could not bother to make two with the same functions and you keep on referring to datasheets which timer supports which function, which is only a waste of time.With those arm chips you're also liberated from those horrible fuse settings. the uC just starts up from a slow internal RC oscillator, and then you configure everything by setting some bits in I/O registers. Those fuses were a truly moronic descision.

author: T3sl4co1l
author_rank: Super Contributor
timestamp: April 26, 2022, 02:16:54 am
content: FWIW, they've fixed a bit of that -- XMEGA have little use for fuses in typical application, and AVR-Dx have repeat instances of timers, USARTs, etc. Plus event and custom logic systems you'd have only dreamed of, back in the day.OTOH, the XMEGA timers are kind of cut from the same old (piecemeal TC0/1/2) cloth. And AVR-Dx seem less well documented than usual, the timers are kind of weird doing a bit of this and that; the basic functions/applications are apparent, but some features -- and lack of others -- make me wonder what specific applications they might've been tweaked to do. Both have reasonably accurate VREF, ADC (12b), faster ADC at that (100kSps+), DAC available, accurate RC timers, etc. Most things that would've been fuses (and very limited accordingly), are now CCP (configuration change protection) so they can be changed at run-time but with a little song and dance that makes the registers not so likely to be randomly corrupted if the CPU starts reading garbage. Also they've come full circle, with AVR-Dx (and mega0, tiny2, etc., I think?) using UPDI, an async serial protocol with autodetect baud -- single wire debug can be done from any plain old serial port!But most of all, it's a learning process, they're all quite different in peripherals, structure, etc. Only the CPU core is the same, and at that, with minor modifications (e.g. XMEGA is generally a bit faster than classic, and adds a couple instructions).And I mean, you can't expect strong backwards compatibility on peripherals; the originals were just so limited. I suppose they could've added onto them rather than overhauling entirely (make new features optional, don't remove old features), but, maybe it's not much further of a step to just redo the thing. And, maybe it's not much more effort to learn a whole new platform instead. So yeh, whatever floats your boat and all.Tim

author: Doctorandus_P
author_rank: Super Contributor
timestamp: April 26, 2022, 10:18:18 pm
content: It's not worth much to me.Speed increase for the XMega's is too small to bother with.Compare that with STM32, where you can grow to 400+ MHz and several MB of flash.Microchip had some PIC's with programmable logic even before they bought Atmel, and the've probably also put that in the newer Xmega's too.But other manufacturers are also not sitting still.Some time ago I had a look at the STSpin.It's an STM32 with a built in SMPS (40V to 60V input I think) and with both built in MOSfet gate drivers and opamps for current sensing. It's almost a complete 3-phase motor controller in a single chip. Just add some external MOSfets and passives.But these days, I simply won't design in products like that, because you put yourself into a corner with parts you can't buy.I'd rather design in more "conventional" parts such as a separate SMPS and gate drivers and then at least have a chance that parts can be second sourced, or if needed, PCB modifications are relatively small if it has to be modified to accommodate available parts.These are not the times for fancy parts.In a more general sense, the complete IC market is bonkers. There really is no practical need to have more then 20 or so different parts in a whole microcontroller family, unless they have extremely specialized peripherals such as (accurate!) 24 bit ADC's built in. ST is for example well known for artificially inflating the number of chips. It's quite common that a uC that does not have an USB peripheral on paper, and you just compile in firmware then it "just works". It's just marketing.Why are there 10.000 different opamps?Why are there 100 variants of a 555?Why do both TL072 and TL082 exist?It's all artificial inflated nonsense created by marketing departments, and in the meantime the big sellers have to stock millions of "different" parts.Once I needed a 1k 1/4W THT resistor and I was not able to narrow it down to less than some 3000 choices. Complete madness.

author: T3sl4co1l
author_rank: Super Contributor
timestamp: April 27, 2022, 11:46:31 am
content: Exactly; there's not much difference between cores, so when you need compute/buck, you're looking somewhere else.IIRC most STMs have the building blocks for SMPS and motor control sorts of stuff already, maybe just not so obviously (or with such dedicated hardware control) as the SMPS oriented ones. Well, gate drivers you'll never see, granted; that's neat. Though I wonder if they're actually integrated, or just co-packed? ST's had some whopper multi-chips before, like uh powerSTEP01 comes to mind, that's got a lot of dies inside it. And that's probably not even very big/many overall, just happens to be one I've used before.There's some merit I suppose, to doing as many things as possible with as common an MCU (or selection of them) as possible. You'll still need to add glue like gate drivers, MOSFETs, whatever regulators, power / battery management, etc. they simply can't provide by themselves, and those will be common enough items that they should always be in fair supply (as long as your footprint/pinout options are kept open?). Thus avoiding the trap of special-purpose single-sourced chips, whether for interface/control, or MCUs themselves, etc.Comes to mind, there's a line of PICs with SMPS hardware included, that's basically the comparator, latch and driver of a UC3843, something like that. And if you didn't have one of those models, they (MCP) make (made?) a chip with all that, greatly simplifying your digital SMPS projects. It's a shame that such a building block, is quite useful for its purpose -- but almost useless in practice as, why stop there, just draw the rest of the fucking regulator* and boom, standalone product; or if you're going to add a chip anyway, like the gate driver to use an MCU for direct digital control, it's not much more bother to use gate drivers and figure out the comparator/latch yourself (in SW/HW, to varying degrees of success/reliability, as the case may be).Or the other thing is to ride on commercial products, whatever they're using. Like, there's no shortage of BMS parts...if you don't mind that they're all grain of sand CSPs for in-pack and on-board (e.g. cellphone and other tightly integrated stuff) use. And don't mind those supplies drying up from year to year as the big players shift around their sources...Tim*As per the meme:(which I can't prevent embedding here, argh)

author: JPortici
author_rank: Super Contributor
timestamp: April 27, 2022, 01:17:20 pm
content: They are usually multiple dies in a package. I really like them because they let you really shrink the board size (Just the chip, the mosfets and a bunch of decoupling to have a 3kW BLDC driver that can be mounted directly on the motor, using the motor housing as heatsink. Add a can/lin transceiver and there is your electronic fuel pump)same for all those RF SoCs

author: westfw
author_rank: Super Contributor
timestamp: April 27, 2022, 10:59:52 pm
content: (not to bring things back on topic, but...)A nice thing about a SNAP is that it will program ARM and PIC32 chips as well as PIC8/AVR...(I'm not sure about non-Microchip ARM chips, though.)

author: mikeselectricstuff
author_rank: Super Contributor
timestamp: April 27, 2022, 11:08:09 pm
content: Quote from: Ian.M on April 18, 2022, 07:18:11 pmAll the PicKit 3 clones I've bought have been fine - I use quite a few as I send them set up in programmer-to-go mode for assembly subcontractors

author: Ian.M
author_rank: Super Contributor
timestamp: April 27, 2022, 11:21:42 pm
content: Yep. Cutting corners on the PICkit 3 with its auto-updating firmware that MPLAB (X) installs when you change device families was a *LOT* harder to do as it was a moving target, so if a cloner's version of the circuit didn't closely follow the original design, there was a much higher risk of it failing either self test or in operation. This removed most of the opportunities for BOM cost savings except by sourcing cheaper directly equivalent devices, which meant that unlike the PICkit 2, there was no race to the bottom to produce 'Muntzed' clones, so PICkit 3 clones are generally a much lower risk buy.

author: seamusdemora
author_rank: Regular Contributor
timestamp: May 01, 2022, 10:03:15 am
content: Quote from: westfw on April 19, 2022, 02:07:03 amI have two questions:I'm staging my first run at a micro-controller project. I've bought a couple of PIC 'Curiosity' boards (PIC16F15244) as prototypes only b/c they appeared to be easy to work with. I would have also bought a PICkit 4 at the same time, but they're back-ordered until late Summer. As of now, my plan is to use the MPLabs IDE & plugins. I came here to learn if there are good alternatives to the un-obtainable PICkit 4 - and to further my education.The SNAP hardware you suggested seems a good alternative to the PICkit 4. But since the cost of the PICkit 4 is 2X the cost of the SNAP, I can't help but wonder if I'm giving up 'something' I might wish I had in the future. Is that 2X price tag for the PICkit 4 due primarily to the lack of HV programming?The 2nd question has to do with the basic functions of these units. I'm under the impression that both devices provide two functions: 'programming' and 'debugging' - correct? Are there other devices that provide only 'programming'? The Curiosity board I've bought includes a 'debug chip' (which baffles me), and so perhaps a 1-function 'programmer' will work just as well?Thanks for any insights,~S

author: westfw
author_rank: Super Contributor
timestamp: May 01, 2022, 09:37:27 pm
content: QuoteThere's a comparison here:https://microchipdeveloper.com/snap:versus-pk4Itlooks like the PICKit4 has fully programmable power supplies for both Vdd and Vpp, which lead to a bunch of related features (but I'm not sure what they're good for.)It's also traditional in the "debugger" product space that more expensive debuggers are faster, either by virtue of faster communications channels, faster internal CPUs, additional hardware support (FPGA/CPLD to handle JTAG, for instance), or just more careful coding. I haven't heard any speed comparisons between PK4 and SNAP, so I'm not sure. The "mEDBG" chip used on some of the "xplained mini" boards is "known to be rather slow compared to an external debugger." (the mEDBG is a 16MHz ATmega32u4 with firmware, and only has full speed USB.)QuoteSure. The famously cheap "USBASP" programmers are "programmer only." In the PIC world there was "PonyProg/SIProg." The various "load this sketch on your Arduino XXX to program YYY" solutions are usually "program only." Some of the "special purpose HV programmer" solutions I was suggesting are "return fuses to factory default" only. Some of the debugging protocols (eg AVR DebugWire) are proprietary and undocumented, so they're pretty tough for 3rd parties to implement.QuoteThe Curiosity board "debug chip" does both programming and debugging (I don't think I've ever seen a "debug only" adapter.) Supposedly you can turn off the "target CPU" of a curiously board and use the debug chip to program and debug off-board chips. Theoretically it is a very similar chip to what's inside of something like a SNAP, without most of the surrounding circuitry to do voltage translations and etc. (the rumor is that the "debug chip" on the Arduino Zero is exactly the same chip (and AVR32 of some kind) that's in an Atmel-ICE.)

author: seamusdemora
author_rank: Regular Contributor
timestamp: May 01, 2022, 11:35:35 pm
content: Quote from: westfw on May 01, 2022, 09:37:27 pmThat's all helpful - esp the comparison (I missed that!); thank you. Based on this, I'm going to save my $32 for the SNAP, and stick with the Curiosity board for the time being. The Curiosity's "fat DIP" construction allows me to plug into my breadboard for easier integration with less clutter. And at my current stage of "expertise", the additional gadgetry doesn't seem to add much.

author: westfw
author_rank: Super Contributor
timestamp: May 03, 2022, 12:18:08 am
content: IMO, the "Curiosity" boards are great values. I own quite a few of them. (and the Xplained Mini boards as well. Any vendor development board that is cheaper than an Arduino with the same CPU is probably a better value,for development.There's the problem that they're probably "less stable" than popular hobbyist boards, and you don't see the very-low-priced derivatives from China, but having a debugger that is "known to work" with the vendor tools is a big advantage. (now if only the "vendor tools" were better at "importing" things like Arduino sketches.)

author: seamusdemora
author_rank: Regular Contributor
timestamp: May 03, 2022, 12:38:09 am
content: Quote from: westfw on May 03, 2022, 12:18:08 amOh this is fun... I'm sure the IDE is a 'good thing' once you get used to it, but it's not what I was expecting. Based on my v. limited & long-ago experience, I had assumed the IDE would open up an editor in main.c, after which you're on your own. I've downloaded a project file from microchip's web/github site - it works - but there is virtually nothing in main.c. Everything seems to be auto-generated, and I can't even see how to change the frequency of the led flasher.lol.Is there a tutorial for dummies somewhere?Thnx,~S

author: westfw
author_rank: Super Contributor
timestamp: May 03, 2022, 08:07:59 am
content: QuoteYou can certainly do that, if you start with "new project" and proceed from there. You'll even have to create your own "main.c"...A lot of the code examples are going to use "Melody" and/or "Harmony" which are code generator and/or library management tools that supposedly reduce the need for learning all the little details. I haven't used them, and don't like the idea much, so I can't comment much.Don't be afraid to look at the generated code files. They should all be included in the project, and they're not awful.and oh yeah: pretty much ANY "real IDE" is going to take quite a bit of "getting used to." People that haven't had to lead a beginner through their initial use of a "professional IDE" generally miss the whole point of Arduino's painful simplicity...

author: seamusdemora
author_rank: Regular Contributor
timestamp: May 03, 2022, 09:34:16 am
content: Quote from: westfw on May 03, 2022, 08:07:59 amI've done some Arduino programming. I didn't care for it much, but it was easy enough to get your bearings & get things accomplished.Here - in MPLAB IDE - it's not easy to get your bearings. I've got perhaps the simplest example available loaded, and have got a conflagration of semi-GUI controls, and 220 lines of 'generated' code in timer.c that are presently undecipherable. There's got to be an easier way - I do not have a year to devote to this!Any suggestions are welcome" alt="" class="bbc_img" />" alt="" class="bbc_img" />

author: JPortici
author_rank: Super Contributor
timestamp: May 03, 2022, 12:14:14 pm
content: Quote from: westfw on May 03, 2022, 08:07:59 amthat is a myth just as "portability between ARM microcontrollers"in fact you need to learn all the little details of the code generator along with the little details of the part in use. They are fine for pin/clock assignment boilerplate code though.. (though there used to be standalone plugins for that)Quotesure isbut you need the datasheet at handthe simplest project i can think of for one of my goto target MCUs, PIC18F26K42.Code://First thing first, configuration bits. Note, these should be declared only once, in a *.c file.//DO NOT PUT IN AN HEADER FILE.//Also, put them at the beginning of the file, before including header file because they could//redeclare some of the magic words//Ah, there is a helper to generate this wall of code: Window->Target Memory Views->Configuration bits. Change the config and click on generate source code// CONFIG1L#pragma config FEXTOSC = OFF // External Oscillator Selection (Oscillator not enabled)#pragma config RSTOSC = HFINTOSC_1MHZ// Reset Oscillator Selection (HFINTOSC with HFFRQ = 4 MHz and CDIV = 4:1)// CONFIG1H#pragma config CLKOUTEN = OFF // Clock out Enable bit (CLKOUT function is disabled)#pragma config PR1WAY = ON // PRLOCKED One-Way Set Enable bit (PRLOCK bit can be cleared and set only once)#pragma config CSWEN = ON // Clock Switch Enable bit (Writing to NOSC and NDIV is allowed)#pragma config FCMEN = ON // Fail-Safe Clock Monitor Enable bit (Fail-Safe Clock Monitor enabled)// CONFIG2L#pragma config MCLRE = EXTMCLR // MCLR Enable bit (If LVP = 0, MCLR pin is MCLR; If LVP = 1, RE3 pin function is MCLR )#pragma config PWRTS = PWRT_OFF // Power-up timer selection bits (PWRT is disabled)#pragma config MVECEN = ON // Multi-vector enable bit (Multi-vector enabled, Vector table used for interrupts)#pragma config IVT1WAY = ON // IVTLOCK bit One-way set enable bit (IVTLOCK bit can be cleared and set only once)#pragma config LPBOREN = OFF // Low Power BOR Enable bit (ULPBOR disabled)#pragma config BOREN = SBORDIS // Brown-out Reset Enable bits (Brown-out Reset enabled , SBOREN bit is ignored)// CONFIG2H#pragma config BORV = VBOR_2P45 // Brown-out Reset Voltage Selection bits (Brown-out Reset Voltage (VBOR) set to 2.45V)#pragma config ZCD = OFF // ZCD Disable bit (ZCD disabled. ZCD can be enabled by setting the ZCDSEN bit of ZCDCON)#pragma config PPS1WAY = ON // PPSLOCK bit One-Way Set Enable bit (PPSLOCK bit can be cleared and set only once; PPS registers remain locked after one clear/set cycle)#pragma config STVREN = ON // Stack Full/Underflow Reset Enable bit (Stack full/underflow will cause Reset)#pragma config DEBUG = OFF // Debugger Enable bit (Background debugger disabled)#pragma config XINST = OFF // Extended Instruction Set Enable bit (Extended Instruction Set and Indexed Addressing Mode disabled)// CONFIG3L#pragma config WDTCPS = WDTCPS_31// WDT Period selection bits (Divider ratio 1:65536; software control of WDTPS)#pragma config WDTE = SWDTEN // WDT operating mode (WDT enabled/disabled by SWDTEN bit)// CONFIG3H#pragma config WDTCWS = WDTCWS_7// WDT Window Select bits (window always open (100%); software control; keyed access not required)#pragma config WDTCCS = LFINTOSC// WDT input clock selector (WDT reference clock is the 31.0 kHz LFINTOSC)// CONFIG4L#pragma config BBSIZE = BBSIZE_512// Boot Block Size selection bits (Boot Block size is 512 words)#pragma config BBEN = OFF // Boot Block enable bit (Boot block disabled)#pragma config SAFEN = OFF // Storage Area Flash enable bit (SAF disabled)#pragma config WRTAPP = OFF // Application Block write protection bit (Application Block not write protected)// CONFIG4H#pragma config WRTB = OFF // Configuration Register Write Protection bit (Configuration registers (300000-30000Bh) not write-protected)#pragma config WRTC = OFF // Boot Block Write Protection bit (Boot Block (000000-0007FFh) not write-protected)#pragma config WRTD = OFF // Data EEPROM Write Protection bit (Data EEPROM not write-protected)#pragma config WRTSAF = OFF // SAF Write protection bit (SAF not Write Protected)#pragma config LVP = ON // Low Voltage Programming Enable bit (Low voltage programming enabled. MCLR/VPP pin function is MCLR. MCLRE configuration bit is ignored)// CONFIG5L#pragma config CP = OFF // PFM and Data EEPROM Code Protection bit (PFM and Data EEPROM code protection disabled)// CONFIG5H//Define some constants//_XTAL_FREQ is used in XC8 by some builtins, like software delays.//It should be set to the device oscillator frequency (not FCY which is oscillator frequency divided by four)//In this example the oscillator is the FRC, set at 1MHz (4MHz, divide by four)//_XTAL_FREQ must be defined BEFORE including xc.h//But all of this is in the compiler manual anyway#define _XTAL_FREQ 1000000UL//xc.h, between other things, select the appropriate device include file.#include <xc.h>#include <stdint.h>#include <stdbool.h>volatile bool ra0state = false;volatile bool ra1state = false;//Interrupt routines. Note that this uses the vectored interrupt controller.//For the legacy interrupt modes declare as such.//But all of this is in the compiler manual anyway//void __interrupt(high_priority) highPriorityInterrupt(void)//void __interrupt(low_priority) lowPriorityInterrupt(void)void __interrupt(irq(TMR4),high_priority) TMR4Interrupt(void) {static int16_t cnt_500ms = 500;PIR7bits.TMR4IF = 0;//1ms has passedClrWdt(); //<- macro that calls the instruction to clear the watchdog timercnt_500ms--;if (cnt_500ms <= 0) {cnt_500ms = 500;//500ms has passedra0state = !ra0state;LATAbits.LATA0 = ra0state; //Or i could have just written "LATAbits.LATA0 ^= 1" or "LATA ^= 0x01"}}//Now in order for the program to know what to do when an unhandled interrupt is hitvoid __interrupt(irq(default),high_priority) DefaultInterrupt(void) {__debug_break(); //The debugger will halt here during a debug run, this is ignored in a production buildNop();Reset();}//Hardware initializationvoid ioInit(void) {TRISAbits.TRISA0 = 0; //RA0 outputTRISAbits.TRISA1 = 0; //RA1 output}void tmr4Init(void) {//1ms Time BaseT4CLK = 1; //Timer clock is FOSC/4 <- see the TMR2/4/6 chapter in the datasheetT4RST = 0; //External reset unused (well, it's assigned to an external pin which is not configured)T4HLT = 0; //Timer is in free running modeT4CON = 0;T4CONbits.CKPS = 1; //1:2 PrescalerTMR4 = 0;PR4 = _XTAL_FREQ/(4*2*1000UL)-1; //I don't like using magic numbers, and you shouldn't if possible. we want a period of 1ms//clock is _XTALFREQ/4 divided by the prescaler (1/2), and that is the number of counts for//a period of 1 second. we want a period of 1ms so we divide the "timer clock" by 1000.//Remove 1 because counting starts from zero, not from 1.T4CONbits.T4ON = 1; //Start the timerIPR7bits.TMR4IP = 1; //Interrupt with high priorityPIR7bits.TMR4IF = 0; //Clear Interrupt FlagPIE7bits.TMR4IE = 1; //Enable Interrupt}//Main function. This program should blink two LEDs, one using interrupts and one using software delaysvoid main(void) {ioInit();tmr4Init();//Enable Interrupts. RA0 will blink in interruptsINTCON0bits.IPEN = 1;INTCON0bits.GIEH = 1;INTCON0bits.GIEL = 1;while(true) {ra1state = !ra1State;LATAbits.LATA1 = ra1State;__delay_m5(500);}}everything hsould be self explanatory(maybe you wanted to use an AVR target? principle is the same, some of the syntax is different. the compiler manual is your friend, it's really well written - check the howtos)

author: T3sl4co1l
author_rank: Super Contributor
timestamp: May 03, 2022, 01:53:01 pm
content: Quote from: seamusdemora on May 03, 2022, 09:34:16 amLooks like, well, standard boilerplate to me -- it won't take you a year to piece together, but weeks to months depending on how experienced you already are with C, seems reasonable. About the time required to dive into anything new and different.Offhand: a lot of hardware abstraction libraries (HALs) do things like that: a handful of functions which set and get certain simplified actions related to the hardware; perhaps a state variable indicating success, ready, or other status (which may be returned in the function, or a global state that's accessed by another function, so you always want to check for success after making setup calls this way); and the interrupt, well the one in the screenshot anyway, seems to be a dummy LED toggle, and presumably there's a different one that calls into the callback function provided.The callback itself may be a bit unusual for the novice C programmer; you can go quite far using just direct function calls, library and OS calls, and making many useful programs that way. It's a somewhat more advanced item to pass around function pointers. And the syntax looks weird, particularly the declaration of a function type. But suffice it to say, the CallbackRegister accepts a pointer to a void(void) function, and assigns it to a variable, which I guess is called elsewhere (i.e.if (Timer1_OverflowCallback != NULL) Timer1_OverflowCallback();). "Register" in the sense, I think, of registering your custom function with the HAL, so it knows to call it.This allows runtime setup of function calls -- most embedded applications don't need this, it's fine to just write everything in the ISR (Interrupt Service Routine) and it's always there on interrupt and never changes (and never needs to) during execution. Well, to be perfectly general and flexible, they've added the option to change it at run-time. Which unfortunately costs quite a bit of overhead (usually, anyway), so there's good reason also not to do it this way, but if you aren't doing performance-critical operations, you may not notice.I don't know offhand how Arduino does it, but I'm guessing similar.Other things function pointers are good for: jump tables (indeed, sufficiently lengthy switch() statements are usually compiled to this); associating function calls/types with data structures / objects (e.g. a menu system with data pointers to navigate to other menus/items, and function pointers to implement their customized (but also sometimes repeated) actions); anything dynamically linked of course (the linking being handled by the OS on loading the .dll/.so file/routines, you just get named function calls from the DLL object); etc.Tim

author: seamusdemora
author_rank: Regular Contributor
timestamp: May 03, 2022, 10:36:51 pm
content: Quote from: JPortici on May 03, 2022, 12:14:14 pmI'll say that is a huge improvement over what I'm looking at in the MPLAB IDE. 149 lines of digestible code vs code generators run amok: 220+ lines in 'tmr1.c', which is only one of several "generated" files. My VisualStudio nightmares might come backLOLFWIW, I'm a EE by training and trade. I'm self-taught in C, and I know what a callback is. I supported myself writing encryption libraries (DLLs) for Windows in the late '90s. But I hated it - I wanted to design hardware, and after 3 years in C programming purgatory I found my way back to making a living with hardware.Anyway, I've convinced myself now that the best way to my current objective is via a uC. I believe I can get all of the functions I need in a single package, and I'm committed to running the software gauntlet. But that array of gobbledygook in the IDE window is just too much.And finally a question: Where can I find 'example projects' with code that's not too dissimilar from what you've posted here? I won't bother with the MPLAB-provided projects - I don't even know where to begin to adapt something that bloated to my project. I found a reference onPIC assembler programminglast night, and began reading that. Are there example projects around that illustrate Assembler?Thnx all~S

author: westfw
author_rank: Super Contributor
timestamp: May 03, 2022, 11:49:08 pm
content: QuoteLook for the examples on github, and the tutorials on youtube, that are labeled "bare metal." (there are only a couple for your particular board, but the others might still be useful for visualization.) (eg)Look for other examples. ThePIClist mailing listused to be an excellent resource for code snippets. Unfortunately for you, a lot of the stuff there pre-dates MPLABX, and mostly pre-dates the common use of C on PICs (say what you want about the free XC8 compiler - prior to that, most PIC C compilers were relatively expensive.) (also, be aware that Microchip recently changed their assembly language syntax (why???!!!), so some old ASM examples would need to be re-written as well.)Give up. Figure out approximately what the extra lines of code are doing for you, and then either delete or ignore them. I'm looking at pic16f15244-delay-led-blink.X, and it has not timer initialization. PROBABLY your 200+ lines of timer code are setting up a "System Tick" so that Arduino-style millis() and etc are available. Fine. You don't need to worry about that until your need the timer for something else, or the interrupts interfere with something. (a "SysTick" isn't just an Arduino thing. ARM Cortex added an extra timer JUST FOR THAT. And IIRC Predko's classicProgramming and Customizing the PIC Microcontrollerrecommends setting this up as well ("if you only sample your buttons every 10ms, you don't need to worry about debounce", etc.) (My edition is also pre-C and pre-MPLABX. I don't know whether it's been modernized in more recent editions.) Ditto for "clock initialization." "It sets the clock to use the external crystal. Great. I'll come back when I need to do something different!"Give up even more, and don't use the IDE. Figure out how to use the tools from the command line instead. I don't really recommend this, because the issues with paths and such have gotten more complex as more chips have been added to the lineup.

author: JPortici
author_rank: Super Contributor
timestamp: May 04, 2022, 02:58:26 pm
content: Quote from: seamusdemora on May 03, 2022, 10:36:51 pmI don't know! i wrote that on the fly. That's more or less how my code style has become over the years (my project from 5 years ago are a lot more complicated, less readable and with more of the "clever" shit that i loathe today.)I've picked up most of it from some guys at the microchip forum, or some app notes (some years ago i came across the dsPIC33EV CAN/LIN starter kit example code. Self contained, no libraries whatsoever. The guy's a hell of an engineer, too) and adopted some coding standards too, like MISRA.But anyway, i thinkg that once you really understand that example i wrote you are good to go.There is how to set the configuration bits and what not to do. Want to know what the config bits really mean? -> datasheet.There is how to access registersThere is how to set up IOsThere is how to set up a peripheral (compare against the datasheet, apply to any other peripheral)There is how to declare and write an ISRYou don't really need nothing more. And you can apply this basic principle to any other architecture (more or less)Oh, one great source of material is also any one of Lucio di Jasio books. Learning to fly for the PIC24 series is one of my favourites. It doesn't matter that it is for another architecture, but it's pleasant to read and i found it very effective in helping you understand the logic steps you need to do in order to take the problem, tink about a solution using peripherals, also in not trivial ways, without caring about the implementation, and only then code said solution. Once you nail down the abstract you can adapt the implementation to the specific peripherals/core you have

author: seamusdemora
author_rank: Regular Contributor
timestamp: May 05, 2022, 05:46:49 am
content: Quote from: westfw on May 03, 2022, 11:49:08 pmAll good suggestions! In fact, I feel I've found a very good example in.He codes in the "new" assembly (PIC AS) that Microchip has thrust on its users. This switch to PIC AS does seem a shame as there are some very good sources of instruction for PIC Assembly programming that have been -at least partly- laid to waste. Perhaps the video's best feature is that it is only about 9 months old as of now. Consequently, the MPLAB X IDE used in the video is identical to the current one (at least in all relevant aspects). My assembly code experience is almost nil, but I presently feel positive about this approach. There are several things I see that will require some effort to understand well enough to use, but I can actuallyseethose challenges - they aren't hidden behind the hedgerows of meaningless (to me the novice)"generated"code. For example: getting the "dual bank" registers fixed "in brain" will require some effort.I read something the other day (don't recall where) that suggested using C on the PIC hardware was roughly similar to"driving square pegs in round holes". I don't know if that's accurate, but it struck me as funnyAnd it seems to suggest that some feel that assembler is better-suited to PIC programming than C. At any rate, I'm going to take a run at this, and we'll see where it leads.Thnx again & always appreciate any feedback.~S

author: JPortici
author_rank: Super Contributor
timestamp: May 05, 2022, 07:29:48 am
content: Quote from: seamusdemora on May 05, 2022, 05:46:49 amContext (though i can't find the sources):mpasm was written in pascal, in a compiler that was probably not ported to 64bit. The sources themselves have quirks that make it non trivial to port to 64bit. Also a number of the old guys have left the company in the past couple of yearsThen, there is XC8 which has always used a different assembler, long before it was called XC8 (The hi tech c compiler)Then, there is also the atmel assembler to mantainSo in the end there are three assemblers: a legacy tool for legacy devices and in practice legacy projects, and two tools they have to mantain anyway because they are part of the actively mantained compiler.MPASM is in fact redundant so they decided to drop the legacy tool when everything moved to 64bit, and i dont' really blame them. I also don't care because i never used the assembler for assembly only programs. I like the comfyness of a compiler and write and linke single assembly modules if i really really really need to.Sucks for those who were used to MPASM but fear not, contrary to many companies you can actually download every version of their devtools that have been released with little efforthttps://www.microchip.com/en-us/tools-resources/archives/mplab-ecosystemFrom what i read there are quirks and missing features on PIC-AS, just because the compiler don't need them but i also read that the compiler team has been very responsive on bugs and adding new features/directives

author: westfw
author_rank: Super Contributor
timestamp: May 05, 2022, 08:53:12 am
content: QuoteMicrochip has been pretty aggressive recently about putting content on github and youtube, covering both PIC and AVR product lines, and both code-generator and "bare metal" applications, and some other stuff too. I've been impressed.Here's a mention of a "Curiosity Nano" tutorial that brought together a lot of stuff that I hadn't noticed before:Quote

author: seamusdemora
author_rank: Regular Contributor
timestamp: May 05, 2022, 08:53:32 am
content: Quote from: JPortici on May 05, 2022, 07:29:48 amI wasn't "used to it" - I am a total newbie on PIC & very little background in Assembly language. Only lamenting the fact that much of the scant documentation & tutorials on PIC-assembler is now a step closer to obsolescence. If I understand your stmt, Microchip had 2 choices: update the old, or create something new. Their money, their decision. Just sayin'

author: JPortici
author_rank: Super Contributor
timestamp: May 05, 2022, 09:35:19 am
content: Actually they didn't create anything new, PIC AS is what's used by XC8 to assemble the asm files generated by the compiler. Now that it's the only officially supported assembler it's being slowly extended at the request of those guys that require programming in assembly only. Their (microchip) decision was between mantaining two overlapping tools or concentrate on the one that is actually needed by them

author: seamusdemora
author_rank: Regular Contributor
timestamp: May 05, 2022, 10:18:29 am
content: Quote from: westfw on May 05, 2022, 08:53:12 amThe presentation was very impressive AFAIC. I'll be scouring the "Microchip University" site for more. Thanks so much for passing this on!But the Curiosity board's'best feature': The staggered headers mean no solderingThnx,~S

author: seamusdemora
author_rank: Regular Contributor
timestamp: May 07, 2022, 07:43:32 am
content: Quote from: seamusdemora on May 05, 2022, 10:18:29 amAn update:I'm still impressed with the video tutorialRapid Prototyping with the Curiosity Nano Platform, but was a bit disappointed when I eventually realized the actual coding demonstrated in the tutorial was for an AVR instead of a PICThe problem I have with all of the examples that Microchip has put on theirGitHub siteis that for me - so far -they have little learning value!!. What does one learn from studying reams of"generated"code? I assume all of these examples started with a blank page - a main.c and .h file?... and I'll guess the IDE generated that code based on something the user typed. So I'm left with the question, "how do I get started?"Thnx,~S