Member

38

221

Member

38

105

Member

11

31

Member

8

36

## Popular Content

Showing content with the highest reputation since 12/23/2018 in Posts

1. 3 points

2. 3 points

## Declarative programming with minizinc

I am doing some work with combinatorial optimizers. It is amazing what happens when you turn over one more rock and see what scurries out. There is a whole class of programming called declarative programming and I have worked with Haskel enough to be slightly familiar with the concepts. I just learned about flat zinc and an easier environment called MiniZinc which are completely declarative and can be used to solve optimization problems by describing the constraints a valid solution fits inside. So here is a quick example of a program to find the smallest area rectangle where the area is 10 times the circumference. var 1..1000: side1; var 1..1000: side2; var float: area; var float: circumference; constraint area = side1 * side2; constraint circumference = 2 * side1 + 2 * side2; constraint area = 10*circumference; solve minimize area; output ["side1 = \(side1)\nside2 = \(side2)\narea = \(area)\ncircumference = \(circumference)\n"]; and here is the output showing every iteration. side1 = 420 side2 = 21 area = 8820.0 circumference = 882.0 ---------- side1 = 220 side2 = 22 area = 4840.0 circumference = 484.0 ---------- side1 = 120 side2 = 24 area = 2880.0 circumference = 288.0 ---------- side1 = 100 side2 = 25 area = 2500.0 circumference = 250.0 ---------- side1 = 70 side2 = 28 area = 1960.0 circumference = 196.0 ---------- side1 = 60 side2 = 30 area = 1800.0 circumference = 180.0 ---------- side1 = 45 side2 = 36 area = 1620.0 circumference = 162.0 ---------- side1 = 40 side2 = 40 area = 1600.0 circumference = 160.0 ---------- ========== Finished in 82msec Obviously this is a trivial example but it turns out there is quite a bit of research and libraries in this field. For example the google OR-Tools which could be incorporated in your C code. If you need to optimize something and you can describe what the answer looks like (the constraints) then these tools are pretty good. Of course these problems are NP-Complete, so solutions can take some time. Good Luck.
3. 3 points

## Making Embedded Systems by Elecia White

https://amzn.to/2Vibb9c After posting the negative review on the other book here I realized that it is not much help unless you provide an alternative! A couple of years ago I stumbled upon this book by Elicia White. Ever since I have recommended it as a must read to every new member of my team, even if they had years of experience they always reported back that they learned something valuable from reading it. I stumbled upon this book looking for something on Design Patterns in Embedded Systems, and in terms of that this was not what I was looking for, there is barely a mention of design patterns in the book, but I was pleasantly surprised by what I did find. I like where the book starts of, explaining the value of Design and Architecture and why this is where you should start with your project. She moves on to basic I/O and Timers which I think goes together pretty well, but importantly she covers the important use cases and patterns quite nicely and points out all of the most common pitfalls people fall into. The next chapter, “Making the Flow of Activity” covers the main paradigms for Embedded Systems like superloop and event driven approaches and even covers table driven state machines and even interrupts, I particularly liked the section called “How NOT to use interrupts”. Next chapter “Doing more with less” was a pretty good introduction to the methods you have to learn to tell how much RAM and FLASH you are using, and she covers important concepts like not using malloc. The chapter on Math is sure to teach even experienced engineers a couple of new tricks and the last chapter on power consumption is practical and well done. Overall I felt like this was a great book for beginners and a pretty good recap even for experienced engineers who will no doubt also learn a couple of new tricks after going through this book.
4. 2 points

## SERCOM fun in Arduino

