LoRa Base Module with ATMEGA328P

I had a need to build a reliable LoRa device, in order to do some testing regarding range etc, for an upcoming project on a friend’s farm. The device needs to be ultra-cheap to manufacture, as well as little power as possible. To achieve this, I decided on using the RA-02 ( From AI Tinker, not sponsored) as well as an ATMEGA328P, which consumes very little current when put to sleep… ( The radio will be on standby the whole time though..)

Building this with a standard Arduino, or another ATMEGA powered development board can be quite messy ( as the picture below shows… )

RA-02 LoRa module with ATMEGA328P PCB – Quite messy !!

A standard Arduino will be even worse, as you need level conversion on the SPI pins, due to the fact that the RA-02 is a 3.3v device, with the GPIO, not being 5v tolerant (Yes, this is true, some other posts on Youtube and similar conveniently leave out this very important little caveat… )

This problem thus warranted a dedicated custom PCB, to be designed in stages, and thoroughly tested of course… And while doing that, I needed to design something that was modular and useable.

I came up with the following design, as a stage one prototype:

Stage 1 LoRa Base Module Prototype

The PCB is basically an Arduino Nano style PCB ( as far as IO is concerned ), with level conversion on the SPI lines ( SCK, MISO, MOSI, SS) as well as a Lora reset and IRQ pin ( which will be essential to wake up the processor later ).

As the prototype will mostly be used in the lab, with some outdoor tests later, provision was not made for battery charging circuitry. Two LDO regulators, 5v and 3.3v provide power to the ATMEGA328P and RA-02 from a DC input of 7.5 to 12v.

Level conversion is fixed at bi-directional 5v to 3v logic levels.

All unused GPIO’s are broken out onto headers.

Code can be uploaded to the MCU via ICSP or a USB-to-serial converter, as I did not add those on board, to save space and power later.

Control Pins are as follows:

RA-02 ModuleATMEGA328P
SCKD13
MISOD12
MOSID11
NSSD10
RESETD9
IQR(DIO0)D2 ( Interrupt 0 )
DIO1Not broken out on stage 1 Prototype
DIO2Not broken out on stage 1 Prototype
DIO3Not broken out on stage 1 Prototype
DIO4Not broken out on stage 1 Prototype
Pin connections between RA-02 and ATMEGA328P

The Schematic diagram are listed below

Schematic Diagram – Page 1
Schematic Diagram – Page 2
PCB – Top
PCB – Bottom

Software

The board is compatible with the LoRa library from Sandeep Mistry. Other libraries may work as well but were not tested yet.

A very basic test sketch follows below:
Note that this sketch does not have any power-saving. It is purely used to do a very basic radio test…
More detailed code will be released in later stages of the project ( more on that later )

#include <SPI.h>              // include libraries
#include <LoRa.h>

const int csPin = 10;          // LoRa radio chip select
const int resetPin = 9;       // LoRa radio reset
const int irqPin = 2;         // change for your board; must be a hardware interrupt pin

byte msgCount = 0;            // count of outgoing messages
int interval = 2000;          // interval between sends
long lastSendTime = 0;        // time of last packet send

void setup() {
  Serial.begin(9600);                   // initialize serial
  while (!Serial);

  Serial.println("LoRa Duplex - Set spreading factor");

  // override the default CS, reset, and IRQ pins (optional)
  LoRa.setPins(csPin, resetPin, irqPin); // set CS, reset, IRQ pin

  if (!LoRa.begin(433E6)) {             // initialize ratio at 433 MHz
    Serial.println("LoRa init failed. Check your connections.");
    while (true);                       // if failed, do nothing
  }

  LoRa.setSpreadingFactor(8);           // ranges from 6-12,default 7 see API docs
  Serial.println("LoRa init succeeded.");
}

