ATMega328P prototype add-on card for use with the MCU-8266-12E IoT controller.

In August of 2021, MakerIoT2020 released the MCU-8266-12E IoT Controller PCB, (part 1 is available here in case you missed that). Shortly after that, we started working on an expansion add-on card, that would work with the APE (Arduino Port Expander) protocol in ESPHome.

While I could have used a standard Arduino board for this, and in fact, I have done so during many of the testing stages,
I decided to design a custom PCB specifically for this task, in order to achieve two specific things…

1). The standard Arduino Board comes in either a 5v logic or 3v logic device. While this is perfect for many projects,
it is still sometimes required to use a logic level converter with some sensors and devices. LORA is a good example of that. As I really dislike using a breadboard, due to their inherent unreliable connections and the ever-present mess of wires going everywhere, I wanted an Arduino or ATMEGA328 based device that already has a level converter built-in.

As I could not find anything like that for sale, I decided to build my own, as you will see shortly.

2). I wanted to start moving away from using the Arduino IDE as much as possible. While the Arduino IDE is great for most tasks, It does lack in a few areas. I thus want to slowly ease myself back into using AVR C, and that requires a board that can be flashed via ICSP. ( yes, yes, you can flash an Arduino with ICSP as well. ) In the case of the planned expansion card, it would basically be a device that is flashed once and then left alone. Serial flashing would be quite unnecessary on there anyway.

The other reason, still part of point 2, is that it seems like everyone else is having all sorts of problems with fuses on the ATMega328 on custom boards etc… I wanted to see if that is really the case or not…

The PCB should also be useable as a standard “Arduino” type device to assist in prototyping and development.

ATMega328P Custom PCB – as a prototype add-on card to the MCU-8266-12E IoT controller

a Quick description of the PCB:

Standard Arduino type headers and pins are provided, with pin labels as for the Arduino Nano.
This gives us:

ATMega 328P MCU running at 16Mhz
12 Digital IO (D2 to D13) [ 14 if we use D1 and D2 as well ]
8 Analog Inputs (A0 to A7) [ A4 and A5 are used for I2C ]
ICSP header for uploading code
USB Port with CH340G for Arduino style serial flashing [This will be removed on the next version]
A Dedicated LDO 3.3v Voltage regulator, with a selectable input source (5v from USB, or directly from VIN – for high current use applications – MAX of 800mA)

An 8 Channel Bi-Directional Logic Level Converter, for now, the converter is fixed at bi-directional 3v to 5v conversion.
Additional 5v (x4), 3v (x4) and Ground pins (x8), as well as 2 general use bus connections (G1, G2) which I added for use with I2C

Led’s are provided on 5v, 3v, Serial Rx, Tx, as well as on pin D13.

Dimensions: 86mm x 51mm

Assembly – During Reflow on a hotplate.
During Reflow

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.

Conclusion

In conclusion, the PCB works quite well, with no issues with flashing the ATMEGA328P with an ICSP programmer from the Arduino IDE, as well as via USB from the Arduino IDE.

The level converter works as expected, successfully translating bidirectional signals on I2C and SPI to and from 3v and 5v devices.

In the next stage, we will focus on the stock APE protocol sketch, as provided by ESPHome, and then, once that is working perfectly, modify it to suit our needs.


Build your own 8 DI Optically Isolated Arduino Shield – Part 3

Welcome to the final instalment of my 8 DI Optically Isolated Arduino Shield. Today I will show you some of the assembly pictures, as well as look at the coding to use this shield. I will also provide you with a link to the manufacturing files, in case you want to make your own.

These PBC’s were manufactured at PCBWAY.

You can order your own version of this board for just $5 USD if you click here

PCBWay makes it quite easy to order prototypes for your PCB’s… Just upload the Gerber files on their website, select your desired options for the PCB and order. The turn-around time is great. I received these boards, ordered together with a stencil for SMD assembly, in exactly 5 days, shipping from China to Thailand 🙂 That is super fast, as it arrived 4 days faster than the components that were ordered locally from Bangkok! Be sure to consider using their services next time you need a PBC made…

Top and bottom layout of completed Shield
Bottom of Shield
Top Layout

Some notes on assembly: The reset switch will seem misplaced, and indeed, it is 🙂 The reason for this is that I could not get any 4 pin tactile switches 🙁 So I had to either leave it unpopulated or use a two-pin tactile switch. As I will be using these shields myself, I decided that although it doesn’t look perfect, the two pin switch will still provide me with the functionality that I want.

On the bottom of the board, you can still see some blobs of flux, as the pictures were taken right after assembly, and have not been cleaned up yet. Some solder joints have also not been cleaned up yet.

The top of the unpopulated PCB
The bottom of the PCB

Testing and Coding

The testing of the board is quite straightforward. I first checked all the power rails with a multimeter to make sure there are no open circuits of shorts. Then I checked connections to all the chips and other components, yes, it takes a while to do that, but rather safe than sorry. After assembly, I repeated this process, making sure that all the components receive the correct power level, and that all switches ( like for addressing and the reset button ) actually do what I intended them to do. The next tests were the individual inputs with the optocouplers. This is done by connecting an input source (between 5.5v and 32v) to each individual input and then physically testing on the pins of the optocoupler in question, for the correct voltage input.

The shield is then powered from 5v and the input test is repeated while checking with a multimeter that the input signal does indeed get transferred by the optocoupler to the PCF8574 chip. I found that with the particular batch of PCF8574 chips that I got, that the IC would only respond reliably with a voltage between 5.5v and 32v. The original design was for 3.0v to 32v. I found that the Optocoupler EL357N seems to be unable to switch itself on at the low current allowed through the resistor divider at the input. This can be fixed by lowering the value of R1, R5, R9, R13, R17, R21, R25, R27 from 4k7 to whatever value you need. Note that that will reduce the top-level input voltage that you can safely use. For my application, however, 5.5v to 24v will be perfect, so I will leave it as is.

The shield is now connected to an Arduino with DuPont Wires, to test the I2C addressing of the PCF8574. The chip address is changed with the 3-way dip switch at SW1. All eight addresses are available. It should be noted that I have used a pull-up configuration on the address lines. That will reverse your logic.. Switching the dip switch on will pull the pin to GND, not to VCC as you would normally expect. Thus as an example, all switches off will give an address 0f 0x3f, while all on will give 0x38.

Coding

You can use the standard Arduino IDE with the Wire.h library to code the shield, or you can use one of the many PCF8574 libraries that are available. I coded my tests with the Embeetle IDE, as it gives me much better control over my code. I will show you a short, interrupt enabled sketch, in Arduino C++ below

#include <Wire.h>

byte _portStatus = 0b00000000;
boolean _readI2C = false;

void MyISR() { // Interrupt service routine
  //Serial.println("Interrupt Occured on Pin2");
  if (_readI2C != true) {
    _readI2C = true;  
  }
}

void setup() {
  // put your setup code here, to run once:
  pinMode(2,INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(2),MyISR,FALLING);
  Serial.begin(115200);
  Wire.begin();
  Wire.beginTransmission(0x20);
  Wire.write(0xFF); // set all pins to 1, needed to make them inputs
  Wire.endTransmission();
}

void loop() {
  // put your main code here, to run repeatedly:
  
  byte _data;
  if (_readI2C == true) {
    _readI2C = false;
    Wire.requestFrom(0x20,1);
    if (Wire.available()) {
      _data = Wire.read();
    }
  }
  if (_portStatus != _data) {
    Serial.print("Port Data Changed : 0xb");
    Serial.print(_portStatus,BIN);
    Serial.print(" changed to : 0xb");
    Serial.println(_data,BIN);
    _portStatus = _data;
    delay(50);
  } else {
    _portStatus = _portStatus;
  }
  
}

Conclusion

This turned out to be a very interesting and fun project to do. From designing the circuit to getting it manufactured and hand assembling it myself was a very satisfying experience. I would like to take this opportunity to thank Wendy Wu, from PCBWay‘s Marketing department, for her assistance with the manufacturing of the board. The speed and efficiency with which she handled this project were fantastic.

Build your own 8 DI Optically Isolated Arduino Shield – Part 2

In part 1 of this article, I introduced my new I2C 8DI Optically Isolated Arduino Shield. Today, I will show you how the full design, as well as the circuit diagram.