I am working on a project for my camping trailer. The trailer has a 200W solar panel charging a 100AH LiFe battery. This crazy amount of energy is used to run lights, a refrigerator and, more importantly, a laptop and telescope while I am in the field. There is the trailer stored in the yard. The grey metal on the front is a set of drawer slides holding the 200W 24v panel. The 24v works well for the MPPT's because I get charging voltage earlier in the morning. The 200W works well because I don't want to move the panels to track the sun while I am camping. Now I want a status panel for the entire trailer in my home office so I can see how prepared I am for camping at moments notice. When I bought the trailer I specified a custom electrical system. This system utilizes a lot of Victron Energy equipment because it works well and it has a serial port with a published specification. They even show off open source projects using their equipment. Here is the electrical box. It did get a bit tight. Each of the blue units is a device with serial data for monitoring. This box lives in the black equipment box on the trailer tongue. The serial port is called VE.Direct and it is a simple 1 second transmission of useful information at 19200 baud. Here is an example of a transmission recorded from the trailer. PID 0xA053 FW 146 SER# HQ1734RTXXT V 13500 I -180 VPV 39200 PPV 0 CS 5 MPPT 1 OR 0x00000000 ERR 0 LOAD ON IL 200 H19 2436 H20 21 H21 106 H22 27 H23 132 HSDS 117 Checksum \$ I decided that step 1 in my project is to collect the data from the 3 devices in the box and report them to a second human interface/radio link in the back of the trailer. Here is my plan: This indicates that I need an MCU that has 5 serial ports and is easily programmed for my Hobby. I have been doing quite a bit of Arduino work in Platform IO and that combination is pretty good so how about using one of the many SAMD21 based Arduino kits. The SAMD21 has 6 SERCOM's that can be used for this purpose. So the first step... How easy is it to use 5 of the SERCOM's to do what I want? Not too bad but there are a few gotcha's. The SAMD21 Arduino support has a file called variant.cpp that defines a big array of structures to cover the capabilities of each pin. This structure includes a "default configuration" setting such as SERCOM, Analog, Digital, Timer, etc... When you open the serial port (Serial.begin(19200)) the serial library puts the pins into the "default" behavior and not the SERCOM behavior. Therefore if you want to use multiple sercom's you must do a few steps. 1) Ensure your SERCOM is initialized with the correct I/O pins. Uart ve1(&sercom2, sc2_rx, sc2_tx, SERCOM_RX_PAD_3, UART_TX_PAD_2); Uart ve2(&sercom3, sc3_rx, sc3_tx, SERCOM_RX_PAD_1, UART_TX_PAD_0); Uart ve3(&sercom1, sc1_rx, sc1_tx, SERCOM_RX_PAD_3, UART_TX_PAD_2); Uart ve4(&sercom4, sc4_rx, sc4_tx, SERCOM_RX_PAD_1, UART_TX_PAD_0); The tricky bit here is mapping the Arduino PIN number, to the SAMD21 Port/PIN numbers so you can determine which portmux settings are applicable. This is helpfully documented in the variant file but it is tedious especially since I build a custom PCB and had to keep track of every abstraction layer to ensure I hooked it up correctly. 2) Start the UARTS. ve1.begin(19200); ve2.begin(19200); ve3.begin(19200); ve4.begin(19200); This step was VERY simple and straight forward. 3) Put the new pins in the correct mode. pinPeripheral(sc1_tx, PIO_SERCOM); pinPeripheral(sc1_rx, PIO_SERCOM); pinPeripheral(sc2_tx, PIO_SERCOM); pinPeripheral(sc2_rx, PIO_SERCOM); pinPeripheral(sc3_tx, PIO_SERCOM); pinPeripheral(sc3_rx, PIO_SERCOM); pinPeripheral(sc4_tx, PIO_SERCOM_ALT); pinPeripheral(sc4_rx, PIO_SERCOM_ALT); The begin() function put each of these pins in their DEFAULT mode according to the variant table. But most of these pins did not have PIO_SERCOM as their default mode. You must call pinPeripheral() after you call begin() OR change the variant table. Naturally, my initial code did not but things did not work. Since I am working on this project off and on for some time, I found the bug in my VE.Direct class! The constructor was issuing the begin() which does make sense but it breaks the UART configuration that was already up and running. Now my serial ports are all running, and I am playing recorded messages to the system so I can debug inside where it is not 40C. On to the next problem. Good Luck
5. 2 points

## Speak and Spell Repair

I just received a care package from my father with a pile of old "junk". In there was a Speak and Spell from around 1978, I don't know when mine was bought. I quickly checked the battery compartment (4 C-cells) fearing to find a pile of corrosion. I did, but it was the rusty sort. The battery contacts were rusted. I opened the unit, removed the contacts and dropped them in vinegar to dissolve the rust. The contacts completely fell apart. A quick Amazon order for Keystone 209's and I was back in business. The new clips seem to be slightly thicker or perhaps stiffer, as the batteries are more difficult to insert. BUT it works! While I was waiting for the 209's to arrive, I considered adding an 18650 battery and a USB battery charger. The old TMS5100 series electronics runs from -15v so there is an inverting boost regulator to drop the 6v down to the -15. I tested and this works OK from 5v which is the standard output from the variety of battery manager/chargers you can find. But in the end I did not want a second button to activate the USB battery and then the normal ON button to activate the device. In any case, my 5 year old son loves it, though he did ask "can we install more games".
6. 2 points

7. 2 points

## Interrup with Mcc - Uart

I think specifically we need to know what processor you are trying to use as this differs from device to device. The simplest and most generic answer would be to add the UART to your project and click on the checkbox to enable interrupts for the driver. After generating code you will have to set the callback which you want called when the interrupt occurs. After this you need to make sure you are enabling interrupts in your main code and it should work. If you supply us with the details above I will post some screenshots for you on how to do this. Just to show you the idea I picked the 16F18875 and added the EUSART as follows: You can see I clicked next to "Enable EUSART Interrupts" Then in my main I ensured the interrupts are enabled. When I now run the code the ISR created by MCC is executed every time a byte is received. The ISR function is called EUSART_Receive_ISR and it is located in the eusart.c file. You can edit this function or replace it by setting a different function as ISR by calling EUSART_SetRxInterruptHandler if you want to change the behavior.
8. 2 points

## How to abstract