void loop() {
  if (millis() - lastSendTime > interval) {
    String message = "LoRa TEST";   // send a message
    message += msgCount;
    sendMessage(message);
    Serial.println("Sending " + message);
    lastSendTime = millis();            // timestamp the message
    interval = random(2000) + 1000;    // 2-3 seconds
    msgCount++;
  }

  // parse for a packet, and call onReceive with the result:
  onReceive(LoRa.parsePacket());
}

void sendMessage(String outgoing) {
  LoRa.beginPacket();                   // start packet
  LoRa.print(outgoing);                 // add payload
  LoRa.endPacket();                     // finish packet and send it
  msgCount++;                           // increment message ID
}

void onReceive(int packetSize) {
  if (packetSize == 0) return;          // if there's no packet, return

  // read packet header bytes:
  String incoming = "";

  while (LoRa.available()) {
    incoming += (char)LoRa.read();
  }

  Serial.println("Message: " + incoming);
  Serial.println("RSSI: " + String(LoRa.packetRssi()));
  Serial.println("Snr: " + String(LoRa.packetSnr()));
  Serial.println();
}

Future Plans

Future plans for this project include the following:
– Integration of a LiPo battery charging module, with a boost converter, to enable the device to run on battery power.
– Integration with an ESP32 or similar, to build a simple GATEWAY device
– CAN-BUS controller integration, to allow for adding multiple sensors to one radio module
– IO card, with galvanically isolated inputs, as well as Relay outputs, for remote control and monitoring applications.



The PCB can be ordered, or the design files downloaded ( a free download ) from my Projects page at PCBWay soon…

This PCB was manufactured at PCBWAY. The Gerber files and BOM, as well as all the schematics, will soon be available as a shared project on their website. If you would like to have PCBWAY manufacture one of your own, designs, or even this particular PCB, you need to do the following…
1) Click on this link
2) Create an account if you have not already got one of your own.
If you use the link above, you will also instantly receive a $5USD coupon, which you can use on your first or any other order later. (Disclaimer: I will earn a small referral fee from PCBWay. This referral fee will not affect the cost of your order, nor will you pay any part thereof.)
3) Once you have gone to their website, and created an account, or login with your existing account,

4) Click on PCB Instant Quote

5) If you do not have any very special requirements for your PCB, click on Quick-order PCB

6) Click on Add Gerber File, and select your Gerber file(s) from your computer. Most of your PCB details will now be automatically selected, leaving you to only select the solder mask and silk-screen colour, as well as to remove the order number or not. You can of course fine-tune everything exactly as you want as well.

7) You can also select whether you want an SMD stencil, or have the board assembled after manufacturing. Please note that the assembly service, as well as the cost of your components, ARE NOT included in the initial quoted price. ( The quote will update depending on what options you select ).

8) When you are happy with the options that you have selected, you can click on the Save to Cart Button. From here on, you can go to the top of the screen, click on Cart, make any payment(s) or use any coupons that you have in your account.

Then just sit back and wait for your new PCB to be delivered to your door via the shipping company that you have selected during checkout.


Build your own USB-ASP Programmer Clone

Using more ATMEGA based MCU’s in my recent projects, and not using ready-made Arduino boards for any of them, it became necessary to invest in a dedicated ASP programmer to flash the MCU’s. Huge delays on electronics components, with confirmed orders being mysteriously cancelled due to sourcing issues, and the high cost of “original OEM ASP programmers”, send me on a search for a DIY style programmer, like the old “NOPPP” ( NO PARTS PIC Programmer) in the good old days…

Personal computers have changed a lot, and while ATMEGA chips are not PIC’s, I did feel that it could be done. Given the fact that you could also use an Arduino UNO as an ISP, and doing a little more digging, I finally found a very attractive alternative…

Thomas Fischl, on his website,https://www.fischl.de/usbasp, has an open-source hardware project, that seemed to be exactly what I needed. His device is capable of programming 5v devices, at various speeds, including a super slow one. He has also written firmware for the device, and although the last update was in 2011, It still seems to be working well, or at least as far as I can see…