This shield was designed to allow an input of between 3.0v and 32.0v to be applied to the various inputs. This will be completely galvanic isolated from the rest of the circuitry on the shield, and thus also from your Arduino, or other micro-controller if you choose to use another one 🙂 Yes, This is possible, as long as you power the shield with 3.0v to 5.0v. You will also have to connect your I2C bus to the SCL and SDA Lines marked on the shield.

Please note that, if you decide to do that, the other Arduino specific pins, as broken out on the shield headers, will have no connections to anything else. :), an obvious fact, but it should be stated, it seems 🙂

The Circuit Diagram

Circuit Diagram, Page 1 of 2

As you can see on page 1, each optically isolated input has a voltage divider resistor network in front of the Opto Coupler. This resistor network also limits the current that can be used by the infrared LED inside of the EL357N chip to 5mA at 32v DC. ( The chip can accept up to 50mA, but it should not be driven so hard 🙂 ) A diode provides reverse-polarity protection to each input as well.

Another voltage divider on the output side limits the current to the PCF8574 Chip. This can also only source or sink 25mA per IO.

Note that there is NO common ground between the input and output sides of this circuit. That means that you have to provide another ground, usually from your external device… This ensures that galvanic isolation between the two circuits is maintained.

Circuit Diagram, Page 2 of 2

On page 2, we can see the various net connections to the connectors, PCF8574 chip, as well as various jumper headers, to select the interrupt pin [H3] ( For Arduino, D2 or D3, other micro-controllers: you are free to select any GPIO to connect to the D2 or D3 header pin ).


You can also select to enable or disable the pull-up resistors on the I2C bus, by shorting the jumper on [H2].
This is usually only needed on the first shield, or in other words, you need one pair of pullup resistors per i2c bus, not one pair per device!

Device addressing is selected with SW1. 8 addresses are available but switching this switch as per the table on the back of the PCB. It is worth mentioning that depending on the version of the PCF8574 chip that is on the shield, there are 8 addresses available, with 0x20h to 0x27h being common on the PCF8574, and 0x38h to 0x3fh being used on the PCF8574A/T version.

Typical Connection

Typical connection of input. Note that there are no common ground between the two devices

The PCB

The shield is built on a double-sided PCB or 71.12mm x 61.72mm. This is only slightly bigger than the standard Arduino Uno. All resistors, capacitors and LED’s are of 0805 sizes. ( smaller than that is a bit hard on my eyes, although it can be done, just takes longer 🙂 ). A ground plane is provided on both sides of the PCB.

PCB design file

All Arduino pins are broken out on a double row of 2.54mm headers. This allows you to use either the outside row with stack-able male-female headers, like on most shields, or you can use dedicated male and female headers, in a zig-zag pattern to stack the shields.

I have done the same with the ICSP header, as on many other commercially available shields, there is only a single female 3×2 header on the bottom, making it quite annoying to use on another shield.

PCB Topside
PCB Bottom side

Manufacturing

This shield is currently being manufactured by PCBWay.

PCBWay provides a rapid and affordable PCB manufacturing service. They also provide PCB assembly, and even a 3D printing and CNC service. This can really help to bring new electronic prototypes to market quickly, as PCBWay can provide you with a complete turn-key solution to bring your product to market. The process to order a PCB is also completely automated, and you can easily do it online in a few minutes. Just upload your completed Gerber Files onto their system via their web interface, and you will get a quote in seconds. You can then pay and place your order immediately from the same page. They also have various shipping methods available, That really helps, as no one wants to pay for excessively expensive shipping, or be stuck having to use only one company.

The design files for this project will be made available as a project on the PCBWay website soon after the release of part 3, which will cover the assemble, testing and programming of the shield.

An Exiting new IDE for Micro Controllers

A few months ago, I was approached by one of the Embeetle team members, to give some feedback on a new IDE that they were working on. I decided to do that, and what a good decision it was… I am not your average developer, and as such, doesn’t spend a lot of my time on fancy IDE software. I rather focus on getting things done… I have been outgrowing the popular Arduino IDE for a long time now, as it is quite limiting in some areas, but stuck to it, as it sort of still serves a purpose in my style of development…

Embeetle changed that outlook completely, and I was hooked almost immediately. Working closely with the development team over the last few months to add Arduino support to Embeetle was also extremely rewarding, especially being able to use bleeding edge software, and actively participating in helping find bugs and discussing new ways to implement new features.

The support team is great, and bugs gets fixed extremely fast, only one advantage of a small dedicated team of programmers, that are focused on quality…

With the now public release of Embeetle, with Arduino Support, a brand new serial monitor, and also a very intuitive library manager, I really hope that more users will give this new IDE a try and hopefully, like me, become hooked and stay with it in the long run…

https://www.embeetle.com/#home

What is LoRa?

Introduction

When designing IoT solutions, we all encounter the problem of connecting our device(s) to each other, either directly, or through the internet. In Urban areas, it is quite easy to use WiFi or even GSM to achieve this, but these solutions often come with additional costs in the form of subscriptions. Although it is possible to run your own WiFi network free of charge, you will soon run into issues with the range…

Enter LoRa (short for Long Range) Radio communication. LoRa is a radio technology derived from chirp spread spectrum technology. It uses an ISM band, meaning it is unregulated in most countries, if you use the correct frequency for your country, that is.

It is also extremely low power, making it ideal for use with battery-powered devices.
The technology is available in Node-to-Node, as well as Node-to -Gateway modes.

In this series, I will show you how to use a few of the existing LoRa Modules available on the market.

Ai-Tinker Ra-02 (Sx1278)

Ra-02 Lora Module, with spring antenna, by Ai-Tinker

This Module is conveniently broken-out onto a breakout board. It is sort of bread-board friendly (depending on the size of your bread-board) and is nicely labelled. It is also extremely cheap ( around $USD5 each, depending on where you buy from).

Caveats

There are quite a few important things that you should know about these modules before you start using them.

Disclaimer: The caveats listed below are by no means complete, or even valid. They are the result of experimentation by myself, with the intent to destroy a few modules, to see how hardy they are. Also take into mind, that living in SE Asia, it is quite common to buy something from a shop, where the seller has no or only a very limited idea of what he or she is selling, and are thus usually quite unable to provide any technical support.

To summarise: USE YOUR HEAD. If I did leave out something, it is quite possible that I forgot, or decided not to include it on purpose. This is a general guide, and you should ideally do your own research as well. That is the best way to learn.



1) Always connect an Antenna. This may seem like a logical one, but it is extremely important. The module is capable of quite a lot of transmission power, and operating it without an antenna will quickly damage the module, permanently.

2) ONLY use 3.3v, even on the control lines (the module uses SPI). This is quite important, as it is not very clearly stated by the suppliers, and will result in very short-lived component operation 😉 If you absolutely have to use 5v, use a level converter. (There are examples available on the internet, where they use this chip directly from an Arduino Uno. I can confirm that that approach does work, BUT, not for very long. I have purposely sacrificed a pair of transceiver modules so that you don’t have to. You can also adjust the SPI frequency, in the event that your level converter is not capable of running at a high SPI frequency.

3)Make sure that you connect ALL the ground pins on the device. This is another area that is not fully explained by the user manual and does “unexplainably” result in damaged modules.

4) Use short, good quality cables, and if possible, keep the module off the breadboard.
While testing the modules, I found that the usual DuPont wires, as everyone should know by now, are quite unreliable. Combine that with a bread-board that has seen its share of use,
and it is a definite recipe for headache 🙂

5) LoRa Antennas are polarised, make sure you have your antennas in the same orientation.
Although this will not prevent it from working over short distances, it makes sense to just do it correctly. Good RF practices never hurt anybody 🙂

Connecting to Arduino

A Note on Power:
It is important to power this module from a decent dedicated 3.3v power-supply.
The Arduino Uno does sometimes have a 3.3v regulator on-board. From my tests, it is however not always up to the task, as the module may spike up to 120mA when transmitting. It is thus also recommended to have a nice fat capacitor across the power lines (decoupling cap) to soak up any spikes.

As mentioned above, a level converter is mandatory for a 5v Arduino. You may do without it if you use a 3.3v Arduino, but once again, your mileage will vary 🙂

Both the transmitter and receiver uses the same connections, which are listed below:

LoRa SX1278 ModuleArduino Board
3.3V
GndGnd
En/NssD10
G0/DIO0D2
SCKD13
MISOD12
MOSID11
RSTD9
Connections to the Arduino from a LoRa RA-02 Module

Remember that you NEED a Level converter between the LoRa Module and the Arduino.

Software Library