I have seen lots of code that is tightly tied to specific hardware or to specific frameworks. This code is OK because it generally satisfies rule #1 (it must work) but as soon as the HW or framework changes this code becomes very difficult to adapt to the new system. Developers often state that they are abstracted from the hardware by the framework but this is generally never the case because the framework was provided by the hardware vendor. So what is a developer to do? Step #1 Ask the right question. Instead of asking HOW do I do a thing (how do I send bytes over the UART). The developer should ask WHAT do I need to do. Ideally the developer should answer this WHAT question at a pretty high level. WHAT do I need to do? I need to send a packet over RS485. Step #2 Define an API that satisfies the answers to the WHAT questions. If I must send a packet over RS485, then perhaps I need a SendPacket(myPacket) function. In the context of my application this function will be 100% clear to my partner developers. Step #3 Implement a trial of my new API that runs on my PC. This is sufficiently abstract that running my application on my development PC should be trivial. I can access a file, or the network, or the COM ports, or the STDIO and still satisfy the API. Get my partners to kick it around a bit. Repeat #1,#2 & #3 until the API is as clear as possible for THIS application. Step #4 Implement the new API on my HW or framework. This may seem like contributing to Lasagna code.... i.e. just another layer. But in fact this is the true definition of the hardware abstraction layer. ALL details of the HW (or framework) that are not required for THIS application are hidden away and no longer contribute to developer confusion. 100% of what is left is EXACTLY what your application needs. Now you have a chance at producing that mythical self documenting code. You will also find that unit testing the business logic can be more easily accomplished because you will MOCK all functions at this new API layer. Hardware NEVER has to be involved. Good Luck.
9. 2 points

10. 2 points

## How to use TMR1 on a PIC16F1

Remember, this timer counts up.and you get the interrupt when it rolls over. To interrupt at a precise interval, you must compute the number of "counts" required for that interval and then subtract from 65535 to determine the timer load value. void setTimer(unsigned int intervalCounts) { TMR1ON = 0; TMR1 = 65535 - intervalCounts; TMR1ON = 1; } By turning the timer off and then setting the counts and restoring the timer, you can be sure that you will not get unexpected behavior if the timer value is written in an unexpected order. I will cover this topic in the next blog post on timers.
11. 2 points

## Why is everybody still using the PIC16F877 ?

Plus you have colleges still making their students use C18... https://www.microchip.com/forums/m1083909.aspx
12. 2 points

13. 2 points

## PIC16f1x vs PIC18f

I think you will be pretty happy with the PIC16F1xxxx for that kind of project. The main advantage of the K42 would be the additional RAM and FLASH. I totally agree with @N9WXU there - when you are adding wifi and communication protocols that counts for a lot and you may end up constrained if you are trying to do it all on the smaller PIC16. If that is the next step you may find yourself porting the code right after writing it, which is never a good timeline. The K42 has up to 128KB of FLASH and 8KB of RAM while the PIC16 is capped at 56KB of FLASH and 4KB of RAM. Although it should be fairly straightforward to port the PIC16F18877 code to any K42 if it is written in C and if you use something like MCC to generate the hardware code for you. If you need help with that part please do give us a shout, we can definitely lend a hand with that part!
14. 2 points

## PIC16f1x vs PIC18f

Everything in your list of requirements looked pretty reasonable for the PIC16 until you said wireless. For wireless, a lot depends upon the details. Bluetooth, WiFi, Subgig, LoRa, etc will all require some kind of RF module. Each RF module generally comes with a co-processor that handles the heavy lifting for the wireless protocol, however... Each wireless module will still have demands upon the host processor. For example, the WINC1500 wifi driver on an ATMEGA4808 took around 10k. After reviewing the driver, it would be possible to shrink the code quite a lot but it would be at the expense of supporting the code for the duration. That is not to suggest that wirelesss is not appropriate for a PIC16, it is just that wireless often comes with additional expectations that are not immediately apparent. Here are a few: 1) Security, most wireless applications require a secure and authenticated connection to the host. 2) phone interface, many wireless applications seem to be tied to iOS and Android. This generally implies BLE4.2 but could mean wifi. 3) IoT. Obviously wireless existed before the internet, most of the wireless customer discussions ended up being Internet of Things discussions. This drove the security requirements. 4) Over the air update. because security and wireless standards are moving fast, most customers end up requiring the ability to update the software to adapt with the times. When you start going through these requirements you can quickly find yourself in a 128k MCU and that will be a PIC18 or AVR in 8-bit land. A reasonable rule of thumb with these kinds of applications is the PIC16/18 will require 2x the FLASH as an AVR for the same application. The details on why this is true would be a future technical post.
15. 2 points

## PIC16f1x vs PIC18f

Hi Keith, Welcome to our forum! We aim to please 🙂 Short answer is that I think the pic16F18877 is an excellent choice to replace the 16F887. It can pretty much do everything the 887 can do better since it can go 50% faster, and has a lot more to offer like CLC’s, PPS on the pins and a host of other features. Perhaps you can give us a little more detail on what you are aiming to do and how. Will you be using XC8 and using C for this and what are you looking for in terms of analog? There are also a lot of interesting goto parts in the PIC18 family, in particular look at the 18FxxK42, it has interesting additional features like DMA and vectored interrupts which are not on the PIC16F1 parts. They also have more flash and RAM if that is what you need.
16. 2 points

