Tag Archives: ARDUINO

328P PORT MANIPULATION

#122 ATMEGA 328P Port Manipulation

Port manipulation was not important to me when I started working with microcontrollers, in fact I didn’t even know it existed and never felt the need for it especially after programming mostly in java script and PHP using functions like digitalread(pin); or digitalwrite(pin); etc. was second nature and speed or efficiency considerations were not really necessary or thought about that much.

Then after intermittently playing around with embedded ICs I got serious during the corruption virus of 2019 during lockdowns and other dilemmas while a lot of corrupt and diabolical cronies enriched themselves. I had a lot of time to focus on a few different things. There was no way I was going to let the circumstances get to me I made sure I was achieving at least one big goal each year and not get bogged down.

I took a look at the IC market and even though there was a chip shortage there were some IC’s available. This mad me try and get into efficient code and cost per IC. I came to the conclusion that I could get hold of IC’s with low memory + flash and very affordable prices. However in order to use them I would have to learn to use port manipulation, macros and interrupts in very efficient ways to the best of my ability at the time.

Now I needed to find new and comprehensive writeups of the principal and so I found the SpenceKonde
megaTinyCore
for the new at the time tinyAVR 0/1/2-series IC’s. The core has a lot explained over the years and was very helpful and easy enough to understand but took a bit of time and real world practical implementations which made learning way more fun and easy. I always need to do practical with theory when it comes to learning I find it very hard to picture learning anything without using it practically.

Now this is about port manipulation on the 328P and I’ll get into the actual implementation now without further ado.

The ATMEGA 328P has 3 ports namely B, C, D with B (digital pin 8 to 13), C (Analog input pins) and D (digital pins 0 to 7).

For the basics you only need to understand 3 types of registers you will be manipulating.

For example:

Port B
PORTBMaps to Arduino digital pins 0 to 7 Data Register – read/write
DDRBThe Port B Data Direction Register – read/write
PINBThe Port B Input Pins Register – read only

Port C
PORTCMaps to Arduino digital pins 8 to 7 Data Register – read/write
DDRC The Port C Data Direction Register – read/write
PINCThe Port C Input Pins Register – read only

Port D
PORTDMaps to Arduino digital pins 14 to 19 Data Register – read/write
DDRDThe Port D Data Direction Register – read/write
PINDThe Port D Input Pins Register – read only

So an example using DDRD (Data Direction Register) to set input and output pins:

Another example is to set digital pins 7,5,3 high:

Now you can do port manipulation with a bit shift instead of binary or hex. this makes things a bit more readable… excuse the pun. 🙂

For example to set the input or output of a single pin you could use:

Example using hexadecimal:

Now to initiate a pullup on a single pin you could use:

Example using hexadecimal:

Example using binary:

Looking at how to read a pin you can use the Input Pins Register PINB:

it is also possible to toggle a pin and there’s different ways. Some are faster then others:

You can also easily write to a pin low or high:

There’s also an atomic operation to writing low or high:

So now that we understand the basics we can get into making life easy by creating macros

Below are 4 functions made easy to iterate over all the pins in each port B, C, D

set_PIN_HIGH(pin);
set_PIN_LOW(pin);
read_PIN_STATE(pin);
toggle_PIN_STATE(pin);

This makes it easy to call the function without having to define the port each time and it’s still fast.

See the example below:

Links:

328P PIN CHANGE INTERRUPTS

#120 ATMEGA 328P Pin Change Interrupts

The 328P has 3 ports B, C, D you will need to know the basics of how they work to before reading this.

The 328P only has 2x external interrupts however there are also 23x pin change interrupts and I will be focusing on the latter for now.

INTx (external interrupts) can report events under four situations: low, any, falling, rising. PCINTx (pin change interrupts) can report events on only one situation: any, which is basically a change in the pin so we can categorise the 23x as change interrupts only.

Using these pin change interrupts are surprisingly easy but require a few steps. However once they are configured code size and complexity can be reduced significantly. Also never forget you paid for the IC and it’s hardware peripherals.. so USE THEM.

You can run a loop checking button states with multiple variables including timing and state variables etc. or…. you can run a similar reduced loop with the use of the pin change interrupts making your life so much easier while not compromising much resources.

So to get started you need to follow 3 steps:

  1. Turn the pin change interrupts on
  2. Choose the pins to interrupt
  3. Use the ISR for the chosen pins