The software library that we will use in our example is the excellent library from Sandeep Mistry. We will just include this into the Arduino IDE, and then use a slightly modified version of the examples for our experiment. It is also important to note that we will use Node-to Node communication, NOT LoRaWan. This means that all your communications will essentially be unencrypted, and not addressed. This does however allow you the flexibility to design and implement your own addressing scheme.

LORA code for Transmitting Side

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

int counter = 0;

void setup() {
  Serial.begin(115200);
  while (!Serial);

  Serial.println("LoRa Sender");

  if (!LoRa.begin(433E6)) { // Set the frequency to that of your  //module. Mine uses 433Mhz, thus I have set it to 433E6
    Serial.println("Starting LoRa failed!");
    while (1);
  }

  LoRa.setTxPower(20);
  
}

void loop() {
  Serial.print("Sending packet: ");
  Serial.println(counter);

  // send packet
  LoRa.beginPacket();
  LoRa.print("hello ");
  LoRa.print(counter);
  LoRa.endPacket();

  counter++;

  delay(5000);
}
LORA code for Receiver Side

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

void setup() {
  Serial.begin(115200);
  while (!Serial);

  Serial.println("LoRa Receiver");

  if (!LoRa.begin(433E6)) {
    Serial.println("Starting LoRa failed!");
    while (1);
  }
}

void loop() {
  // try to parse packet
  int packetSize = LoRa.parsePacket();
  if (packetSize) {
    // received a packet
    Serial.print("Received packet '");

    // read packet
    while (LoRa.available()) {
      Serial.print((char)LoRa.read());
    }

    // print RSSI of packet
    Serial.print("' with RSSI ");
    Serial.println(LoRa.packetRssi());
  }
}

Where to from here?

If all went well, you will see packets being received in the serial monitor of the Arduino IDE, connected to the receiver module. You will also see that the data from this example is sent as a string… It is however also possible to send binary data, by using the LoRa.write() function.

In the next part of this series, I will show you how to use LoRa with the ESP32/ESP8266,
as well as a working example with binary data transmission and an addressing scheme in part 3.

Thank you

Using the MCP23017 to increase your GPIO’s

Today I will show you another useful IO Expander chip, The MCP23017. This chip, although similar to the PCF8475, which I have already covered in a previous article, has many additional features that may make it a very attractive solution when you need some more extra GPIO pins for a big project…

Features

Let us look at some of the features of this chip

  • 16-Bit Remote Bidirectional I/O Port:
  • I/O pins default to input
    • High-Speed I2C Interface (MCP23017):
  • 100 kHz
  • 400 kHz
  • 1.7 MHz
    • High-Speed SPI Interface (MCP23S17):
  • 10 MHz (maximum)
    • Three Hardware Address Pins to Allow Up to
    Eight Devices On the Bus
    • Configurable Interrupt Output Pins:
  • Configurable as active-high, active-low or
    open-drain
    • INTA and INTB Can Be Configured to Operate
    Independently or Together
    • Configurable Interrupt Source:
  • Interrupt-on-change from configured register
    defaults or pin changes
    • Polarity Inversion Register to Configure the
    Polarity of the Input Port Data
    • External Reset Input
    • Low Standby Current: 1 µA (max.)
    • Operating Voltage:
  • 1.8V to 5.5V @ -40°C to +85°C
  • 2.7V to 5.5V @ -40°C to +85°C
  • 4.5V to 5.5V @ -40°C to +125°C
MCP23017 Pinout Diagram

The sixteen I/O ports are separated into two ‘ports’ – A (on the right) and B (on the left. Pin 9 connects to 5V, 10 to GND, 11 isn’t used, 12 is the I2C bus clock line (Arduino Uno/Duemilanove analogue pin 5, Mega pin  21), and 13 is the I2C bus data line (Arduino Uno/Duemailnove analogue pin 4, Mega pin 20).

External pull-up resistors should be used on the I2C bus – in our examples we use 4.7k ohm values. Pin 14 is unused, and we won’t be looking at interrupts, so ignore pins 19 and 20. Pin 18 is the reset pin, which is normally high – therefore you ground it to reset the IC. So connect it to 5V!

Finally we have the three hardware address pins 15~17. These are used to determine the I2C bus address for the chip. If you connect them all to GND, the address is 0x20. If you have other devices with that address or need to use multiple MCP23017s, see figure 1-2 in the datasheet.

You can alter the address by connecting a combination of pins 15~17 to 5V (1) or GND (0). For example, if you connect 15~17 all to 5V, the control byte becomes 0100111 in binary, or 0x27 in hexadecimal.

It is also available on a convenient breakout PCB, for about $USD0.80 from AliExpress

MCP23017 on Breakout PCB – Back
MCP23017 on Breakout PCB – Front

Please Note: THIS BREAKOUT PCB IS NOT SUITED FOR USE ON A BREADBOARD. YOU WILL SHORT OUT VCC AND GROUND AS WELL AS ALL THE IO PINS IF YOU TRY TO USE IT ON A BREADBOARD.

As you can see, the pins are however very clearly labelled, and thus easy to use. I have also purposely soldered my header pins “the wrong way round” to prevent using it on a breadboard, as this will short out Vcc to Ground!

Having interrupt outputs is one of the most important features of the MCP23017, since the microcontroller does not have to continuously poll the device to detect an input change. Instead an interrupt service routine can be used to react quickly to an input change such a key press…

To make life even easier each GPIO input pin can be configured with an internal pullup (~100k) and that means you won’t have to wire up external pull up resistors for keyboard input. You can also mix and match inputs and outputs the same as any standard microcontroller 8 bit port.

Addressing

The 23017 has three input pins to allow you to set a different address for each attached MCP23017.

The above corresponds to a hardware address for the three lines A0, A1, A2 corresponding to the input pin values at the IC. You must set the value of these hardware inputs as 0V or (high) volts and not leave them floating otherwise they will get random values from electrical noise and the chip will do nothing!

The four left most bits are fixed a 0100 (specified by a consortium who doles out address ranges to manufacturers).

So the MCP23017 I2C address range is 32 decimal to 37 decimal or 0x20 to 0x27 for the MCP23017.

Please note: The addresses are the same as those for the PCF8475. You must thus be careful if you use these two devices on the same i2c bus!

MCP23017 Non interrupt registers

IODIR I/O direction register

For controlling I/O direction of each pin, register IODIR (A/B) lets you set the pin to an output when a zero is written and to an input when a ‘1’ is written to the register bit. This is the same scheme for most microcontrollers – the key is to remember that zero (‘0’) equates to the ‘O’ in Output.

GPPU Pullup register

Setting a bit high sets the pullup active for the corresponding I/O pin.

OLAT Output Latch register

This is exactly the same as the I/O port in 18F series PIC chips where you can read back the “desired” output of a port pin whether or not the actual state of that pin is reached. i.e. consider a strong current LED attached to the pin – it is easily possible to pull down the output voltage at the pin to below the logic threshold i.e. you would read back a zero if reading from the pin itself when in fact it should be a one. Reading the OLAT register bit returns a ‘one’ as you would expect from a software engineering point of view.

IPOL pin inversion register

The IPOL(A/B) register allows you to selectively invert any input pin. This reduces the glue logic needed to interface other devices to the MCP23017 since you won’t need to add inverter logic chips to get the correct signal polarity into the MCP23017.

It is also very handy for getting the signals the right way up e.g. it is common to use a pull up resistor for an input so when a user presses an input key the voltage input is zero, so in software you have to remember to test for zero.

Using the MCP23017 you could invert that input and test for a 1 (in my mind a key press is more equivalent to an on state i.e. a ‘1’) however I use pullups all the time (and uCs in general use internal pullups when enabled) so have to put up with a zero as ‘pressed’. Using this device would allow you to correct this easily.Note: The reason that active low signals are used everywhere is a historical one: TTL (Transistor Transistor Logic) devices draw more power in the active low state due to the internal circuitry, and it was important to reduce unnecessary power consumption – therefore signals that are inactive most of the time e.g. a chip select signal – were defined to be high. With CMOS devices either state causes the same power usage so it now does not matter – however active low is used because everyone uses it now and used it in the past.

SEQOP polling mode : register bit : (Within IOCON register)

If you have a design that has critical interrupt code e.g. for performing a timing critical measurement you may not want non critical inputs to generate an interrupt i.e. you reserve the interrupt for the most important input data.

In this case, it may make more sense to allow polling of some of the device inputs. To facilitate this “Byte mode” is provided. In this mode, you can read the same set of GPIOs using clocks but not needling to provide other control information. i.e. it stays on the same set of GPIO bits, and you can continuously read it without the register-address updating itself. In non-byte mode, you either have to set the address you read from (A or B bank) as control input data.

Now to examine how to use the IC in our sketches.

As you should know by now most I2C devices have several registers that can be addressed. Each address holds one byte of data that determines various options. So before using we need to set whether each port is an input or an output. First, we’ll examine setting them as outputs. So to set port A to outputs, we use:

Wire.beginTransmission(0x20);
Wire.write(0x00); // IODIRA register
Wire.write(0x00); // set all of port A to outputs
Wire.endTransmission();

Then to set port B to outputs, we use:

Wire.beginTransmission(0x20);
Wire.write(0x01); // IODIRB register
Wire.write(0x00); // set all of port B to outputs
Wire.endTransmission();

So now we are in void loop()  or a function of your own creation and want to control some output pins. To control port A, we use:

Wire.beginTransmission(0x20);
Wire.write(0x12); // address port A
Wire.write(??);  // value to send
Wire.endTransmission();

To control port B, we use:

Wire.beginTransmission(0x20);
Wire.write(0x13); // address port B
Wire.write(??);  // value to send
Wire.endTransmission();

… replacing ?? with the binary or equivalent hexadecimal or decimal value to send to the register.

To calculate the required number, consider each I/O pin from 7 to 0 matches one bit of a binary number – 1 for on, 0 for off. So you can insert a binary number representing the status of each output pin. Or if binary does your head in, convert it to hexadecimal. Or a decimal number.

So for example, you want pins 7 and 1 on. In binary that would be 10000010, in hexadecimal that is 0x82, or 130 decimal. (Using decimals is convenient if you want to display values from an incrementing value or function result).

For example, we want port A to be 11001100 and port B to be 10001000 – so we send the following (note we converted the binary values to decimal):

Wire.beginTransmission(0x20);
Wire.write(0x12); // address port A
Wire.write(204); // value to send
Wire.endTransmission();
Wire.beginTransmission(0x20);
Wire.write(0x13); // address port B 
Wire.write(136);     // value to send
Wire.endTransmission();

A complete Example

// pins 15~17 to GND, I2C bus address is 0x20
#include "Wire.h"
void setup()
{
 Wire.begin(); // wake up I2C bus
// set I/O pins to outputs
 Wire.beginTransmission(0x20);
 Wire.write(0x00); // IODIRA register
 Wire.write(0x00); // set all of port A to outputs
 Wire.endTransmission();
Wire.beginTransmission(0x20);
 Wire.write(0x01); // IODIRB register
 Wire.write(0x00); // set all of port B to outputs
 Wire.endTransmission();
}
void binaryCount()
{
 for (byte a=0; a<256; a++)
 {
 Wire.beginTransmission(0x20);
 Wire.write(0x12); // GPIOA
 Wire.write(a); // port A
 Wire.endTransmission();
Wire.beginTransmission(0x20);
 Wire.write(0x13); // GPIOB
 Wire.write(a); // port B
 Wire.endTransmission();
 }
}
void loop()
{
 binaryCount();
 delay(500);
}

Using the pins as inputs

Although that may have seemed like a simple demonstration, it was created show how the outputs can be used. So now you know how to control the I/O pins set as outputs. Note that you can’t source more than 25 mA of current from each pin, so if switching higher current loads use a transistor and an external power supply and so on.

Now let’s turn the tables and work on using the I/O pins as digital inputs. The MCP23017 I/O pins default to input mode, so we just need to initiate the I2C bus. Then in the void loop() or other function all we do is set the address of the register to read and receive one byte of data.

// pins 15~17 to GND, I2C bus address is 0x20
#include "Wire.h"
byte inputs=0;
void setup()
{
 Serial.begin(9600);
 Wire.begin(); // wake up I2C bus
}
void loop()
{
 Wire.beginTransmission(0x20);
 Wire.write(0x13); // set MCP23017 memory pointer to GPIOB address
 Wire.endTransmission();
 Wire.requestFrom(0x20, 1); // request one byte of data from MCP20317
 inputs=Wire.read(); // store the incoming byte into "inputs"
 if (inputs>0) // if a button was pressed
 {
 Serial.println(inputs, BIN); // display the contents of the GPIOB register in binary
 delay(200); // for debounce
 }
}

Other Libraries

You can also download and install the MCP23017 Library from Adafruit for the Arduino IDE.
This library will make using this chip even easier… I will discuss this library in another post

I hope this will be useful to somebody.

Using I2C with a 4×4 Matrix Keypad

Using a matrix keypad is a very easy way to add multiple control buttons to a project, be it to enter a password, or to control different devices. These keypads do unfortunately have some serious flaws (in my view anyway)

1) They are usually of extremely low quality ( especially some of the membrane types from China). This means they dont last very long.
2) A typical 4×4 Matrix keypad will require 8 of your precious IO pins for itself.