## Microchip XPress Evaluation boards

Even better. The USB programming interface code is all on GitHub HERE-> https://github.com/MicrochipTech/XPRESS-Loader
17. 1 point

## Forum etiquette - a question

PICKitPlus Many of you will have used or may be using Microchip’s PICkit2 and PICkit3 in-Circuit Debugger/Programmers. Our PICkitPlus software is a total replacement for the original PICkit 2 and PICkit 3 software. It has many new capabilities designed to facilitate programming of 8-bit PIC microcontrollers using a genuine or clone programmer.. Our software provides support for the newer 8-bit microcontrollers, and, we maintain support for old chips and new chips. The PICkit2 programmer was released back in 2005, and allowed the user to program and debug most of the 8 and 16 bit PIC microcontrollers and dsPIC controllers as well. Its successor, the PICkit3 programmer, was released some years later. In 2009 and 2012, Microchip stopped providing support for the PICkit 2 and PICkit3 software , respectively. They released the source code for the Windows GUI software, making it possible for users to update and maintain it themselves. This resulted in the launch of the PICkitPlus software in 2018 by the PICkitPlus team. We are now in 2021 a Microchip Development Partner - which is good recognition of our work. We provide PICkitPlus software for Windows, Linux and PIs. For all operating systems we have command line utility, and for Windows we have PICKitPlus GUI for the PICkit 2 and PICkit 3, PKEasy, PKAutowatch and PICkitPlus Gang Programmer. Supporting nearly 1000 PIC MCUs, includes PIC10F, PIC12F, PIC16F, PIC18F, PIC24, PIC32, dsPIC30 and dsPIC33 family Manages Microchip HEF and SAF memory Retains support for programming CAN I/O Expander & KEELOQ series: MCP2502X/5X & HCSxx Retains read and write operation for serial EEPROM 11LCxx, 24LCxx, 25LCxx and 93LCxx Supported operating systems (32bit/64bit): Windows XP ,Windows Vista, Windows 7, Windows 8, Windows 10, Linux and Pi New programming protocols support for new classes of 8-bit Microchip PIC microcontrollers Updated and managed database for Microchip PIC microcontrollers Improved user interface, help, guidance and direct access to the 8-bit Microchip PIC microcontroller database. Supports TURBO mode to decrease time to program and verify ---- If you have the original Microchip software you can use our improved database - this will give you new legacy parts and you can get the corrections for the existing legacy parts. If you new support for the newer Microchip PICs - you will need PICKitPlus. We have new capabilities that just do not exist in the old Microchip software. ---- To see all our software and hardware. See www.pickitplus.co.uk. If you are interested - ping me a message I we can provide a microforum discount for a few months! Cheers, Evan
18. 1 point

## Help!!! by any one here!

This is a user help forum for all topics on engineering and embedded software development. Feel free to browse the articles, ask questions and enjoy the fellowship of fellow embedded engineers. Welcome to the group.
19. 1 point

## MCC keeps setting my outputs to "Analog", why?

Setting ANSEL just disables the digital input. So with ANSEL set to 1, you'll get back 0 regardless which voltage is applied. If you want to make analog measurements, it's a good idea to disable the digital input. Otherwise it'll begin to toggle between 0 and 1 all the time if the voltage is in the forbidden zone (between low and high level). Back when PICs didn't have a dedicated LAT (latch) register, leaving the ANSEL at 1 had a serious side effect: This is from an old PIC16F887. If ANSEL was left at 1, PORT would be always zero. You could still set the output stage to 1 or 0, but you would always read back 0. This leads to a RMW (read-modify-write) problem. To change a particular pin, you had to read out the PORT register for an entire bank, modify the bit for your pin and write it back. If a pin has ANSEL set, it'll return 0, although the output is actually 1. With the write back operation, this pin will be set to 0. So you want to set RA3 to 1, but RA5 (with ANSEL set) gets cleared mysteriously at the same time.. This lead to day-filling debugging sessions and lot of grey hair, so many people still yell "Set ANSEL to zero!!" if you use it as a digital output pin. For modern PICs, this isn't a problem anymore: These devices have a latch register, where you set the logic state for the output buffer. The digital read back is separated, its still available in PORT. If you leave ANSEL set to 1, it'll only affect the PORT register now, LAT is independent from the actual voltage at the pin. Long story short: For modern PICs, you can leave ANSEL set to 1 for digital outputs.
20. 1 point

## SERCOM fun in Arduino

Hi...when we first checked out the ATSAMD21 chip, we were very happy to see that the chip has 6 "SERCOM"s, a.k.a SERial COMmunication modules. Each one of these modules can be used for I2C, SPI or Serial. That means you can have 3 UART's & 3 SPI's, or maybe 2 SPI's and 4 I2C's. Basically, you have a ton of options for adding more hardware support for the most common 3 chip-to-chip protocols.
21. 1 point

## Smart Air Compressor Power