I did however decide to add my own twist to the design and build in a logic level converter, to be able to program 3.3v devices as well…

The modified schematic is below:

Schematic Page 1
Schematic Page 2

I chose to do my own PCB layout, to incorporate the changes listed earlier, namely the logic level conversion from 5v to 3v, as well as adding a 3.3v LDO voltage regulator to provide 3.3v to the target in case it is required.

PCB Topside
PCB Bottom Side
3D Render of the PCB

The PCB is still in transit from the factory, and thus I will update this article later with pictures of the actual device.

Firmware can be flashed using any ASP programmer, Arduino as ISP as well, but with the caveat that you have to use AVRDude from the command line… More on that in the follow-up post… ( I would like to show actual screenshots of the process, and not theory.. ). The links to the firmware are available on https://www.fischl.de/usbasp, courtesy of Thomas Fischl, whom I would like to thank for making this open-source hardware project available freely, as well as for writing and maintaining the firmware.


The PCB can be ordered, or the design files downloaded ( a free download ) from my Projects page at PCBWay soon…

This PCB was manufactured at PCBWAY. The Gerber files and BOM, as well as all the schematics, will soon be available as a shared project on their website. If you would like to have PCBWAY manufacture one of your own, designs, or even this particular PCB, you need to do the following…
1) Click on this link
2) Create an account if you have not already got one of your own.
If you use the link above, you will also instantly receive a $5USD coupon, which you can use on your first or any other order later. (Disclaimer: I will earn a small referral fee from PCBWay. This referral fee will not affect the cost of your order, nor will you pay any part thereof.)
3) Once you have gone to their website, and created an account, or login with your existing account,

4) Click on PCB Instant Quote

5) If you do not have any very special requirements for your PCB, click on Quick-order PCB

6) Click on Add Gerber File, and select your Gerber file(s) from your computer. Most of your PCB details will now be automatically selected, leaving you to only select the solder mask and silk-screen colour, as well as to remove the order number or not. You can of course fine-tune everything exactly as you want as well.

7) You can also select whether you want an SMD stencil, or have the board assembled after manufacturing. Please note that the assembly service, as well as the cost of your components, ARE NOT included in the initial quoted price. ( The quote will update depending on what options you select ).

8) When you are happy with the options that you have selected, you can click on the Save to Cart Button. From here on, you can go to the top of the screen, click on Cart, make any payment(s) or use any coupons that you have in your account.

Then just sit back and wait for your new PCB to be delivered to your door via the shipping company that you have selected during checkout.




Automate your desk- or floor-standing fan

A typical desktop oscillating fan

Desk or floor-standing fans are one of those appliances that will be present in almost every home or office. Some of the newer ones may already have remote control of some sort, while the older models won’t. It is however quite easy to do a retro-fitted controller to most of them, and at the same time, give them some (limited) intelligence.

Your typical oscillating fan does not have a lot of intelligence built-in. They normally consist of an electrical motor, with three separate windings, of varying inductance ( meaning the number of turns in the coil of wire will change the magnetic field generated, thereby changing the speed of the electric motor).

These windings have one common side, where all three of them are connected together, and the other three are separated. Normally the live wire from your mains supply (220v AC in my case) will go to this common connection. The neutral wire will go to the common of a four-position mechanical switch, with each winding going to one of positions 2,3 and 4 ( This results in a 3-speed configuration, with the first switch being off). It is also VERY important to note that this mechanical switch is hardware interlocked, meaning that ONLY one switch can be on at any given time… This is to ensure that electricity can only flow through one winding at a time. If you were to send electricity through multiple windings at the same time, the motor will still work, but not for very long…

A more modern Oscillating Fan


In order to automate an oscillating fan, we would thus need a way to switch the separate windings on and off, while preventing other windings from getting power at the same time. I chose to do this with SPST relays, as a proof of concept, and plan to design it with DPDT relays at a later stage to implement a proper hardware interlock, in addition to the software interlock implemented in the control software ( more on that later)