These two flaws can however easily be solved, if we use a bit of technology, and are willing to to a bit of simple circuit construction by ourselves.

What does this mean ? Most of us makers will inevitably have a piece of proto-board or strip-board lying around, as well as a few momentary push-button switches. These can easily be used to make out own, much more reliable keypad. Let us look at the circuit

Circuit diagram for a 4×4 Matrix Keypad

As we can see, to build a 4×4 matrix keypad, we will need 16 momentary switches. These are connected together as shown above. You can then interface it with your favourite micro-controller to read the key(s) pressed…

This definitely solves the first of my problems, but we still need 8 pins to control this keypad… or do we? No, we don’t, we need only 2 pins. That is to say if we use one of those PCF8574 I2C IO port expander modules. They are much more reliable, as well as quite cheap as well. all depending on where you buy them from, and how long you are willing to wait for shipping 🙂

Let us see how to connect the keypad to the I2C Module

a 4×4 Membrane Matrix Keypad with PCF8574 I2C port expander module
Connecting the two together, note that we do not connect the INT pin
Connect Power (VCC, GND and I2C lines
Connect to Arduino or your preferred microcontroller. We have used Arduino Uno, Note that you can also connect the I2C to A4 (SDA) and A5(SCL) if you prefer.

Now, we need to install some libraries

The first one is the actual Keypad library, you can download it from the link below

The second library that we will need, is the keypad_i2c library, once again, download it from the link below.

Coding the keypad



#include <Key.h>
#include <Keypad.h>
#include <Keypad_I2C.h>

#define I2CADDR 0x26 // Set the Address of the PCF8574

const byte ROWS = 4; // Set the number of Rows
const byte COLS = 4; // Set the number of Columns

// Set the Key at Use (4x4)
char keys [ROWS] [COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

// define active Pin (4x4)
byte rowPins [ROWS] = {0, 1, 2, 3}; // Connect to Keyboard Row Pin
byte colPins [COLS] = {4, 5, 6, 7}; // Connect to Pin column of keypad.

// makeKeymap (keys): Define Keymap
// rowPins:Set Pin to Keyboard Row
// colPins: Set Pin Column of Keypad
// ROWS: Set Number of Rows.
// COLS: Set the number of Columns
// I2CADDR: Set the Address for i2C
// PCF8574: Set the number IC
Keypad_I2C keypad (makeKeymap (keys), rowPins, colPins, ROWS, COLS, I2CADDR, PCF8574);

void setup () {
  Wire .begin (); // Call the connection Wire
  keypad.begin (makeKeymap (keys)); // Call the connection
  Serial.begin (9600);

}
void loop () {
 
  char key = keypad.getKey (); // Create a variable named key of type char to hold the characters pressed
 
  if (key) {// if the key variable contains
    Serial.println (key); // output characters from Serial Monitor
  }
}

Upload this to your Arduino device and enjoy. This sketch can also be adapted for 1×4, and 4×3 keypads, and with a little modification, will also work perfectly on ESP32 or ESP8266 as well…

What is SPI? Serial Peripheral Interface – Part 1

Introduction

The Serial Peripheral Interface is a synchronous serial communication interface for short-distance communication, it is typically used in embedded systems. The interface was developed by Motorola in the mid 1980’s and has become a very popular standard.

It is used with many kinds of sensors, LCD’s and also SD-Cards. SPI operates in a Master-Slave model, with a possibility of multiple slave devices, each selected in turn by a SS (slave select) or CS (chip select) pin that is usually pulled low by the master.

Typical connection between two SPI devices

Typical configuration

SPI is a four-wire interface, with the different lines being
– MOSI [Master Out Slave In]
-MISO [Master In Slave Out]
-SCLK [Serial Clock OUT – generated by the master]
-SS/CS [Slave Select or Chip Select, sometimes also labelled CE – Chip Enable]

SPI is a FULL DUPLEX interface, where the master initiates the communication frames between the various slave devices. This is usually done by pulling the particular device’s SS/CS pin low. Data is then shifted simultaneously into and out of the devices by means of the MOSI and MISO lines on the bus. The frequency of the serially shifted data is controlled by the SCLK line. This clock signal is generated by the master device.

It is important to note that MOST of the slave devices have a tri-state (HIGH IMPEDANCE) mode on their MISO pins. This electrically disconnects the MISO pin from the bus when the device is not selected via the SS/CS pin.

You should also note the SPI slave devices that do not have a tri-state mode on their MISO pins, should not be used on the same bus as devices that have without using an external tri-state buffer circuit between the non-tristate device and the rest of the devices on the MISO bus.

Typical connection between an SPI Master and three Slave devices


It is possible to connect multiple SPI slave devices to on Master device if you remember that each slave device will need its own dedicated SS/CS pin on the master. This can however quickly use a lot of IO pins on a microcontroller, thus being one of the disadvantages of SPI versus I2C. SPI is however quite a bit faster than I2C.

Data Transmission

To begin communication, the bus master configures the clock, using a frequency supported by the slave device, typically up to a few MHz. The master then selects the slave device with a logic level 0 on the select line. If a waiting period is required, such as for an analog-to-digital conversion, the master must wait for at least that period of time before issuing clock cycles.

During each SPI clock cycle, full-duplex data transmission occurs. The master sends a bit on the MOSI line and the slave reads it, while the slave sends a bit on the MISO line and the master reads it. This sequence is maintained even when only one-directional data transfer is intended.

A typical hardware setup using two shift registers to form an inter-chip circular buffer

Transmissions normally involve two shift registers of some given word-size, such as eight bits, one in the master and one in the slave; they are connected in a virtual ring topology. Data is usually shifted out with the most significant bit first. On the clock edge, both master and slave shift out a bit and output it on the transmission line to the counterpart. On the next clock edge, at each receiver the bit is sampled from the transmission line and set as a new least-significant bit of the shift register. After the register bits have been shifted out and in, the master and slave have exchanged register values. If more data needs to be exchanged, the shift registers are reloaded and the process repeats. Transmission may continue for any number of clock cycles. When complete, the master stops toggling the clock signal, and typically deselects the slave.

Transmissions often consist of eight-bit words. However, other word-sizes are also common, for example, sixteen-bit words for touch-screen controllers or audio codecs, such as the TSC2101 by Texas Instruments, or twelve-bit words for many digital-to-analogue or analogue-to-digital converters.

Every slave on the bus that has not been activated using its chip select line must disregard the input clock and MOSI signals and should not drive MISO (I.E. must have a tri-state output) although some devices need external tri-state buffers to implement this.

Clock polarity and phasing

In addition to setting the clock frequency, the master must also configure the clock polarity and phase with respect to the data. Motorola SPI Block Guide names these two options as CPOL and CPHA (for clock polarity and phase) respectively, a convention most vendors have also adopted.

The timing diagram is shown below. The timing is further described below and applies to both the master and the slave device.

  • CPOL determines the polarity of the clock. The polarities can be converted with a simple inverter.
  • CPOL=0 is a clock which idles at 0, and each cycle consists of a pulse of 1. That is, the leading edge is a rising edge, and the trailing edge is a falling edge.
  • CPOL=1 is a clock which idles at 1, and each cycle consists of a pulse of 0. That is, the leading edge is a falling edge, and the trailing edge is a rising edge.
  • CPHA determines the timing (i.e. phase) of the data bits relative to the clock pulses. Conversion between these two forms is non-trivial.
  • For CPHA=0, the “out” side changes the data on the trailing edge of the preceding clock cycle, while the “in” side captures the data on (or shortly after) the leading edge of the clock cycle. The out-side holds the data valid until the trailing edge of the current clock cycle. For the first cycle, the first bit must be on the MOSI line before the leading clock edge.
  • An alternative way of considering it is to say that a CPHA=0 cycle consists of a half cycle with the clock idle, followed by a half cycle with the clock asserted.
  • For CPHA=1, the “out” side changes the data on the leading edge of the current clock cycle, while the “in” side captures the data on (or shortly after) the trailing edge of the clock cycle. The out-side holds the data valid until the leading edge of the following clock cycle. For the last cycle, the slave holds the MISO line valid until slave select is de-selected.
  • An alternative way of considering it is to say that a CPHA=1 cycle consists of a half cycle with the clock asserted, followed by a half cycle with the clock idle.
A timing diagram showing clock polarity and phase. Red lines denote clock leading edges, and blue lines, trailing edges.

The MOSI and MISO signals are usually stable (at their reception points) for the half cycle until the next clock transition. SPI master and slave devices may well sample data at different points in that half cycle.

This adds more flexibility to the communication channel between the master and slave.

Mode numbers

The combinations of polarity and phases are often referred to as modes which are commonly numbered according to the following convention, with CPOL as the high order bit and CPHA as the low order bit:

For “Microchip PIC” / “ARM-based” microcontrollers (note that NCPHA is the inversion of CPHA):

SPI modeClock polarity
(CPOL/CKP)
Clock phase
(CPHA)
Clock edge
(CKE/NCPHA)
0001
1010
2101
3110
For PIC32MX: SPI mode configure CKP, CKE and SMP bits. Set SMP bit and CKP, CKE two bits configured as above table.
ModeCPOLCPHA
000
101
210
311
For other microcontrollers:

Another commonly used notation represents the mode as a (CPOL, CPHA) tuple; e.g., the value ‘(0, 1)’ would indicate CPOL=0 and CPHA=1.

Note that in Full Duplex operation, the Master device could transmit and receive with different modes. For instance, it could transmit in Mode 0 and be receiving in Mode 1 at the same time.

Independent Slave Configuration

In the independent slave configuration, there is an independent chip select line for each slave. This is the way SPI is normally used. The master asserts only one chip select at a time.

Pull-up resistors between the power source and chip select lines are recommended for systems where the master’s chip select pins may default to an undefined state. When separate software routines initialize each chip select and communicate with its slave, pull-up resistors prevent other uninitialized slaves from responding.

Since the MISO pins of the slaves are connected together, they are required to be tri-state pins (high, low or high-impedance), where the high-impedance output must be applied when the slave is not selected. Slave devices not supporting tri-state may be used in independent slave configuration by adding a tri-state buffer chip controlled by the chip select signal. (Since only a single signal line needs to be tri-stated per slave, one typical standard logic chip that contains four tristate buffers with independent gate inputs can be used to interface up to four slave devices to an SPI bus.)

Typical SPI configuration

Daisy chain configuration

Some products that implement SPI may be connected in a daisy chain configuration, the first slave output being connected to the second slave input, etc. The SPI port of each slave is designed to send out during the second group of clock pulses an exact copy of the data it received during the first group of clock pulses. The whole chain acts as a communication shift register; daisy chaining is often done with shift registers to provide a bank of inputs or outputs through SPI. Each slave copies input to output in the next clock cycle until the active low SS line goes high. Such a feature only requires a single SS line from the master, rather than a separate SS line for each slave.

Note that not all SPI devices support this. You should thus check your datasheet before using this configuration!

SPI Daisy Chain configuration

Valid Communications

Some slave devices are designed to ignore any SPI communications in which the number of clock pulses is greater than specified. Others do not care, ignoring extra inputs and continuing to shift the same output bit. It is common for different devices to use SPI communications with different lengths, as, for example, when SPI is used to access the scan chain of a digital IC by issuing a command word of one size (perhaps 32 bits) and then getting a response of a different size (perhaps 153 bits, one for each pin in that scan chain).

Interrupts

SPI devices sometimes use another signal line to send an interrupt signal to a host CPU. Examples include pen-down interrupts from touchscreen sensors, thermal limit alerts from temperature sensors, alarms issued by real-time clock chips, SDIO, and headset jack insertions from the sound codec in a cell phone. Interrupts are not covered by the SPI standard; their usage is neither forbidden nor specified by the standard. In other words, interrupts are outside the scope of the SPI standard and are optionally implemented independently from it.

Bit Banging a SPI Master – Example code

Below is an example of bit-banging the SPI protocol as an SPI master with CPOL=0, CPHA=0, and eight bits per transfer. The example is written in the C programming language. Because this is CPOL=0 the clock must be pulled low before the chip select is activated. The chip select line must be activated, which normally means being toggled low, for the peripheral before the start of the transfer, and then deactivated afterwards. Most peripherals allow or require several transfers while the select line is low; this routine might be called several times before deselecting the chip.

/*
 * Simultaneously transmit and receive a byte on the SPI.
 *
 * Polarity and phase are assumed to be both 0, i.e.:
 *   - input data is captured on rising edge of SCLK.
 *   - output data is propagated on falling edge of SCLK.
 *
 * Returns the received byte.
 */
uint8_t SPI_transfer_byte(uint8_t byte_out)
{
    uint8_t byte_in = 0;
    uint8_t bit;

    for (bit = 0x80; bit; bit >>= 1) {
        /* Shift-out a bit to the MOSI line */
        write_MOSI((byte_out & bit) ? HIGH : LOW);

        /* Delay for at least the peer's setup time */
        delay(SPI_SCLK_LOW_TIME);

        /* Pull the clock line high */
        write_SCLK(HIGH);

        /* Shift-in a bit from the MISO line */
        if (read_MISO() == HIGH)
            byte_in |= bit;

        /* Delay for at least the peer's hold time */
        delay(SPI_SCLK_HIGH_TIME);

        /* Pull the clock line low */
        write_SCLK(LOW);
    }

    return byte_in;
}

This concludes part 1 of my series on SPI. I hope you found it interesting and useful.

The OLED Display

Introduction

Adding a display to any project can instantly increase its visual appeal, as well as make the project easier to control. Displays available to Electronic enthusiasts mostly include some sort of LCD or even TFT display. LCD displays are usually bulky and very limited in their ability to display a lot of information, whereas TFT type displays are still a bit on the expensive side, and not very easy to interface with for the beginner.

Today, I would like to introduce a different type of display, which is available in an I2C as well as SPI version. These displays are very easily readable in almost any light conditions, lightweight, and most importantly, they are extremely cheap. I am talking about the OLED display of course… Many of us may already have one of them in our mobile phones, or even TV screen…

128×32 I2C OLED Display (40mmx10mm) [0.91″] Front view

Some Technical Data

An organic light-emitting diode (OLED or Organic LED), also known as an organic EL (organic electroluminescent) diode,[1][2] is a light-emitting diode (LED) in which the emissive electroluminescent layer is a film of organic compound that emits light in response to an electric current. This organic layer is situated between two electrodes; typically, at least one of these electrodes is transparent. OLEDs are used to create digital displays in devices such as television screens, computer monitors, portable systems such as smartphoneshandheld game consoles and PDAs. A major area of research is the development of white OLED devices for use in solid-state lighting applications.[3][4][5]

There are two main families of OLED: those based on small molecules and those employing polymers. Adding mobile ions to an OLED creates a light-emitting electrochemical cell (LEC) which has a slightly different mode of operation. An OLED display can be driven with a passive-matrix (PMOLED) or active-matrix (AMOLED) control scheme. In the PMOLED scheme, each row (and line) in the display is controlled sequentially, one by one,[6] whereas AMOLED control uses a thin-film transistor backplane to directly access and switch each individual pixel on or off, allowing for higher resolution and larger display sizes.

An OLED display works without a backlight because it emits visible light. Thus, it can display deep black levels and can be thinner and lighter than a liquid crystal display (LCD). In low ambient light conditions (such as a dark room), an OLED screen can achieve a higher contrast ratio than an LCD, regardless of whether the LCD uses cold cathode fluorescent lamps or an LED backlight. OLED displays are made in the same way as LCDs, but after TFT (for active matrix displays), addressable grid (for passive matrix displays) or ITO segment (for segment displays) formation, the display is coated with hole injection, transport and blocking layers, as well with electroluminescent material after the 2 first layers, after which ITO or metal may be applied again as a cathode and later the entire stack of materials is encapsulated. The TFT layer, addressable grid or ITO segments serve as or are connected to the anode, which may be made of ITO or metal.[7][8] OLEDs can be made flexible and transparent, with transparent displays being used in smartphones with optical fingerprint scanners and flexible displays being used in foldable smartphones.

The full article is available here if you are interested.

128×32 I2C OLED Display (40mmx10mm) [0.91″] Back view

Connecting the circuit

This display is once again extremely easy to connect, as it uses the very versatile I2C protocol. (An SPI version is also available).

Connecting 128×32 OLED display to an Arduino Uno Clone

Connect the following wires to the Arduino / ESP32
+5v (red) to the VCC pin on the display
Gnd to Gnd
SDA (A4 on Uno) to SDA, and SCL (A5 on Uno) to SCL

The Software Libraries

The 128×32 OLED display that we will be using today, is based on the SSD1306. We will thus be using a library suplied by Adafruit to interface with this chip. There are various other libraries available, but I have found the Adafruit library the most stable.

To load this, start by opening the Arduino IDE, and go to the Sketch->Include Library->Manage Libraries option on the menu

The Library Manager will now open

We need to install two (2) Libraries

– Adafruit GFX ( this is for graphics)
– Adafruit SSD1306 ( to control the actual display )

Click on “Close” after installation is completed.

Using the display

We will use one of the standard Adafruit examples to show you the capabilities of the tiny little screen. The example are so straight forward to use, that I find it unnecessary to say anything else about it 🙂

Open the ssd1306_128x32_ic2 Example from the Examples menu in the Arduino IDE and upload it to your Arduino, making sure that you set the dimensions of your screen first (in my case 128×32 )

/**************************************************************************
 This is an example for our Monochrome OLEDs based on SSD1306 drivers

 Pick one up today in the adafruit shop!
 ------> http://www.adafruit.com/category/63_98

 This example is for a 128x32 pixel display using I2C to communicate
 3 pins are required to interface (two I2C and one reset).

 Adafruit invests time and resources providing this open
 source code, please support Adafruit and open-source
 hardware by purchasing products from Adafruit!

 Written by Limor Fried/Ladyada for Adafruit Industries,
 with contributions from the open source community.
 BSD license, check license.txt for more information
 All text above, and the splash screen below must be
 included in any redistribution.
 **************************************************************************/

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

#define NUMFLAKES     10 // Number of snowflakes in the animation example

#define LOGO_HEIGHT   16
#define LOGO_WIDTH    16
static const unsigned char PROGMEM logo_bmp[] =
{ B00000000, B11000000,
  B00000001, B11000000,
  B00000001, B11000000,
  B00000011, B11100000,
  B11110011, B11100000,
  B11111110, B11111000,
  B01111110, B11111111,
  B00110011, B10011111,
  B00011111, B11111100,
  B00001101, B01110000,
  B00011011, B10100000,
  B00111111, B11100000,
  B00111111, B11110000,
  B01111100, B11110000,
  B01110000, B01110000,
  B00000000, B00110000 };

void setup() {
  Serial.begin(9600);

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

  // Show initial display buffer contents on the screen --
  // the library initializes this with an Adafruit splash screen.
  display.display();
  delay(2000); // Pause for 2 seconds

  // Clear the buffer
  display.clearDisplay();

  // Draw a single pixel in white
  display.drawPixel(10, 10, SSD1306_WHITE);

  // Show the display buffer on the screen. You MUST call display() after
  // drawing commands to make them visible on screen!
  display.display();
  delay(2000);
  // display.display() is NOT necessary after every single drawing command,
  // unless that's what you want...rather, you can batch up a bunch of
  // drawing operations and then update the screen all at once by calling
  // display.display(). These examples demonstrate both approaches...

  testdrawline();      // Draw many lines

  testdrawrect();      // Draw rectangles (outlines)

  testfillrect();      // Draw rectangles (filled)

  testdrawcircle();    // Draw circles (outlines)

  testfillcircle();    // Draw circles (filled)

  testdrawroundrect(); // Draw rounded rectangles (outlines)

  testfillroundrect(); // Draw rounded rectangles (filled)

  testdrawtriangle();  // Draw triangles (outlines)

  testfilltriangle();  // Draw triangles (filled)

  testdrawchar();      // Draw characters of the default font

  testdrawstyles();    // Draw 'stylized' characters

  testscrolltext();    // Draw scrolling text

  testdrawbitmap();    // Draw a small bitmap image

  // Invert and restore display, pausing in-between
  display.invertDisplay(true);
  delay(1000);
  display.invertDisplay(false);
  delay(1000);

  testanimate(logo_bmp, LOGO_WIDTH, LOGO_HEIGHT); // Animate bitmaps
}

void loop() {
}

void testdrawline() {
  int16_t i;

  display.clearDisplay(); // Clear display buffer

  for(i=0; i<display.width(); i+=4) {
    display.drawLine(0, 0, i, display.height()-1, SSD1306_WHITE);
    display.display(); // Update screen with each newly-drawn line
    delay(1);
  }
  for(i=0; i<display.height(); i+=4) {
    display.drawLine(0, 0, display.width()-1, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  delay(250);

  display.clearDisplay();

  for(i=0; i<display.width(); i+=4) {
    display.drawLine(0, display.height()-1, i, 0, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  for(i=display.height()-1; i>=0; i-=4) {
    display.drawLine(0, display.height()-1, display.width()-1, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  delay(250);

  display.clearDisplay();

  for(i=display.width()-1; i>=0; i-=4) {
    display.drawLine(display.width()-1, display.height()-1, i, 0, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  for(i=display.height()-1; i>=0; i-=4) {
    display.drawLine(display.width()-1, display.height()-1, 0, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  delay(250);

  display.clearDisplay();

  for(i=0; i<display.height(); i+=4) {
    display.drawLine(display.width()-1, 0, 0, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }
  for(i=0; i<display.width(); i+=4) {
    display.drawLine(display.width()-1, 0, i, display.height()-1, SSD1306_WHITE);
    display.display();
    delay(1);
  }

  delay(2000); // Pause for 2 seconds
}

void testdrawrect(void) {
  display.clearDisplay();

  for(int16_t i=0; i<display.height()/2; i+=2) {
    display.drawRect(i, i, display.width()-2*i, display.height()-2*i, SSD1306_WHITE);
    display.display(); // Update screen with each newly-drawn rectangle
    delay(1);
  }

  delay(2000);
}

void testfillrect(void) {
  display.clearDisplay();

  for(int16_t i=0; i<display.height()/2; i+=3) {
    // The INVERSE color is used so rectangles alternate white/black
    display.fillRect(i, i, display.width()-i*2, display.height()-i*2, SSD1306_INVERSE);
    display.display(); // Update screen with each newly-drawn rectangle
    delay(1);
  }

  delay(2000);
}

void testdrawcircle(void) {
  display.clearDisplay();

  for(int16_t i=0; i<max(display.width(),display.height())/2; i+=2) {
    display.drawCircle(display.width()/2, display.height()/2, i, SSD1306_WHITE);
    display.display();
    delay(1);
  }

  delay(2000);
}

void testfillcircle(void) {
  display.clearDisplay();

  for(int16_t i=max(display.width(),display.height())/2; i>0; i-=3) {
    // The INVERSE color is used so circles alternate white/black
    display.fillCircle(display.width() / 2, display.height() / 2, i, SSD1306_INVERSE);
    display.display(); // Update screen with each newly-drawn circle
    delay(1);
  }

  delay(2000);
}

void testdrawroundrect(void) {
  display.clearDisplay();

  for(int16_t i=0; i<display.height()/2-2; i+=2) {
    display.drawRoundRect(i, i, display.width()-2*i, display.height()-2*i,
      display.height()/4, SSD1306_WHITE);
    display.display();
    delay(1);
  }

  delay(2000);
}

void testfillroundrect(void) {
  display.clearDisplay();

  for(int16_t i=0; i<display.height()/2-2; i+=2) {
    // The INVERSE color is used so round-rects alternate white/black
    display.fillRoundRect(i, i, display.width()-2*i, display.height()-2*i,
      display.height()/4, SSD1306_INVERSE);
    display.display();
    delay(1);
  }

  delay(2000);
}

void testdrawtriangle(void) {
  display.clearDisplay();

  for(int16_t i=0; i<max(display.width(),display.height())/2; i+=5) {
    display.drawTriangle(
      display.width()/2  , display.height()/2-i,
      display.width()/2-i, display.height()/2+i,
      display.width()/2+i, display.height()/2+i, SSD1306_WHITE);
    display.display();
    delay(1);
  }

  delay(2000);
}

void testfilltriangle(void) {
  display.clearDisplay();

  for(int16_t i=max(display.width(),display.height())/2; i>0; i-=5) {
    // The INVERSE color is used so triangles alternate white/black
    display.fillTriangle(
      display.width()/2  , display.height()/2-i,
      display.width()/2-i, display.height()/2+i,
      display.width()/2+i, display.height()/2+i, SSD1306_INVERSE);
    display.display();
    delay(1);
  }

  delay(2000);
}

void testdrawchar(void) {
  display.clearDisplay();

  display.setTextSize(1);      // Normal 1:1 pixel scale
  display.setTextColor(SSD1306_WHITE); // Draw white text
  display.setCursor(0, 0);     // Start at top-left corner
  display.cp437(true);         // Use full 256 char 'Code Page 437' font

  // Not all the characters will fit on the display. This is normal.
  // Library will draw what it can and the rest will be clipped.
  for(int16_t i=0; i<256; i++) {
    if(i == '\n') display.write(' ');
    else          display.write(i);
  }

  display.display();
  delay(2000);
}

void testdrawstyles(void) {
  display.clearDisplay();

  display.setTextSize(1);             // Normal 1:1 pixel scale
  display.setTextColor(SSD1306_WHITE);        // Draw white text
  display.setCursor(0,0);             // Start at top-left corner
  display.println(F("Hello, world!"));

  display.setTextColor(SSD1306_BLACK, SSD1306_WHITE); // Draw 'inverse' text
  display.println(3.141592);

  display.setTextSize(2);             // Draw 2X-scale text
  display.setTextColor(SSD1306_WHITE);
  display.print(F("0x")); display.println(0xDEADBEEF, HEX);

  display.display();
  delay(2000);
}

void testscrolltext(void) {
  display.clearDisplay();

  display.setTextSize(2); // Draw 2X-scale text
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(10, 0);
  display.println(F("scroll"));
  display.display();      // Show initial text
  delay(100);

  // Scroll in various directions, pausing in-between:
  display.startscrollright(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  display.startscrollleft(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  display.startscrolldiagright(0x00, 0x07);
  delay(2000);
  display.startscrolldiagleft(0x00, 0x07);
  delay(2000);
  display.stopscroll();
  delay(1000);
}

void testdrawbitmap(void) {
  display.clearDisplay();

  display.drawBitmap(
    (display.width()  - LOGO_WIDTH ) / 2,
    (display.height() - LOGO_HEIGHT) / 2,
    logo_bmp, LOGO_WIDTH, LOGO_HEIGHT, 1);
  display.display();
  delay(1000);
}

#define XPOS   0 // Indexes into the 'icons' array in function below
#define YPOS   1
#define DELTAY 2

void testanimate(const uint8_t *bitmap, uint8_t w, uint8_t h) {
  int8_t f, icons[NUMFLAKES][3];

  // Initialize 'snowflake' positions
  for(f=0; f< NUMFLAKES; f++) {
    icons[f][XPOS]   = random(1 - LOGO_WIDTH, display.width());
    icons[f][YPOS]   = -LOGO_HEIGHT;
    icons[f][DELTAY] = random(1, 6);
    Serial.print(F("x: "));
    Serial.print(icons[f][XPOS], DEC);
    Serial.print(F(" y: "));
    Serial.print(icons[f][YPOS], DEC);
    Serial.print(F(" dy: "));
    Serial.println(icons[f][DELTAY], DEC);
  }

  for(;;) { // Loop forever...
    display.clearDisplay(); // Clear the display buffer

    // Draw each snowflake:
    for(f=0; f< NUMFLAKES; f++) {
      display.drawBitmap(icons[f][XPOS], icons[f][YPOS], bitmap, w, h, SSD1306_WHITE);
    }

    display.display(); // Show the display buffer on the screen
    delay(200);        // Pause for 1/10 second

    // Then update coordinates of each flake...
    for(f=0; f< NUMFLAKES; f++) {
      icons[f][YPOS] += icons[f][DELTAY];
      // If snowflake is off the bottom of the screen...
      if (icons[f][YPOS] >= display.height()) {
        // Reinitialize to a random position, just off the top
        icons[f][XPOS]   = random(1 - LOGO_WIDTH, display.width());
        icons[f][YPOS]   = -LOGO_HEIGHT;
        icons[f][DELTAY] = random(1, 6);
      }
    }
  }
}

I hope that you find this useful and inspiring.
Thank you

Multiple I2C Devices on the same Bus, I2C Part 3

Today I will continue my series on I2C by showing you how to use multiple devices on the I2C bus. This will be an extremely short post, as it builds on skills that we have already covered.

I will connect the following

1 x 16×2 I2C LCD Screen address 0x27
1x 128×32 I2C OLED Display address 0x3C
2x PCF8574 I2C Io Extenders address 0x20 and 0x21

All of these devices will be controlled from Arduino Uno, using the following libraries


LiquidCrystal_I2C.h to control the LCD screen,
Wire.h and PCF8574.h to control the I2C IO extenders and
Adafruit_GFX, Adafruit_SSD1306.h and SPI.h to control the SSD1306 128×32 OLED display.

With DuPont wires and breadboards being the reliable things they are, I decided that, after initial testing, I will not show you how to do button inputs on the PCF8574 at this stage. The amount of stray capacitance floating around on the breadboards, and small momentary push-button switches, made for a very impressive but unreliable mess of wires, with no real learning value to it 😉 Maybe some more on that later when I do a decent real-world example using these technologies 🙂

As the total distance between the devices is relatively short, it was not necessary to use pull-up resistors on the I2C bus in my setup. I suspect that that is due to the fact that they may already be included on some of my devices.

The circuit is quite straight forward.

  1. Connect all SDA pins on the I2C devices together serially, and connect that to the Arduino SDA pin ( That is usually A4)
  2. Connect all SCL pins on the I2C devices together serially, and connect that to the Arduino SCL pin ( That is usually A5)

    A note: On my Uno clone, there is an additional I2C breakout at the top of the device, near the USB adapter. I chose to use that as well as A4 and A5, as the bus hung itself up when connected to the breadboard. Your mileage may vary on this one 🙂
  3. Connect all 5v (Vcc) lines to 5v on the Arduino, and all Ground (GND) lines to GND on the Arduino.
  4. Now connect 4 LEDs, through a suitable resistor ( 640 ohms up to 1k ohm ) to pin P0 and P1 on both of the PCF8574 IO extenders. Also, connect the other leg of the LED to ground.
  5. I have powered my Uno from an external 5v power supply, as I did not want to pull too much current from the regulator on the actual Uno clone.

That should complete your hardware setup. Double check all your connections, and then load the i2c scanner sketch in the Arduino IDE, you may find it under the examples for the Wire.h library.

Power up the circuit, and upload the sketch to the Uno. Open the Serial Monitor.

You should see 4 I2C devices being detected. Note their addresses. If you dont see 4 devices, check your wiring and addresses. You may have a device with a conflicting address or a bad connection. If you used the breadboard to connect the bus, chances are very good that you will not see all the devices.

Good, if all of that is working, copy paste the following code into a new Arduino IDE window.
I will explain the code in the section below:

/*
  Multiple devices on the I2C bus
  Maker and Iot Ideas, MakerIoT2020
*/
// Include the libraries that we will need
#include <SPI.h> // needed for OLED display. 
#include <PCF8574.h> // PCF8574
#include <Wire.h> // Generic I2C library
#include <Adafruit_GFX.h> // for OLED display
#include <Adafruit_SSD1306.h> // for OLED display
#include <LiquidCrystal_I2C.h> // For I2C LCD display

// we need to define the size of the OLED screen

#define OLED_WIDTH 128
#define OLED_HEIGHT 32

// mine does not have an onboard reset pin. If yours do, specify the 
// pin that it is connected to on the Arduino here. To use the 
// Arduino reset pin, specify -1 as below

#define OLED_RESET -1

// Define the OLED display, width,hight protocol and reset pin
Adafruit_SSD1306 oled(OLED_WIDTH,OLED_HEIGHT, &Wire, OLED_RESET);

// Define the I2C LCD screen address and pin configuration
LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7,3,POSITIVE);

// Define the PCF8574 devices ( you can have up to 8 on a bus )
// but in this case, my LCD uses address 0x27, so I will have a 
// conflicting address if I were to use 8 of them together with the
// LCD

PCF8574 Remote_1(0x20); 
PCF8574 Remote_2(0x21);

// Note the I2C addresses. You can obtain them from the i2c_scanner

void setup() {
  // serial debugging if needed
  Serial.begin(115200);
  // Start OLED Display Init

  if (!oled.begin(SSD1306_SWITCHCAPVCC,0x3C)) { // Init the OLED 
    Serial.println(F("OLED INIT FAILED"));
    for(;;); // Dont proceed ... loop forever
  }
  oled.display();
  delay(2000); // This delay is required to give display time to 
  // initialise properly
  oled.clearDisplay();
  oled.setTextSize(0);
  oled.setTextColor(SSD1306_WHITE);
  oled.setCursor(0,0);
  oled.println("TEST SCREEN");
  oled.display();
  delay(2000);
  oled.clearDisplay();
  oled.setCursor(1,0);
  oled.println("OLED SCREEN ON");
  oled.display();

  // Start the LCD

  lcd.begin(16,2);
  
  // Set the initial state of the pins on the PCF8574 devices
  // I found that the PCF8574 library sometimes does funny things
  // This is also an example of how to use native i2c to set the 
  // status of the pins
  
  Wire.begin();
  Wire.beginTransmission(0x20); // device 1
  Wire.write(0x00); // all ports off
  Wire.endTransmission();
  Wire.begin();
  Wire.beginTransmission(0x21); // device 2
  Wire.write(0x00); // all ports off
  Wire.endTransmission();
  // Set pinModes for PCF8574 devices
  // Note that there are two of them

  Remote_1.pinMode(P0,OUTPUT);
  Remote_1.pinMode(P1,OUTPUT);
  Remote_2.pinMode(P0,OUTPUT);
  Remote_2.pinMode(P1,OUTPUT);
  
  // Start both IO extenders

  Remote_1.begin();
  Remote_2.begin();

  // and set ports to low on both
  // you may find that if you ommit this step, they come up in an
  // unstable state.

  Remote_1.digitalWrite(P0,LOW);
  Remote_1.digitalWrite(P1,LOW);
  Remote_2.digitalWrite(P0,LOW);
  Remote_2.digitalWrite(P1,LOW);
  
}

void loop() {
  // Draw a character map on the OLED display.
  // This function is borrowed from the Adafruit library

  testdrawchar();

  // Write to the IO extenders

  Remote_1.digitalWrite(P0,HIGH);
  Remote_1.digitalWrite(P1,LOW);
  Remote_2.digitalWrite(P0,HIGH);
  Remote_2.digitalWrite(P1,LOW);
  
  // Display their status on the LCD
  lcd.setCursor(0,0);
  lcd.print(" R1 P0=1 P1=0");
  lcd.setCursor(0,1);
  lcd.print(" R2 P0=1 P1=0");
  delay(500);

  // Change status
  Remote_1.digitalWrite(P1,HIGH);
  Remote_1.digitalWrite(P0,LOW);
  Remote_2.digitalWrite(P1,HIGH);
  Remote_2.digitalWrite(P0,LOW);

  // Update LCD
  lcd.setCursor(0,0);
  lcd.print(" R1 P0=0 P1=1");
  lcd.setCursor(0,1);
  lcd.print(" R2 P0=0 P1=1");
  delay(500);
  // Do some graphics on the OLED display
  // Function borrowed from Adafruit
  testdrawrect();
  oled.clearDisplay();
  delay(500);
  // repeat indefinitely

}

void testdrawrect(void) {
  oled.clearDisplay();

  for(int16_t i=0; i<oled.height()/2; i+=2) {
    oled.drawRect(i, i, oled.width()-2*i, oled.height()-2*i, SSD1306_WHITE);
    oled.display(); // Update screen with each newly-drawn rectangle
    delay(1);
  }

  delay(500);
}

void testdrawchar(void) {
  oled.clearDisplay();

  oled.setTextSize(1);      // Normal 1:1 pixel scale
  oled.setTextColor(SSD1306_WHITE); // Draw white text
  oled.setCursor(0, 0);     // Start at top-left corner
  oled.cp437(true);         // Use full 256 char 'Code Page 437' font

  // Not all the characters will fit on the display. This is normal.
  // Library will draw what it can and the rest will be clipped.
  for(int16_t i=0; i<256; i++) {
    if(i == '\n') oled.write(' ');
    else          oled.write(i);
  }

  oled.display();
  delay(500);
}

This concludes a quick and dirty show and tell… I hope that it will stimulate questions and ideas for a lot of people.

Thank you