A few weeks ago, I installed shop air in my garage. I was pretty proud when it held 150psi all night. But of course I did not quite tighten a connection and at 2 AM (or so my daughter tells me) there was a loud bang followed by a steady "compressor" noise. I did not notice until the next morning when I wondered why there was a noise from the garage. That compressor was pretty hot for running 6 hours straight. Of course this could be stopped by turning the compressor off each night. But, I write embedded software for a living and lately I have been deep into IoT projects. Naturally, this was an ideal chance to do something about my dumb compressor. Ingredients First, I needed a way to switch the compressor on-off remotely. These Sonoff switches are almost perfect. On the plus side, they have an ESP8266 inside so I can run TASOMOTA which is a generic Home Automation / IoT firmware for all things 8266. On the down side, they only are good for 10A. So I added a 120VAC 2 pole relay good for 30A. The compressor has a 16.6A motor draw so some overkill seems appropriate. I refreshed the Sonoff Basic with Tasmota and installed everything inside a metal electrical box. And when I visited the web page: I can turn the compressor on/off from my phone. Fantastic! As long as I had everything opened up, I went ahead and added 2 pressure sensors. Left and right of the primary pressure regulator. The left side sensor goes to the compressor and lets me know what it is doing. I am now tempted to remove the mechanical hysteretic controller on the compressor and simply use the Sonoff switch and some electronic pressure sensing to do the same thing. We shall see. Everything is now in place to ensure the compressor can be automatically turned off, or have a maximum run limit. The only thing left is software! Good Luck.
22. 1 point

## I2C problem locking up / stuck on Curiosity PIC32MZEF development board

Some advice for Microchip: If this was my product I would stop selling development kits with A1 or A3 silicon to customers. I2C is widely used and it will create a really bad impression of the product's reliability if customers were to evaluate it with defective silicon. And please fix the Errata, your workaround for I2C Issue 1 does not work as advertized !
23. 1 point

## MPLAB Harmony Configuration Settings for UART Higher Baud rates - PIC32MX470512L

According to your zip package, PBCLK is set to 48 MHz, not 96MHz? And it's a PIC32MX470F512L, just for clarity 🙂 It would be a good idea to debug your project and have a look at the actual register settings, to see if Harmony did everything right. I would also suggest to check the analog output signal with a scope to check the frequency and the signal quality. Is there a signal at higher baud rates and how does it look like?
24. 1 point

## Simulator, UART with DMA, PIC32, MPLAB X IDE

Of course, the simulator may be fine. It may just be Harmony that's not implementing USART via DMA correctly...
25. 1 point

## Issues with inline after switching to XC32 v2.15 - "multiple definition of"

Of course the answer here is that the semantics for inline in C89 do not exist (there is no such thing as inline), in GNU89 you can define a C function in a C file and place inline on it as a hint for the optimizer, BUT in C99 and C11 this is illegal, in C99 and C11 the standard specifies that the only legal way to use inline is to have the function body in the header file ... Read this for some background: https://gustedt.wordpress.com/2010/11/29/myth-and-reality-about-inline-in-c99/ This is the relevant part "So you’d have to put the implementation of such candidate functions in header files." EDIT: To be super pedantic about it, the standard does not exactly say you must place the definition in the header file, but if you want to use the function from more than one C file you will have to do exactly that for it to work.
26. 1 point

## Issues with inline after switching to XC32 v2.15 - "multiple definition of"

It seems that in 2.15 they changed how the command line options are interpreted. in 2.10, there was a -fgnu89-inline option that ensured the inlines operated in a particular way (the GNU89 way). In 2.15 it seems this option is being quietly ignored. You can test by removing the option from the command line when you build in 2.10 and then you should see the same error.
27. 1 point

## Wrapper for printf to filter string

printf will bind to stdio by simply calling putchar repeatedly. If your user will supply the data there is no risk if you run the code in Trustzone as they will not be able to access any data maliciously without causing a hardware fault. So this means your only remaining problem is ensuring that the user does not print backspace characters or \r\n characters, so you can simply remove/ignore backspace and replace every \r\n with "\r\nSECURE:" and you should be good? This can all be done quite safely inside of the implementation of putchar, and you can run that inside of Trustzone (which I have not used myself so I do not know the details of the limitations)
28. 1 point

## Problems with MPLAB Xpress PIC18F47K40 Evaluation Board

If you have purchased a "MPLAB(R) Xpress PIC18F47K40 Evaluation Board" from Microchip (part number DM182027) and you are running into difficulty because the board is behaving strangely it is most likely caused by a silicon errata on this device! The errata can be downloaded here: http://ww1.microchip.com/downloads/en/DeviceDoc/PIC18F27-47K40-Silicon-Errata-and-Data-Sheet-Clarification-80000713E.pdf The relevant section of the Errata is shown at the end. What is happening is that the compiler is using a TBLRD instruction somewhere and this instruction is not behaving as expected due to a silicon bug in REV A2 of the PIC18F47K40, causing the read to fail and the program to malfunction. Typically this happens as part of the C initialization code generated by the XC8 compiler, and since the compiler is optimizing, changing the code may cause the problem to temporarily disappear because you have few enough global variables that a table read is no longer the fastest way to initialize the memory segment for variables with static linkage. The XC8 compiler can avoid generating the sequence which will cause the failure if you tell it in the linker settings to implement the workaround for this Errata. This is done by adding +NVMREG to the setting as follows. Note that this is under the section "XC8 Linker" and the Option Category "Additional Options". This is the relevant section of the Errata.
29. 1 point