STEP 1:

To turn on the pin change interrupts you will need to use the PCICR register.

Writing 1 to bit 0 will turn on the portB (PCINT0 – PCINT7)
Writing 1 to bit 1 will turn on the portC (PCINT8 – PCINT14)
Writing 1 to bit 2 will turn on the portD (PCINT16 – PCINT23)
From bit 3 onwards (from right to left) bits are ignored.

STEP 2:

Now you need to choose which pins you want to interrupt.
You will need to use a mask and the 328P has 3 masks: PCMSK0, PCMSK1, and PCMSK2
These masks are set in the same way as the PCICR register was set.

STEP 3:

Now you need to use the correct ISR for the chosen pins.
make sure to keep the ISR as fast as possible and use as little code as possible in the ISR.
Also if you have any variables in the ISR make sure to make them volatile. This tells the compiler that it could change at any time and to reload it each time instead of optimizing it.

Full Super Simple Example:

Links:

MPLABX VS ARDUINO IDE

#119 Differences and similarities between the two

Recently I wrote about the pros and cons etc. about different programmers used to program embedded devices. I mentioned a few examples like ST-Link, PicKit and standard DIY programmers. Now since programmers work hand in hand with the programming software on your PC I decided to talk a bit about the 2 IDEs I use often. (Although you can easily setup platform IO with a compiler for embedded devices I will be focusing mostly on full IDEs but will make mentions to using text editors)

So I’ll start with the Arduino IDE. it’s simple to install and to get started with. There’s many libraries and there’s a wide support on the internet. Note: at least in my experience in South Africa at the public school I went to there was basically no interest or effort to promote Arduino and similar platforms. Looking back this was very disappointing since I’m 99% sure I would have gotten into Arduino much earlier in life if certain educational departments had made an effort in promoting Science instead of supporting political nonsense like the “science must fall” movement but I digress.

That being said Arduino is not all fun and games, it’s a great learning introduction tool but can promote bad code practices and reliance on libraries for work. Arduino also heavily promotes using easy functions instead of port manipulation methods… even in advanced projects… this can be a bit annoying especially when you want to use a library in a project with a different MCU and also when you want to keep code small and efficient. This can really bloat your MCU code and as you can imagine there is really not much room “literally” when programming embedded devices. Macros for port manipulation can really help but relying on digitalwrite(pin1); to pull a pin high or low can really cause some confusion later on

There may be more pros and cons not mentioned above but really I just want to get into the stuff that I can mention off the top of my head for this article.

Now switching to the free MPLABX IDE. I can say that the learning curve is quite steep but easy to get into with repetitive use. Once you get familiar with the layout you can start seeing quite a few pros compared to Arduino. having the ability to view the entire file structure in the IDE helps a ton. Also AVR has been integrated into MPLABX for some years now so you can easily program Arduino style. The IDE promotes professional main.c files and avr-main.c files which is very cool (I’m not really into ASM programming at least for now there’s a very big learning curve but one day I’ll get into it I hope 🙂 ) MPLABX also supports a huge variety of ICs and you can easily download updates for these as well as some libraries. Another pro is the GUI MCC (MPLAB Code Configurator) ok, ok I’m not a huge fan because I always somehow bloat up my project and break things but I can totally see how it could help by providing a GUI for setting clocks and bits etc. Another cool feature is that there are options for dark mode in the ide and it uses NetBeans.

There are a few downsides to the MPLABX IDE for example when using a 4k screen the Nebeans part always has blurry visuals now you can adjust the DPI but then all the text is super small and when adjusting the text it becomes inconsistent in certain places. Like for example the IDE text is small but your code text is big. This has always been an issue for me but I guess I’m just suffering from a 4k screen 🙂 Another issue is that I have always had to use expensive dedicated programmers when using MPLABX non of my DIY CH340N etc. programmers will work with MPLABX. Also programming AVR requires an AVR programmer so you can’t just use a PicKit3 for everything. Another pro is that it’s easy to choose compilers in a list. You cans install multiple compilers without issue. Another great feature is that you can install the so called MPLABEXT extension using visual studio code so you don’t have to use the IDE but can keep compatibility. Another cool feature is the ability to read and program the fuses or (configuration bits for PIC). Once again there may be some pros and cons not mentioned but I’m just writing this off the top of my head.