My requirements for the device are the following:
1) Must operate from mains power, using the existing power cord of the fan.
2) Must allow for local operation of the fan using the existing control buttons.
3) Must be able to update firmware OTA, and have WiFi connectivity for control via Home Assistant or MQTT
4) Must be capable of adding support for ESP Now protocol at a later stage
5) The fan must not have any visible modifications on the outside

The 3 speed Fan controller PCB

Taking all of my requirements into consideration, I have designed the following PCB to take care of my needs. As I do not require a lot of GPIO for this ( only 3 outputs, and 3 inputs ), I have decided to use an ESP8266-12E module from Espressif ( manufactured by AITinker, not sponsored by either company). This module is relatively cheap and has more than enough flash memory, RAM, as well as GPIO available.

Circuit Diagram – Page 1
Circuit Diagram – Page 2

As we can see, the circuit is minimal, with optical isolation on the relay drivers, a programming header, and a 3-way input for the mechanical switch.

The completed PCB, wired to the oscillating fan

As seen in the picture above, the wiring is quite simple, with the neutral wire looped to the common terminal of each relay (I had only green mains rated cable available, will replace it later with a proper white cable to keep to wiring standards). Black is live, with one wire going to the mains socket, and the other to the common of the motor coil windings. Light blue, yellow and white ( connected to the N/O terminal of the relays) corresponds to speeds 1, 2 and 3 of the fan.

At the top of the board, 3 wires go to the mechanical switch and a fourth to DC ground. (Note that there is no AC voltage on any of the switches. )

Mounting the PCB in the base of the oscillating fan

The PCB is mounted in the base of the fan while taking care to ensure that no AC cables are near the DC components. The ESP8266 chip is oriented to the side ( logo side of PCB ) to prevent interference to the WiFi signal. The mechanical switch is mounted into its original position, and its wires are routed away from any AC carrying wires to prevent interference.

It is important to note here that the firmware for the PCB was uploaded before assembly. You should NOT attempt serial uploading while the device is connected to mains power under any circumstances. ( While I have taken every precaution to ensure that AC and DC components of the circuit are separated from each other, it is just common sense to not try to upload firmware with mains connected)

The completed PCB shows the Upload port near the right top corner.

Uploading firmware:

Initial uploading of firmware can be performed by connecting a USB-to-serial adapter to the UPLOAD port and providing 5v and ground from the USB-to-serial adapter. The flash button is held down, and the board is reset, after which you can proceed with uploading, alternatively, you can also connect the DTR and RTS lines from the serial adapter to automatically reset the board and enter flash mode as needed. ( If your adapter supports this of course).

ESPHome configuration

The YAML configuration for ESPHome is listed below:

esphome:
  name: esphome-web-18df94

esp8266:
  board: nodemcuv2


# Enable logging
logger:

# Enable Home Assistant API
api:

ota:


wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password

  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "Esphome-Web-18Df94"
    password: "verysecurepassword"

captive_portal:

sensor:
  - platform: adc
    pin: VCC
    name: "ESP8266 Chip Voltage"
    id: mcu_voltage
    unit_of_measurement: "V"
    device_class: "voltage"
    accuracy_decimals: 2
    update_interval: 60s
    
  - platform: wifi_signal
    name: "WiFi Signal Sensor"
    id: wifi_strength
    device_class: "signal_strength"
    unit_of_measurement: "dBm"
    update_interval: 240s