## RTCOUNTER example - (solved) Caused by Silicon Errata

Hi KM1/Orunmila, adding "NVMREG" even I am able to see the proper result on hardware.
30. 1 point

## Welcome!

Awesome, the forum will give you more permission to post files and images after you have made at least 3 posts.
31. 1 point

## RTCOUNTER example - (solved) Caused by Silicon Errata

I narrow down the issue. The controller is restarting due to "Stack Overflow". line number 220 code is causing the issue, reschedule = timer->callbackPtr(timer->payload); It looks like its a recursive which causing the issue but, I was not able to understand the part of the code how it works in a given time. We tried by adding "NULL" pointer check to that line that worked but, I feel like as an application or function of API it may not but, it just saves from restarting the controller. if(timer->callbackPtr != NULL) reschedule = timer->callbackPtr(timer->payload); I have attached the snapshot of the StackOverflow Flag setting. BTW. looks like its a simulator bug on showing nMLCR bit has low every time. I tested the voltage on the nMLCR it's not low nor dropping while executing the program.
32. 1 point

## RTCOUNTER example - (solved) Caused by Silicon Errata

Hi KM1, If we load RTCOUNTER is loads the "Timer0 without interrupt" but, i see that the interrupt is enabled in the code. Could you please give some details on why Interrupt is enabled. Also, I see EUSART and SPI-MASTER code in it if you share some details on this then it may be helpful.
33. 1 point

## Pretty output from your serial port

Back in the good old days™, real programmers used a modem to dial into BBS's and share programs. A little while later, we used our modems to dial into the University VAX or Unix machines to do our programming assignments. In those days, we interacted with the servers via text terminals and sometimes with graphics terminals over the serial connections (before we had ethernet in the dorm rooms). The interactivity included cursor movements, windowed screen scrolling and even COLOR!!!. I am here to tell you that these wonders are still available today through the magic of the terminal emulation modes built into most every serial terminal program. (that is why they are called terminal emulators). So here is a crash course in using this information. First: the raw data can be had here: https://en.wikipedia.org/wiki/ANSI_escape_code There are a number of terminal emulations but the most common ones were VT100 and ANSI. These were related so most codes do work. Here is how to use them in your program: First let us setup some constants 1 2 3 4 5 6 7 8 9 10 // A selection of ANSI Control Codes #define RESET "\33[0m" #define CLS "\33[2J" #define HOME "\33[1;1H" #define RED "\33[31m" #define GREEN "\33[32m" #define BLUE "\33[34m" #define WHITE "\33[37m" #define INVERSE "\33[7m" #define NORMAL "\33[27m" Next let us use them with some print commands. 1 printf(RESET GREEN "Hello" BLUE "_" RED "World" CSI_RESET "%d\n",5); Notice, that C will automatically concatenate strings when you place them all next to each other. This will issue a RESET to the terminal to ensure all other formatting like double high, flashing or inverse text are all removed. Then It sets the text color to green, prints Hello, sets it to blue and prints the _ finally red for the World, clears the formatting and prints the integer 5. That should be enough of an example for you to go wild. Each control code is about 4-5 bytes long so it does not add much to your program but it sure does make error messages stand out. Good Luck
34. 1 point

## Why is everybody still using the PIC16F877 ?

In the ivory tower of the university price is not that important. If you build less than 10 devices even a difference of 5\$/€ for each would not be worth to waste 1h of work 😉 For he student board I linked above which is sold a few hundred times it is a little bit more important to keep the price for all the components in the range of 10€ to make it attractive for them to get and build their own. (let them handle and solder the different sized components is one additional intention) A 18F2xK22 is is for sure not the cheapest uC you can get, but in 2013 it was one of the most feature rich in the 8-Bit PIC range that is relative easy to understand with all of its peripherals for beginners in mikrocontroller programming. Of course the presence of lots of tools like PICkit3 and knowledge of the MPLAB IDE and PIC18 at the side of the tutors in the labs was influencing the choice. 😉 I think the tools are very important especially if you do it not solely work with them or if you want to use them for teaching. At the moment there is another subject where Python will be used as a fist programming language for our students. A small part of this subject should be about embedded programming too. So we play around with circuitPython and microPhyton to see if it is easy enough to get an insight in just two or three lessons. Therefore we bought some tiny boards with SAMD21 and ESP32 controllers. Maybe some day we will build our own circuit/micropython board as we did with the PIC one but for the beginning it es more easy to use such controllers with huge libraries already available for them.
35. 1 point

## Microforum Recommended Book Reading List for Embedded Software Engineers

I have found the textbook “introduction to algorithms” by Thomas Cormen et al to be very helpful.
36. 1 point

## Mixing C and ASM