An honourable mention goes to the text editor approach. This is very light weight and generally bloat free and offers a lot of flexibility which makes using visual studio code a great choice but of course it’s not really a dedicated IDE.

Now to close off I will include to code samples to show the differences between the Arduino IDE and MPLABX IDE I will be programming an AVR device the ATtiny826 in the comparison examples.

Arduino blink code example including a blink without delay and a fast blink sample I made :



MPLABX blink code example including a blink without delay and a fast blink sample I made :

ESP32 DEVKIT V1

#76 ESP32 that is Arduino & MicroPython Compatible

ESP-WROOM-32 32-bit 240 MHz microprocessor

The ESP32 has already integrated an antenna and RF balun, power amplifier, low-noise amplifiers, filters, and power management module. The entire solution takes up the least amount of printed circuit board area. This board is used with 2.4 GHz dual-mode Wi-Fi and Bluetooth chips by TSMC 40nm low power technology, power and RF properties best, which is safe, reliable, and scale-able to a variety of applications.

DIY ATTINY85 ALARM

#62 SIMPLE DIY ATTINY85 ALARM

Working prototype PCB .

Upon experiencing a few break-ins on the farm I decided to look for a simple alarm system to monitor certain door. For such a simple project a full on alarm commercial alarm system would be overkill.. So I endeavored on the short and fruitful DIY journey.

My system is based on the simple circuit from Great Scott on YouTube. The brains of the circuit is the Arduino programmable Attiny85 MCU. A reset push button, notification LED, arm/disarm toggle switch, notification buzzer and magnetic read switch are the IN/OUT components used.

The project runs on 12 volts (12 volts for the siren) which is filtered down to 5 volts for the Attiny85. My plan is to use a 12 volts 7 ampere lead acid battery combined with a smart charge board to power the project effectively.

After soldering the components onto the board everything worked fine. However the siren was very soft and the 2N2222A transistor was getting extremely hot. This is because the transistor has to provide a ton of current to the siren in order to get it working at 100% capacity. A quick fix is to remove the 1k resistor between Attiny85 pin 1 and the transistors base.(replace it with normal wire) This allows the siren to be louder but the transistor is still hot. A possible permanent solution will be to just use a 5v relay or look for a transistor with a higher current tolerance.

In the end I decided to go with a 5v relay module since it’s a quick reliable solution but is more expensive than a transistor. In a future upgrade I will most likely use a BC517 darlington as referenced by this article. It will be cheaper than a relay and provides more than enough current for a 15W 1 tone siren (380ma).

DATASHEETS

WEMOS D1 MINI

#57 WEMOS D1 MINI WIFI DEV BOARD

Wemos D1 mini

The Wemos D1 mini is a small WiFi based development board. The board is based off of the ESP-8266EX MCU developed by Espressif . The dimensions are 34.2*25.6 mm which allows this small package to be used effortlessly in large scale applications. Shields are also widely available and add to the ease of use for this board.

Features

  • 11 digital IO, interrupt/pwm/I2C/one-wire supported(except D0)
  • 1 analog input(3.2V max input)
  • a Micro USB connection
  • Compatible with MicroPython, Arduino, nodemcu

Technical specs

  • Operating Voltage 3.3V
  • Digital I/O Pins 11
  • Analog Input Pins 1(3.2V Max)
  • Clock Speed 80/160MHz
  • Flash 4M Bytes
  • Size 34.2*25.6mm
  • Weight 3g

My specific board comes from a company called Farylink. It looks like they make small boards with wifi capabilitys.

According to there website:

Shenzhen Huayulian technology co., LTD is an IOT company that integrates rd, production and sales and is technology-oriented and service-oriented. With a rich background in the IOT industry, it focuses on the research, development and production of IOT communications.

[datasheet]
Size fingers for scale.
Looks like someone rubbed of the programming IC’s serial markings. Or perhaps it was manufactured without any markings? Either way the fact remains its 100% a Chinese copy.

The link to the CH340 driver (which is required to program the Wemos D1 mini over USB) can be found here.

DIY VOLTAGE DIVIDER

#56 DIY VOLTAGE DIVIDER

In order to measure the voltage of a DC battery we will need a voltage divider sensor. I built an easy DIY voltage divider which works quite well. All we need are two resistors to measure the voltage in a certain way so our Arduino doesn’t fry.

