Example code for NHD-0216KZW/ 0220DZW/ 0420DZW - (SPI)
#include <reg52.h> sbit SCL = P3^4; sbit SDOUT = P1^0; sbit SDIN = P1^1; sbit C_S = P3^3; void delay(unsigned int n) //Delay subroutine { unsigned int i,j; for (i=0;i<n;i++) for (j=0;j<250;j++) {;} } void WriteCommand(unsigned char ins) { unsigned char i; C_S=0; SCL = 0; SDOUT = 0; //RS = 0 (Command) SCL = 1; //RS registered SCL = 0; SDOUT = 0; //RW = 0 SCL = 1; //RW registered SCL = 0; for (i=0x80;i;i>>=1) { if((ins&0x80)==0x80) SDOUT = 1; else SDOUT = 0; ins=(ins<<1); SCL = 0; SCL = 1; SCL = 0; } C_S=1; } void WriteDataInit() { C_S=0; SCL = 0; SDOUT = 1; //RS = 1 (Data) SCL = 0; //RS registered SCL = 1; SCL = 0; SDOUT = 0; //RW = 0 SCL = 1; //RS registered SCL = 0; } void WriteData(unsigned char dat) { unsigned char i; for (i=0x80;i;i>>=1) { if((dat&0x80)==0x80) SDOUT = 1; else SDOUT = 0; dat=(dat<<1); SCL = 0; SCL = 1; SCL = 0; } } void init() { WriteCommand(0x38);//function set delay(30); WriteCommand(0x06);//entry mode set delay(30); WriteCommand(0x02);//return home delay(30); WriteCommand(0x01);//clear display delay(30); WriteCommand(0x0c);//display on delay(30); WriteCommand(0x80);//line 1 character 1 delay(30); } void main() { char i=0x21, j; init(); while(1) { C_S = 1; WriteCommand(0x80); //Line 1 WriteDataInit(); //WriteDataInit() must only be executed once before starting to write data //if WriteDataInit() is executed between writes, the display will recognize the two bits as data bits and not RS/RW bits. for(j=0; j<20; j++) { WriteData(i++); delay(10); } C_S = 1; //Pulling C_S High means write data is completed //if next instruction to the display is data, must use WriteDataInit() first //if write command is executed without pulling C_S high, it will recognize the following instruction on the bus as data regardless WriteCommand(0xC0); //Line 2 WriteDataInit(); for(j=0; j<20; j++) { WriteData(i++); delay(10); } C_S = 1; WriteCommand(0x94); //Line 3 WriteDataInit(); for(j=0; j<20; j++) { WriteData(i++); delay(10); } C_S = 1; WriteCommand(0xD4); //Line 4 WriteDataInit(); for(j=0; j<20; j++) { WriteData(i++); delay(10); } } }