One strength of 8 bit devices is the precise timing. Unlike 32 bit machines, you simply don't have to deal with such things like - a bus matrix - long pipelines - clock domain crossing - caching A colleague of mine calls 8 bit devices "honest souls". You can calculate the exact behavior by simply counting instruction cycles. I had three situations where I needed to mix ASM and C. I recommend to use an encapsulated ASM module, inline ASM gets messy quickly. - for a motor to have exact commutation times after a BEMF event - for a capacity measurement with an AD input - to sample two AD channels and do a MAC operation for an enery meter All three solutions needed fastest execution and exact timing, independent from the compiler. This also had the advantage that I had to do testing of these routines only once. For example I didn't have to check for things like motor efficiency under load every time I released an update. There is a pitfall if you use ASM functions in interrupts. Because the compiler loses track of which registers to backup, XC8 simply copies all registers. But there was a way to skip automatic context saving. I'll have to look that up tomorrow. Oh and did they fix the clumsy switch case implementation in XC8 finally? I noticed that they use an XOR sequence to branch to the cases. That means the higher the case number, the higher the latency to execute the code in the case. Another reason for ASM.
37. 1 point

## Hello

Hi! I just signed up, reading your stories is great :) Let's if I can contribute a few more tales.
38. 1 point

## UART Baudrate Error Budget

Ok I think I get it now. We can separate the quality of the link from the basic budget. We know on a perfect link the slew rate is instant. I will do a 10% bit time slew rate for the table calculation as that is typically what I like to have. Sorry I was too lazy to do the 8x, but it is somewhere inbetween. Over Sampling Samples from Start to centre of stop bit Budget without Sampling Uncertainty As % Sampling Uncertainty Error Budget with Sampling Uncertainty Clock Error Budget Ideal slew Clock Error Budget 10% bit slew 4x 38 +-2 sample periods 5.26% 1 period +-1 sample period +-1.32% +-0.52% 16x 152 +-8 sample periods 5.26% 1 period +-7 sample periods +-2.3% +-2.03% From the PIC16F18875 datasheet the clock accuracy is +-2%, which means that from 0 to 60C between 2.3V to 5.5V you can use the internal oscillator for 2 devices to communicate realiably only if both devices are oversampling at 16x, if you want to use 4x over sampling you will not get reliable communication as the clocks cannot remain within +-0.52%.
39. 1 point

## Fast C parity calculations on PIC16F

Sadly, free mode is embarrassing and pro mode is expensive. It has been for a long time.
40. 1 point

## Fast C parity calculations on PIC16F

That was what I did first, and was horrified by the code generated by XC8 2.0 in free mode. That was my attempt to force it to do it efficiently. XC8 v.1.34 in Pro mode only has one pointless instruction: 309 ;main.c: 41: return WREG; 310 07FE 0809 movf 9,w ;volatile 311 07FF 0008 return Std and Free mode have an extra pointless instruction: 320 07FD 0020 movlb 0 ; select bank0 321 07FE 0809 movf 9,w ;volatile 322 07FF 0008 return and XC8 2.0 in C90 Free mode (Opt 0) is a bit ordinary: 1218 07D4 ;main.c: 41: return WREG; 1219 movlb 0 ; select bank0 1220 07D4 0020 movf (9),w ;volatile 1221 07D5 0809 goto l9 1222 07D6 2FD7 1223 l594: 1224 07D7 line 42 1225 1226 l9: 1227 07D7 return C90 Free / Opt 1 is same as v1.x in free mode 541 ;main.c: 41: return WREG; 542 07D9 0020 movlb 0 ; select bank0 543 07DA 0809 movf 9,w ;volatile 544 07DB 0008 return C99 mode generated the same code. (And that macro generates horrible code if you are not in Pro mode...)
41. 1 point

## Sprintf acting strangely

See http://www.elm-chan.org/fsw/strf/xprintf.html for one possible embedded implementation. I've seen others out there...
42. 1 point

## Software Estimation: Demystifying the Black Art (Developer Best Practices) - by Steve McConnell

So while I am in a book reviewing mood. This book by Steve McConnell (of Code Complete Fame) I now keep on my desk. It is a reference on all the important topics in software project management. The book is expertly laid out so you can read it in the order which you need for your situation. If you are on a project and you need help there are instructions in the introduction on which order to read, if you are a top-down kind of person there is an order and if you are a bottom up kind of person yet another order. I was giving a class on the topic and made a list of all the important topics to cover, when I got this book I found that it covered them all and then some. This is hands down the best project management book I have read. I really liked the discussion on the difference between a Target Date and a Deadline and also the Cone of Uncertainty in general. Whether you are using Agile methods or more traditional sequential methods to run your projects, this book will help you either way. Perhaps my favorite part of the book is an excercise on estimation where he asks readers to estimate things like the temperature of the surface of the sun, you can make a range as wide as you need to - but you have to make the range wide enough to have 90% confidence that the correct answer is within your range - most people fail miserably at doing this! Check it out here : https://amzn.to/2SszcbR
43. 1 point

## I need help with I2C on a PIC16F1 device