binary_sensor:
  - platform: gpio
    pin: 
      number: 12
      inverted: true
    name: "Fan Local Control Speed 1"
    id: "fan_local_1"
    icon: "mdi:fan-speed-1"
    filters:
      - delayed_on: 500ms
      - delayed_off: 500ms
    
    on_press:
      then:
        - switch.turn_on: speed1
    on_release:
      then:
        - switch.turn_off: speed1
  
  - platform: gpio
    pin: 
      number: 13
      inverted: true
    name: "Fan Local Control Speed 2"
    id: "fan_local_2"
    icon: "mdi:fan-speed-2"
    filters:
      - delayed_on: 500ms
      - delayed_off: 500ms
    
    on_press:
      then:
        - switch.turn_on: speed2
    on_release:
      then:
        - switch.turn_off: speed2
      
  - platform: gpio
    pin: 
      number: 14
      inverted: true
    name: "Fan Local Control Speed 3"
    id: "fan_local_3"
    icon: "mdi:fan-speed-3"
    filters:
      - delayed_on: 500ms
      - delayed_off: 500ms
    
    on_press:
      then:
        - switch.turn_on: speed3
    on_release:
      then:
        - switch.turn_off: speed3

switch:
  - platform: template
    name: "Fan Off"
    id: "fan_off"
    icon: "mdi:fan-off"
    lambda: |-
      if (id(speed1).state or id(speed2).state or id(speed3).state) {
        return false;
      } else {
        return true;
      }
    turn_on_action:
      - switch.turn_off: speed1
      - switch.turn_off: speed2
      - switch.turn_off: speed3
      

  - platform: gpio
    pin: 16
    interlock: &interlock_group [speed1, speed2, speed3]
    interlock_wait_time: 1000ms
    name: "Fan Speed 1"
    icon: "mdi:fan-speed-1"
    id: "speed1"
    inverted: true
    
    
  - platform: gpio
    pin: 5
    interlock: *interlock_group
    interlock_wait_time: 1000ms
    name: "Fan Speed 2"
    icon: "mdi:fan-speed-2"
    id: "speed2"
    inverted: true
    
  - platform: gpio
    pin: 4
    interlock: *interlock_group
    interlock_wait_time: 1000ms
    name: "Fan Speed 3"
    icon: "mdi:fan-speed-3"
    id: "speed3"
    inverted: true
    

Manufacturing the PCB

This PCB was manufactured at PCBWAY. The Gerber files and BOM, as well as all the schematics, will soon be available as a shared project on their website. If you would like to have PCBWAY manufacture one of your own, designs, or even this particular PCB, you need to do the following…
1) Click on this link
2) Create an account if you have not already got one of your own.
If you use the link above, you will also instantly receive a $5USD coupon, which you can use on your first or any other order later. (Disclaimer: I will earn a small referral fee from PCBWay. This referral fee will not affect the cost of your order, nor will you pay any part thereof.)
3) Once you have gone to their website, and created an account, or login with your existing account,

4) Click on PCB Instant Quote

5) If you do not have any very special requirements for your PCB, click on Quick-order PCB

6) Click on Add Gerber File, and select your Gerber file(s) from your computer. Most of your PCB details will now be automatically selected, leaving you to only select the solder mask and silk-screen colour, as well as to remove the order number or not. You can of course fine-tune everything exactly as you want as well.

7) You can also select whether you want an SMD stencil, or have the board assembled after manufacturing. Please note that the assembly service, as well as the cost of your components, ARE NOT included in the initial quoted price. ( The quote will update depending on what options you select ).

8) When you are happy with the options that you have selected, you can click on the Save to Cart Button. From here on, you can go to the top of the screen, click on Cart, make any payment(s) or use any coupons that you have in your account.

Then just sit back and wait for your new PCB to be delivered to your door via the shipping company that you have selected during checkout.

Remaking the STM32 Blue-Pill – Part 1

Why did I do this?
Of all the various development boards in my electronics lab, surely the most versatile, but most neglected must be the STM32 Blue Pill. Not that there is anything wrong with it, It is a very very nice board, but unfortunately, there are a few issues ( mostly personal ) that make it not jump out at me for use in a new project.

Of these, and quite similar to the Arduino Nano, and original Raspberry Pi Pico is the fact that it was designed to be mostly used on a breadboard, issues with using the USB port, wrong components installed at the factories, and needing magnification to read port numbers, made me decide to solve it in my own way.