After working out my requirements for a 12v 7Ah battery I came to the conclusion that I needed a 30k and a 7.5k resistor. This will allow me to measure DC voltage from 0.025v to 25v.

I built 2 sensors
Top of the board

I only had to break the connection on the trace where the screw terminal was soldered to.

After creating a simple Arduino sketch I was able to output the data to the serial monitor. I had to add the correction factor of -0.150 to get an accurate reading after checking with two multimeters.

voltage read sketch
Serial monitor display

I used the Arduino pro mini as the MCU of this project.

MADUINO ZERO SIM808

#48 MADUINO ZERO SIM808 GPS TRACKER

The Maduino Zero SIM808 GPS Tracker is an IOT (Internet of things) Solution based on the 32-bit Atmel’s SAMD21 MCU and GPRS/GSM GPS module SIM808. It intergrates a micro Controller ATSAMD21G18, GRRS/GSM module SIM808, which is the upgrade version of SIM900, power management and storage, to make the SIM808 GPS Tracker ready for IOT projects such as smart-home, outdoor monitoring, shared bicycle, etc. The Marduino Zero SIM808 GPS Tracker based on the Arduino, users can program it with Arduino IDE, which is very easy especially for the none-programmers.

This is the V3.4 version, Note that to ensure the module starts up right, a lipo battery is needed to power up the Maduino Zero SIM808 GPS tracker V3.4.

Quick Spec

  • AT Input Voltage: 3.4-4.2V
  • Microcontroller: ATSAMD21G18, 32-Bit ARM Cortex M0+
  • Clock Speed: 48 MHz
  • Micro SIM connector
  • Integrated Power Control System
  • AT command interface with “auto baud” detection Quad-band: 850/900/1800/1900Mz
  • Send and receive GPRS data (TCP/IP, HTTP, etc.)
  • GPS L1 C/A code
  • 22 tracking /66 acquisition channels
  • Tracking: -165 dBm
  • Cold starts: -148 dBm
  • Time-To-First-Fix:Cold starts-32s (typ.), Hot starts-1s (typ.),Warm starts-5s (typ.)
  • Accuracy: approx. 2.5 meters
  • Interface: I2C/SPI/UART/18*GPIO
  • Arduino compatible
  • Working Temperature: -40 – 85℃
  • Size: 40 x 55mm
  • Net Weight: 23g

PRO MINI FARM ALARM V1.0

#42 PRO MINI FARM ALARM V1.0 BREADBOARD

The Pro Mini V1.0 testing for the Farm Alarm

The Pro Mini has proven to be a suitable solution. The board is very small and has more than enough specs to control the GSM/GPRS module while also sending data to a remote server via TCP.

The Pro Mini requires an FTDI programmer since there is no USB port on the board.

FTDI programmers pin out relative to the Pro Mini
Pro Mini ( ATMEL MEGA328P MU1039 )

FAILED ATTINY85 EXAMPLE

#41 A FAILED ATTINY85 EXAMPLE (GSM/GPRS)

A quick solder up to test the circuit (had issues with power sharing between GSM module and ATTINY85)

My first attempt to build a small circuit which controls a relay to an alarm speaker was a failure. Contrary to popular belief failure in electronics projects is quite common and I would argue that it is of paramount need if you want to learn anything.

Surprisingly my failure was in using the ATTINY85 instead a Pro Mini, Uno or Mega. Some problems I had were:

  • Not enough RAM to hold all my variables (I had to scrounge 😢)
  • Very limited FLASH memory.
  • GSM module interferes with the ATTINY’s 5v power source when connected using the same source with no filtering.

In a later project I created a reliably working solution with the Pro Mini as the brains.

My goal was to create a small circuit which uses the ATTINY85 as the brains. It uses the A6-GSM-Module to receive SMS’s, phone calls and sends TCP data. Finally it has a 5v relay which will switch on/off an alarm speaker. The theory is that when I’m on the farm in the fields and not near the house, I have the option of remotely starting an audio alarm at will. This should be a deterrent to potential criminals.

I made an easier to debug testing circuit with exposed copper traces (Same issues)

After making an easier to debug circuit I tried to get the ATTINY85 to work happily with the GSM module. This was going to be a bit complicated and I suspect I would have to isolate power between the ATTINY85 and the GSM module. This would require more components and the board is already looking cramped. A much easier solution is to use the Pro Mini instead of the ATTINY85.

The Pro Mini is most certainly a beauty.