Your pro-tip for the day. If you use this code from MCC on a PICmicrocontroller, the function i2c_ISR must be duplicated due to the way the C stack is implemented on a PICmcu. If you want to save code space, simply decide how you want your code to run (interrupt or polled) and remove the call to i2c_isr from the master interrupt code or remove the test in master_operation. Either one will remove the duplication because the function i2c_ISR will not exist in both contexts. (interrupt and "main")
44. 1 point

## Three Phase PWM

Pretty cool stuff! Around 2004 I rewound a single phase 3/4 HP 120 VAC 4 pole induction motor, to make a 7 VAC, 12 pole,three phase motor. I used a 220V 3 HP VFD and two step-down transformers to run it at 240 Hz which was about 1800 RPM. My idea was to run a three phase motor directly on a 12 VDC battery, or perhaps a 48V battery pack clocked at 4x frequency to get 4x power. I also made a very rough VFD using a PIC16F684, with modified sine (rectangular) waves, and it did run, but after a bit the driver transistors blew out. I know a lot more now about how to properly choose and drive MOSFETs, and that's what I plan to do with this project. I added functionality to my spreadsheet that adds a percentage of 3rd harmonic to the synthesized waveform, and I can reproduce the increased output voltage in that way. This is 15% harmonic. I updated my file: http://enginuitysystems.com/pix/electronics/Three_Phase_Sine_Waves.ods
45. 1 point

## Why is everybody still using the PIC16F877 ?

That would require some information about where this test memory is, and how the second trap instruction works to "leak".
46. 1 point

## Sprintf acting strangely

A lot of people use printf and sprintf quite a lot without thinking how it actually works. The problem here is that the format string is interpreted at runtime, but the parameters are passed in with specific data types. If you look deeper into the specification for these functions you will find that the relationships between the data types in your format string (e.g. %d) to the parameters you are passing through after the format string is purely by agreement and the compiler cannot convert the variables to the correct type automatically at compile time. The conversion rules for printf (and sprintf) say that every parameter passed into the function in the variable argument list (that is after the comma) shall be subjected to integer promotion, which means that it will be increased in size at least to an "int". The size of an int would be different depending on the architecture or device, but it will always be at least 16-bits (as the C standard requires the int type to be at least 16-bits - even if the processor is only 8-bits) After this the parameters are packed next to each other in memory as a raw data block, and the printf code will unpack it again assuming that you followed the agreement of passing the correct data types. What happened in the code in the question above is that the constant used to multiply with was a 32-bit value, which means that we passed 3x 32 bit values into printf. So the raw data block looked like this: 32-bit 32-bit 32-bit 0x00000032 0x00000046 0x00000050 But the sprintf function is expecting 3 x integers which are on this platform 16-bits in size, which means that it is interpreting the data as we specified which is 3x 16bit integers: 16-bit 16-bit 16-bit 0x0032 0x0000 0x0046 Of course the next integers would be 0x0000 followed by 0x0050 and then the last 0x0000. The order of these are such because of the order the bytes are stored within the number (little endian, which means the lowest byte has the lowest address). If we used %ld instead the printf function would have interpreted the data correctly of course, so always make sure you use the correct format specifiers which match your parameters exactly, the compiler is not going to check this for you - it is your responsibility! When you are on a 32-bit processor where an int is actually 32-bits it is very easy to get this right by accident as everything ends up being converted to a 32-bit parameter, but you should still take care. Sometimes we use larger data types and often our code needs to be ported to other devices and this can easily become a hard bug to track down if you are not aware of these mechanics.
47. 1 point

## Why is everybody still using the PIC16F877 ?

If you use the __builtin_software_breakpoint() compiler built-in function and look at the list file generated by the compiler you will see that it translates the instruction (0x003) as "trap" - this instruction is not documented in the device instruction set or datasheet, but it easy enough to discover by looking at the lst file. 1211 1212 ;main.c: 17: __builtin_software_breakpoint(); 1213 07F1 0003 trap 1214 1215 ;main.c: 18: __nop(); 1216 07F2 0000 nop 1217 ...
48. 1 point

## Why is everybody still using the PIC16F877 ?

I think the main driver here is the sheer volume of old projects available online or floating around in schools. New users don't understand the devices well enough to adapt the code from the old version to run in the new devices, even though the new devices are so much easier to work with. It's going to take time for all this example code to evolve from "original mid-range" to "enhanced mid-range". Some of my favourite features of the new PIC16F devices are: Internal oscillator. No need to debug a crystal circuit just to get some instant gratification. LATx registers. No need to work around RMW problems. Three hardware breakpoints. Don't lose "step over" etc. functionality after setting one breakpoint. Linear memory. Arrays larger than 80 bytes are now easy. Dual FSR pointers, able to access RAM and ROM, with automatic 16 bit pre/post increment/decrement. Hardware context save/restore for interrupt code. Simple single instruction RAM banking. Ability to access WREG the same as any other SFR.
49. 1 point

## Welcome!

Looking good so far! 🙂
50. 1 point

## MCC keeps setting my outputs to "Analog", why?

Ok, so every time I set up a pin as an output MCC insists on making it "Analog". It looks like this setting has something to do with the ANSEL register, but surely an output is not Analog so why do they do this?

Want to keep up to date with all our latest news and information?