It is also not possible to use it (the original Blue-Pill) with any of the ready-made shields for the Arduino Nano, due to different pin-outs etc. Thus requiring a mess of wires and more modules on a breadboard, or lying free on the bench, to add sensors and other devices to this particular development board…

It can be argued that its small size does make it attractive, with which I definitely do not disagree, but unlike the bigger STM32 development boards with a lot of included peripherals, or the Arduino Ecosystem, where it is possible to develop your hardware prototypes on an Arduino Uno, using various shields, and then move on to a custom PCB later, the blue pill’s development cycle seems to be very much tied to the use of a breadboard and/or modules connected with jumper wires etc…

My idea was thus to take some inspiration from the bigger STM32 Nucleo and Discovery type platforms, add very detailed, and readable pin numbers, and peripheral descriptions, as well as lay a foundation onto which I can in future design stackable shields to expand the functionality of the device.

In order to make it easier for Makers and Hobby Electronics Enthusiasts, the new PCB was designed with 0805 SMD components. These are still quite easy to solder by hand, and usually do not require the use of any special equipment (That most beginners just starting out with the hobby won’t necessarily own or have access to by default). All of this was done with the hope that more people will start using this form factor, as well as to stimulate the development of shields and add-on cards to truly bring the blue pill to the same level regarding ease-of-use that the Arduino Ecosystem currently occupies.


What changes did I make?

Blue Dev Board Schematic Diagram – MakerIot2020

The schematic diagram was not changed at all. All ports and pin numbers are 100% compatible with the original Blue Pill. Components sizes were changed from 0402 to 0805. I also made sure that the USB port would be functional, and would not require any modifications to be performed to make it useable (unlike some of the blue pill PCB’s available in Asia, which ships with a wrong value resistor at R10.

The PCB form factor has been changed to be the same size as the Arduino Uno, but with two rows of 20-pin 2.54mm headers. A more powerful 3.3v LDO regulator and additional smoothing capacitors were added. The main changes are to the silkscreen, where the pin numbering was enlarged to be more easily readable, and detailed labelling of the various possible peripherals were added. The board is also a single layer PCB, whereas the original was a double layer PCB, due to its small size.

Where and when can you get one?

The PCB is currently in production at PCBWay. When I have completed all testing of the PCB, it will be available as a PCBWay shared project, which means that you can order your own, or freely download the Manufacturing files to produce your own if you so choose. You can also contact me directly.

I plan to have completed all testing and to make available the manufacturing files, by the end of February 2022. Please be patient.

This PCB was manufactured at PCBWAY. The Gerber files and BOM, as well as all the schematics, will soon be available as a shared project on their website. If you would like to have PCBWAY manufacture one of your own, designs, or even this particular PCB, you need to do the following…
1) Click on this link
2) Create an account if you have not already got one of your own.
If you use the link above, you will also instantly receive a $5USD coupon, which you can use on your first or any other order later. (Disclaimer: I will earn a small referral fee from PCBWay. This referral fee will not affect the cost of your order, nor will you pay any part thereof.)
3) Once you have gone to their website, and created an account, or login with your existing account,

4) Click on PCB Instant Quote

5) If you do not have any very special requirements for your PCB, click on Quick-order PCB

6) Click on Add Gerber File, and select your Gerber file(s) from your computer. Most of your PCB details will now be automatically selected, leaving you to only select the solder mask and silk-screen colour, as well as to remove the order number or not. You can of course fine-tune everything exactly as you want as well.

7) You can also select whether you want an SMD stencil, or have the board assembled after manufacturing. Please note that the assembly service, as well as the cost of your components, ARE NOT included in the initial quoted price. ( The quote will update depending on what options you select ).

8) When you are happy with the options that you have selected, you can click on the Save to Cart Button. From here on, you can go to the top of the screen, click on Cart, make any payment(s) or use any coupons that you have in your account.

Then just sit back and wait for your new PCB to be delivered to your door via the shipping company that you have selected during checkout.