Learning Centre

ATmega328 Development Board



Directions to select the ATmega328 board on Arduino IDE

Installing the ATmega328 Board in Arduino IDE

Before starting this method, make sure you have the latest version of the Arduino IDE 1.8.19 installed in your computer.
If you don’t, install it from https://www.arduino.cc/en/software, continue with this tutorial.
Step 1: Plug the ESP32 Trainer Kit to your computer. With your Arduino IDE open, follow these steps: Step 2 : Select your Board in Tools > Board menu (it’s the Arduino Uno)

Arduino Uno

Select the Port if you don’t see the COM Port in your Arduino IDE, you need to install the FTDI Drivers:https://ftdichip.com/drivers/d2xx-drivers/
For Installation Guide, CLICK HERE

Arduino Uno

Installing Libraries

Step 1: To install a new library into your Arduino IDE. Open the IDE and click to the "Sketch" menu and then Include Library arrow Manage Libraries.

Step 2: Then the Library Manager will open and you will find a list of libraries that are already installed or ready for installation. In this example we will install the RTC library(i.e rtclib).Enter the library name to find it, click on it, then select the version of the library you want to install. Sometimes only one version of the library is available.Then click on install.If you don’t find the library then refer page 12.

Step 3: Wait for the IDE to install the new library. Downloading may take time depending on your connection speed. Once it has finished, an Installed tag should appear next to the RTC library. Then click on close.

Another Method for installing and importing a .zip Library

Step 1: Go to Google, search for the library(i.e rtclib) you want to install, click on download ZIP.

Step 2: In the Arduino IDE, go to Sketch arrow Include Library arrow Add .ZIP Library.

Step 3:Select the library you would like to add. Go to the .zip file's downloaded location and open it.

Libraries link

1. Keypad Library (keypad.h)  DOWNLOAD HERE
2. LCD Library (LiquidCrystal.h)  DOWNLOAD HERE
3. RTC Libraries (rtclib)  DOWNLOAD HERE , (Wire.h)  DOWNLOAD HERE
4. SD Card Libraries (FS.h)  DOWNLOAD HERE ,(SD.h)  DOWNLOAD HERE , (SPI.h)  DOWNLOAD HERE
5. OLED Libraries (Adafruit_GFX.h)  DOWNLOAD HERE, (Adafruit_SSD1306.h)   DOWNLOAD HERE

Blinking an LED

Aim:Interfacing LED’s with ATmega328-Microcontroller.
Description:To learn how to programme an ATmega328-Microcontroller to blink an LED by connecting an LED’S to its digital pins.
Hardware Requirement:ATmega328 IoT Development Kit and FRC cable.

Procedure:

1. Connect P1 port and SV2 (LED) port using FRC cable as shown above.
2. Connect the USB cable to the board.
3. Open Arduino IDE. Select Arduino Uno in boards and select COM port.
4. Now write the program, verify and Upload it.
5. Now you can see the LED blink on the ATmega328 development board.

Code


const int L1=2, L2=3, L3=4, L4=5, L5=6, L6=7, L7=8, L8=9; //initializing LED pins
void setup()
{
pinMode(L1, OUTPUT); // Set all Port P1 pins as output
pinMode(L2, OUTPUT);
pinMode(L3, OUTPUT);
pinMode(L4, OUTPUT);
pinMode(L5, OUTPUT);
pinMode(L6, OUTPUT);
pinMode(L7, OUTPUT);
pinMode(L8, OUTPUT);
}
void loop()
{
digitalWrite(L1, HIGH);
digitalWrite(L2, HIGH);
digitalWrite(L3, HIGH);
digitalWrite(L4, HIGH);
digitalWrite(L5, HIGH);
digitalWrite(L6, HIGH);
digitalWrite(L7, HIGH);
digitalWrite(L8, HIGH);
delay(2000);
digitalWrite(L1, LOW);
digitalWrite(L2, LOW);
digitalWrite(L3, LOW);
digitalWrite(L4, LOW);
digitalWrite(L5, LOW);
digitalWrite(L6, LOW);
digitalWrite(L7, LOW);
digitalWrite(L8, LOW);
delay(2000);
}

Seven Segment Displays

Aim:Interfacing ATmega328-Microcontroller with seven segment display
Description:To display numbers in 7 segment display
Hardware Requirement:ESP32-Microcontroller Development board and FRC Cables.

Procedure:

1. Connect P1 port and SV4 (Data) port and connect P2 port and SV3 (Select) port using FRC cable as shown above.
2. Connect the USB cable to the board.
3. Open Arduino IDE .Select Arduino Uno in boards and select COM port.
4. Now write the program, verify and Upload it.
5. Now you can see that number starts displaying on the seven segments on the ATmega328 development board.

Code


const int sel1=10, sel2=11, sel3=12, sel4=13; //initializing
selection pins -Port P2
const int a=2 ,b=3, c=4, d=5, e=6, f=7, g=8, dp=9;
//initializing data pins -Port P1
void setup()
{
pinMode(sel1,OUTPUT); //declaring Selection Pins as output
pinMode(sel2,OUTPUT);
pinMode(sel3,OUTPUT);
pinMode(sel4,OUTPUT);
digitalWrite(sel1,LOW); //selecting all 4 digits of 7-Segment
display by making it LOW
digitalWrite(sel2,LOW);
digitalWrite(sel3,LOW);
digitalWrite(sel4,LOW);
pinMode(a,OUTPUT); //declaring data pins as output
pinMode(b,OUTPUT);
pinMode(c,OUTPUT);
pinMode(d,OUTPUT);
pinMode(e,OUTPUT);
pinMode(f,OUTPUT);
pinMode(g,OUTPUT);
pinMode(dp,OUTPUT);
delay(100);
}
void Loop
{
// print 0
digitalWrite(a,LOW);
digitalWrite(b,LOW);
digitalWrite(c,LOW);
digitalWrite(d,LOW);
digitalWrite(e,LOW);
digitalWrite(f,LOW);
digitalWrite(g,HIGH);
digitalWrite(dp,LOW);
delay(2000);
// print 1
digitalWrite(a,HIGH);
digitalWrite(b,LOW);
digitalWrite(c,LOW);
digitalWrite(d,HIGH);
digitalWrite(e,HIGH);
digitalWrite(f,HIGH);
digitalWrite(g,HIGH);
digitalWrite(dp,HIGH);
delay(2000);
// print 2
digitalWrite(a,LOW);
digitalWrite(b,LOW);
digitalWrite(c,HIGH);
digitalWrite(d,LOW);
digitalWrite(e,LOW);
digitalWrite(f,HIGH);
digitalWrite(g,LOW);
digitalWrite(dp,LOW);
delay(2000);
// print 3
digitalWrite(a,LOW);
digitalWrite(b,LOW);
digitalWrite(c,LOW);
digitalWrite(d,LOW);
digitalWrite(e,HIGH);
digitalWrite(f,HIGH);
digitalWrite(g,LOW);
digitalWrite(dp,LOW);
delay(2000);
// print 4
digitalWrite(a,HIGH);
digitalWrite(b,LOW);
digitalWrite(c,LOW);
digitalWrite(d,HIGH);
digitalWrite(e,HIGH);
digitalWrite(f,LOW);
digitalWrite(g,LOW);
digitalWrite(dp,LOW);
delay(2000);
// print 5
digitalWrite(a,LOW);
digitalWrite(b,HIGH);
digitalWrite(c,LOW);
digitalWrite(d,LOW);
digitalWrite(e,HIGH);
digitalWrite(f,LOW);
digitalWrite(g,LOW);
digitalWrite(dp,LOW);
delay(2000);
// print 6
digitalWrite(a,LOW);
digitalWrite(b,HIGH);
digitalWrite(c,LOW);
digitalWrite(d,LOW);
digitalWrite(e,LOW);
digitalWrite(f,LOW);
digitalWrite(g,LOW);
digitalWrite(dp,LOW);
delay(2000);
// print 7
digitalWrite(a,LOW);
digitalWrite(b,LOW);
digitalWrite(c,LOW);
digitalWrite(d,HIGH);
digitalWrite(e,HIGH);
digitalWrite(f,HIGH);
digitalWrite(g,HIGH);
digitalWrite(dp,HIGH);
delay(2000);
// print 8
digitalWrite(a,LOW);
digitalWrite(b,LOW);
digitalWrite(c,LOW);
digitalWrite(d,LOW);
digitalWrite(e,LOW);
digitalWrite(f,LOW);
digitalWrite(g,LOW);
digitalWrite(dp,LOW);
delay(2000);
// print 9
digitalWrite(a,LOW);
digitalWrite(b,LOW);
digitalWrite(c,LOW);
digitalWrite(d,LOW);
digitalWrite(e,HIGH);
digitalWrite(f,LOW);
digitalWrite(g,LOW);
digitalWrite(dp,LOW);
delay(2000);
}  

Hex Keypad

Aim:To interface 4x4 Hex Keypad with ATmega328-Microcontroller module.
Description:To display the pressed key on the serial monitor.
Hardware Requirement:ATmega328-Microcontroller Development board and FRC Cable.

Procedure:

1. Connect P1 port and SV5(4*4 Key Matrix) port using FRC cable as shownabove.
2. Connect the USB cable to the board.
3.Open Arduino IDE .Select Arduino Uno in boards and select COM port
4. Now write the program, verify and Upload it.
5. After uploading is done open serial monitor to observe the output.
6. On your serial monitor, the number appears for each switch pressed.

Code


#include <Keypad.h>
char keys[4][4]={
{'1','2','3','4'},{'5','6','7','8'},{'9','0','A','B'},{'C','D'
,'E','F'}}; //defining characters of 4X4 Key Matrix
byte rowPin[4]={2,3,4,5}; //declaring the rows and column pins
(Port P1)
byte colPin[4]={6,7,8,9};
Keypad keypad=Keypad(makeKeymap(keys),rowPin,colPin,4,4); //
Creating 4X4 Keypad Matrix
void setup()
{
Serial.begin(9600);
}
void loop()
{
char pressed=keypad.getKey(); //This function will fetch the
character being pressed
if(pressed)
{
Serial.print("Key pressed = ");
Serial.println(pressed);
}
delay(500);
}

Output

Liquid Crystal Display

Aim:To interface LCD display with ATmega328-Microcontroller module
Description:To display the message on the LCD screen.
Hardware Requirement:ATmega328-Microcontroller Development board and FRC Cable.

Procedure:

1.Connect P1 port and SV1(LCD 16*2 Display) port using FRC cable as shown above.
2. Connect the USB cable to the board.
3.Open Arduino IDE .Select Arduino Uno in boards and select COM port
4. Write the program, verify and Upload it.
5. Now you can see the output on LCD.

Code


#include<LiquidCrystal.h> // Include the LCD library
LiquidCrystal lcd(2,3,6,7,8,9); //Port P1 Mapping the pins
with library
void setup()
{
Serial.begin(9600); //Baud Rate
lcd.begin(16,2); //initializing 16X2 LCD display
}
void loop()
{
lcd.setCursor(0,0); //first line in display
lcd.print("*WELCOME TO RDL*");
delay(3000);
//lcd.clear();
lcd.setCursor(0,1); //second line in display
lcd.print("LEARNING IS FUN");
delay(3000);
lcd.clear();
}

IR (Infrared) Sensor

Aim:To Interfacing IR sensor with ATmega328-Microcontroller module.
Description:To learn how to read values from an IR sensor using ATmega328-Microcontroller
Hardware Requirement:ESP32-Microcontroller Development board, IR sensor, F-F Patch Chords

Procedure:

1.Connect P1 port pins (5, GND, 3V) to IR Sensor pins (OUT, GND, 5V) using patch chords as shown above.
2. Connect the USB cable to the board.
3.Open Arduino IDE .Select Arduino Uno in boards and select COM port
4. Write the program, verify and Upload it.
5. Now you can see the output on the serial monitor

Code


const int proximity=2; //D2 of port P1 connected to IR sensor
int value=0;
void setup() {
Serial.begin(9600);
pinMode(proximity, INPUT); //declared as input
delay(100);
}
void loop() {
value=digitalRead(proximity); // storing sensor data in a
variable.
delay(1000);
if(!value) //check for an obstacle if present.
{
Serial.println("obstacle detected.."); //display this message
when obstacle detects
}
}

Output

RTC (Real Time Clock)

Aim:Interfacing Real Time Clock module with ATmega328-Microcontroller module.
Description:To display Date and Time on the serial monitor using ATmega328 microcontroller development board.
Hardware Requirement:ATmega328-Microcontroller Development board and RTC Battery.

Procedure:

1.Connect the USB cable to the board
2.Open Arduino IDE .Select Arduino Uno in boards and select COM port
3.Write the program, verify and Upload it.
4. Open the serial monitor to observe the output.

Code


#include "Wire.h"
#define DS1307_I2C_ADDRESS 0x68
// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val){
return( (val/10*16) + (val%10) );
}
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val){
return( (val/16*10) + (val%16) );
}
void setup(){
Wire.begin();
Serial.begin(9600);
delay(1000);
// set the initial time here:
setDS1307time(00,50,12,2,22,3,21); // DS1307 seconds, minutes,
hours, day, date, month, year
delay(1000);
}
void setDS1307time(byte second, byte minute, byte hour, byte
dayOfWeek, byte
dayOfMonth, byte month, byte year){
// sets time and date data to DS1307
Wire.beginTransmission(DS1307_I2C_ADDRESS);
Wire.write(0); // set next input to start at the seconds
register
Wire.write(decToBcd(second)); // set seconds
Wire.write(decToBcd(minute)); // set minutes
Wire.write(decToBcd(hour)); // set hours
Wire.write(decToBcd(dayOfWeek)); // set day of week (1=Sunday,
7=Saturday)
Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31)
Wire.write(decToBcd(month)); // set month
Wire.write(decToBcd(year)); // set year (0 to 99)
Wire.endTransmission();
}
void readDS1307time(byte *second, byte *minute, byte *hour,
byte *dayOfWeek, byte *dayOfMonth, byte *month, byte *year)
{
Wire.beginTransmission(DS1307_I2C_ADDRESS);
Wire.write(0); // set DS1307 register pointer to 00h
Wire.endTransmission();
delay(100);
Wire.requestFrom(DS1307_I2C_ADDRESS, 7);
// request seven bytes of data from DS1307 starting from
register 00h
*second = bcdToDec(Wire.read() & 0x7f);
*minute = bcdToDec(Wire.read());
*hour = bcdToDec(Wire.read() & 0x3f);
*dayOfWeek = bcdToDec(Wire.read());
*dayOfMonth = bcdToDec(Wire.read());
*month = bcdToDec(Wire.read());
*year = bcdToDec(Wire.read());
Wire.endTransmission();
}

void displayTime(){
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
// retrieve data from DS1307
readDS1307time(&second, &minute, &hour, &dayOfWeek,
&dayOfMonth, &month,
&year);
// send it to the serial monitor
Serial.print(hour, DEC);
// convert the byte variable to a decimal number when
displayed
Serial.print(":");
if (minute<10){
Serial.print("0");
}
Serial.print(minute, DEC);
Serial.print(":");
if (second<10){
Serial.print("0");
}
Serial.print(second, DEC);
Serial.print(" ");
Serial.print(dayOfMonth, DEC);
Serial.print("/");
Serial.print(month, DEC);
Serial.print("/");
Serial.print(year, DEC);
Serial.print(" Day of week: ");
switch(dayOfWeek){
case 1:
Serial.println("Sunday");
break;
case 2:
Serial.println("Monday");
break;
case 3:
Serial.println("Tuesday");
break;
case 4:
Serial.println("Wednesday");
break;
case 5:
Serial.println("Thursday");
break;
case 6:
Serial.println("Friday");
break;
case 7:
Serial.println("Saturday");
break;
}
}
void loop(){
displayTime(); // display the real-time clock data on the
Serial Monitor,
delay(1000); // every second
}


Output

ADC

Aim:To Interface ADC with ATmega328- Microcontroller Modue.
Description:To learn how to read ADC values using ATmega328-Microcontroller.
Hardware Requirement:ATmega328-Microcontroller Development board and FRC Cable.

Procedure:

1.Connect P3 port and SV12(ADC & Temp) port using FRC cable as shown above.
2. Connect the USB cable to the board.
3.Open Arduino IDE .Select Arduino Uno in boards and select COM port
4. Write the program, verify and Upload it.
5. Open the serial monitor to observe the output.

Code


const int adc1=0;
const int adc2=1;
const int adc3=2;
int value1=0, value2=0, value3=0;
float res1=0, res2=0, res3=0;
void setup() {
Serial.begin(115200);
pinMode(adc1, INPUT); // Pins Port1 Connected to ADC Knobs
pinMode(adc2, INPUT);
pinMode(adc3, INPUT);
delay(500);
}
void loop() {
delay(1000);
value1=analogRead(adc1);
value2=analogRead(adc2);
value3=analogRead(adc3);
res1=float((value1*3.3)/4095); //3.3v is maximum voltage
applied as a input
res2=float((value2*3.3)/4095); //it is 12bit ADC hence
dividing by 4095 gives actual voltage
res3=float((value3*3.3)/4095);
Serial.print("The output of ADC1= ");
Serial.print(res1);
delay(500);
Serial.print("\t The output of ADC2= ");
Serial.print(res2);
delay(500);
Serial.print("\t The output of ADC3= ");
Serial.println(res3);
delay(500);
}

Output

L298 Motor

Aim:To Interface L298 Motor with ATmega328-Microcontroller Board.
Description:This experiment shows how to rotate the L298 Motor clockwise and anticlockwise using ATmega328-Microcontroller.
Hardware Requirement:ATmega328-Microcontroller Development board, L298 Motor and FRC Cable.

Procedure:

1.Connect P1 port and SV9 port using FRC cable.
2. Connect the USB cable to the board.
3.Open Arduino IDE .Select DOIT ESP32 DEVKIT V1in boards and select COM port.
4. Write the program, verify and Upload it.

Code


const int En1=4,En2=5; //initializing enable pins
const int in1=6, in2=7, in3=8, in4=9; //initializing input
pins
void setup()
{
// channel A
pinMode(En1,OUTPUT);
pinMode(in1,OUTPUT);
pinMode(in2,OUTPUT);
// channel B
pinMode(En2,OUTPUT);
pinMode(in3,OUTPUT);
pinMode(in4,OUTPUT);
}
void loop() {
//enabling motor1
digitalWrite(En1,HIGH);
digitalWrite(En2,LOW);
// Motor 1 clockwise rotation
digitalWrite(in1,HIGH); //motor1 keep rotating for 2 seconds
in clockwise direction
digitalWrite(in2,LOW);
delay(2000);
//Motor 1 anticlockwise rotation
digitalWrite(in1,LOW); //motor1 keep rotating for 2 seconds
in anti-clockwise direction
digitalWrite(in2,HIGH);
delay(2000);
//enabling Motor 2
digitalWrite(En1,LOW);
digitalWrite(En2,HIGH);
// Motor 2 clockwise rotation
digitalWrite(in3,HIGH); //motor2 keep rotating for 2 seconds
in clockwise direction
digitalWrite(in4,LOW);
delay(2000);
//Motor2 anticlockwise rotation
digitalWrite(in3,LOW); //motor2 keep rotating for 2 seconds
in anti-clockwise direction
digitalWrite(in4,HIGH);
delay(2000);
}

SD Card

Aim:Interfacing SD card with ATmega328-Microcontroller Board to list the directories stored in memory card.
Description:To read the stored directories in SD card using ATmega328 microcontroller development board.
Hardware Requirement:ATmega328-Microcontroller Development board and SD Card.

Procedure:

1.Insert the SD Card in the slot given in the board.
2. Connect the USB cable to the board.
3.Open Arduino IDE .Select Arduino Uno in boards and select COM port
4. Write the program, verify and Upload it.
5.Open the serial monitor to observe the output.

Code


#include <SPI.h>
#include <SD.h>
File myFile;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
 ; // wait for serial port to connect. Needed for native
USB port only
}
Serial.print("Initializing SD card...");
if (!SD.begin(10)) {
 Serial.println("initialization failed!");
 while (1);
}
Serial.println("initialization done.");
// open the file. note that only one file can be open at a
time,
// so you have to close this one before opening another.
myFile = SD.open("test.txt", FILE_WRITE);
// if the file opened okay, write to it:
if (myFile) {
 Serial.print("Writing to test.txt...");
 myFile.println("RDL TECHNOLOGIES PVT. LTD");
 // close the file:
 myFile.close();
 Serial.println("done.");
 } else {
 // if the file didn't open, print an error:
 Serial.println("error opening test.txt");
}
// re-open the file for reading:
myFile = SD.open("test.txt");
if (myFile) {
 Serial.println("test.txt:");
 // read from the file until there's nothing else in it:
while (myFile.available()) {
 Serial.write(myFile.read());
 }
 // close the file:
 myFile.close();
} else {
 // if the file didn't open, print an error:
 Serial.println("error opening test.txt");
}
}
void loop() {
// nothing happens after setup
}


Output

OLED

Aim:To Interface OLED Display with ATmega328-Microcontroller Board.
Description:To display message on OLED screen.
Hardware Requirement:ATmega328-Microcontroller Development board

Procedure:

1. Connect the USB cable to the board.
2.Open Arduino IDE .Select Arduino Uno in boards and select COM port
3. Write the program, verify and Upload it.
4.Now you can see the output displaying the message on OLED of ATmega328 microcontroller board.

Code


#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
#define OLED_RESET 4 // Reset pin
#define SCREEN_ADDRESS 0x3C //0x3C for 128x32pixels OLED
Adafruit_SSD1306 display (SCREEN_WIDTH, SCREEN_HEIGHT,
&Wire,OLED_RESET);
void setup() {
Serial.begin(9600);
if(!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS))
//SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V
internally
{
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
}
void loop() {
text();
display.invertDisplay(true);
delay(2000);
display.invertDisplay(false);
delay(2000);
}
void text(void) {
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE); // Draw white text
display.setCursor(5,3); //setting cursor on X Y plane
display.print(F("Welcome To ...RDL..."));
display.setTextColor(SSD1306_BLACK, SSD1306_WHITE); // Draw
'inverse' text
display.display();
delay(2000);
}

Temperature Sensor

Aim:To extract information from temperature sensor
Description:To learn how to read values from a temperature sensor using ATmega328-Microcontroller.
Hardware Requirement:ATmega328-Microcontroller Development board

Procedure:

1.Connect P2 port and SV12 port using FRC cable as shown above
2. Connect the USB cable to the board.
3.Open Arduino IDE .Select Arduino Uno in boards and select COM port
4. Write the program, verify and Upload it.
5.Now you can see the output on the serial monitor.

Code


const int tempPin = 13; // pin 13 of port P2 connected to LM35 output
int Value;
double milivlt,Cel,Far;
void setup()
{
Serial.begin(9600);
}
void loop()
{
Value = analogRead(tempPin); //read sensor output value
milivlt = (Value / 2048.0) * 3300; // converting it to
millivots.
Cel = milivlt * 0.1; // calculating temperature in Celsius
Far = (Cel * 1.8) + 32; // convert from C to Fahrenheit
Serial.print(" Temperature in Celsius = ");
Serial.print(Cel);
Serial.print("*C");
Serial.print("\t Temperature in Fahrenheit = ");
Serial.print(Far);
Serial.println("*F");
delay(2000); //check the temperature every 2 second
}


Output

Real Time Stamp Data (RTC)

• This program uses the CloudPLCRTC and Cloud_PLC libraries to log real-time data to an SD card.
• In the setup function, it initializes serial communication, creates a CSV file with a header, and sets up the RTC module.
• The loop function retrieves the current date and time from the RTC, prints it to the Serial Monitor, and appends the timestamp to the CSV file every 3 seconds.


Wiring Diagram

ATmega328 Development Board


Code

#include "CloudPLCRTC.h"
#include "Cloud_PLC.h"

File myFile;
CloudPLCRTC rtc;

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

  Cloud_PLC_File_Init();
  myFile = SD.open("/real_time_data.csv", FILE_WRITE);
  if (myFile) 
{
    myFile.println("     Real Time DATA     ");
    myFile.close();
  } else
 {
    Serial.println("error opening analog_data.csv");
  }

  rtc.begin();
  // Uncomment the line below to set the RTC to the time this sketch was compiled
  //rtc.adjustToCompileTime();
  // Uncomment the line below to set the RTC to a specific date & time
  //rtc.adjustToDateTime(2024, 7, 8, 17, 41, 10);
}

void loop()
 {
  String formattedDateTime = rtc.getFormattedDateTime();
  Serial.println(formattedDateTime);
  myFile = SD.open("/real_time_data.csv", FILE_APPEND);
  if (myFile)
 {
    myFile.print(formattedDateTime);
    delay(1000);
    myFile.println();
    myFile.close();
  } else
 {
    Serial.println("error opening real_time_data.csv");
  }
  Serial.println();
  delay(3000);
}


Note

ATmega328 Development Board Libraries, User Manuals and Installation guides look into the download section.
ATmega328 Development Board Install the Cloud PLC libraries(cloudplc.h) before getting start with coding. Download
ATmega328 Development Board Above download link, you will find all the IO functionalities included in the Cloud PLC library.
ATmega328 Development Board In the Arduino IDE, go to the Boards Manager, select the ESP32 board, and ensure that you have selected the board version is 1.0.4.


Digital Input WiFi Interface - JSON

• This program uses the Cloud_PLC library to connect to a WiFi network and send JSON data.
• In the setup function, it initializes serial communication, configures the WiFi connection, and sends an initial JSON payload.
• The loop function continuously checks the state of a digital input (IN1), prints its state to the Serial Monitor, and sends updated JSON data to a specified URL every 2 seconds.


Wiring Diagram

ATmega328 Development Board


Code

#include "Cloud_PLC.h"  // Include the header file for Cloud_PLC library

void setup()
{
  Serial.begin(115200); 
 // Initialize serial communication at 115200 baud rate
  Cloud_PLC_initialisation();
  Cloud_PLC_Config_WIFI("your SSID", "your password");
  Serial.println("Connecting to WiFi...");            // Call the initialization function for Cloud_PLC
  Serial.println("Sending initial JSON data...");
  Cloud_PLC_JSON("URL", "state", "Initial State"); 
  Serial.println("Initial JSON data sent!");
}
void loop()
{
  // Check the digital input state of DI1
  const char* inputState;
  if (Cloud_PLC_Digital_Read(DI1) == HIGH)
  {
    inputState = "HIGH";
  } else
  {
    inputState = "LOW";
  }

  // Print the digital input state to the Serial Monitor
  Serial.println(inputState);

  // Send the JSON data
  Cloud_PLC_JSON("https://yourURL.com/CloudplcTest.php", "DIN", inputState);

  delay(2000);  // Wait for 2000 milliseconds (2 seconds)
}


Note

ATmega328 Development Board Libraries, User Manuals and Installation guides look into the download section.
ATmega328 Development Board Install the Cloud PLC libraries(cloudplc.h) before getting start with coding. Download
ATmega328 Development Board Above download link, you will find all the IO functionalities included in the Cloud PLC library.
ATmega328 Development Board In the Arduino IDE, go to the Boards Manager, select the ESP32 board, and ensure that you have selected the board version is 1.0.4.


Digital Input WiFi Interface - MQTT

• This program uses the Cloud_PLC library to connect to WiFi and configure MQTT communication.
• In the setup function, it initializes serial communication, sets up WiFi, and configures MQTT with provided credentials.
• The loop function checks the state of a digital input (IN1), prints the state to the Serial Monitor, and publishes the state to an MQTT topic every 2 seconds.


Wiring Diagram

ATmega328 Development Board


Code

#include "Cloud_PLC.h" // Include the header file for Cloud_PLC library
void setup()
{
  Serial.begin(115200);
  delay(500);
  // Initialize serial communication at 115200 baud rate
  Cloud_PLC_initialisation();
  Serial.println("Configuring to WiFi..."); // Call the initialization function for Cloud_PLC
  Cloud_PLC_Config_WIFI("your SSID", "your password");
  Serial.println("Configuring MQTT...");
  Cloud_PLC_Config_MQTT("yourMQTT_brocker_address", PORT, "username", "password");
  delay(1000);
}
void loop()
{
  // Check the digital input state of DI1
  const char* inputState;
  if (Cloud_PLC_Digital_Read(DI1) == HIGH)
  {
    inputState = "HIGH";
  } else
  {
    inputState = "LOW";
  }
  // Print the digital input state to the Serial Monitor
  Serial.println(inputState);
  Cloud_PLC_MQTT_Publish("DIN", inputState);

  delay(2000); // Wait for 2000 milliseconds (2 seconds)
}


Note

ATmega328 Development Board Libraries, User Manuals and Installation guides look into the download section.
ATmega328 Development Board Install the Cloud PLC libraries(cloudplc.h) before getting start with coding. Download
ATmega328 Development Board Above download link, you will find all the IO functionalities included in the Cloud PLC library.
ATmega328 Development Board In the Arduino IDE, go to the Boards Manager, select the ESP32 board, and ensure that you have selected the board version is 1.0.4.


Controlling Relay By MQTT

• This program connects an Cloud PLC to a Wi-Fi network and an MQTT broker, allowing it to receive commands to control two relays via MQTT messages.
• The relays are connected to pins 15 and 13 and can be turned on or off by publishing specific messages ("1N" or "1F" for Relay 1, "2N" or "2F" for Relay 2) to the subscribed topic "CPLRelay."
• The ESP32 maintains the connection to the MQTT broker and handles incoming messages to control the relays accordingly.


Wiring Diagram

ATmega328 Development Board

ATmega328 Development Board


Code


	#include <WiFi.h>
#include <PubSubClient.h>

// Replace these with your network credentials and MQTT details
const char* ssid = "your ssid";
const char* password = "your password";
const char* mqtt_server = "MQTT brocker address";
const int mqtt_port = your PORT number;
const char* mqtt_user = "your MQTT username"; 
const char* mqtt_password = "your password";
const char* subscribe_topic = "CPLRelay";

WiFiClient espClient;
PubSubClient client(espClient);

// Function to connect to WiFi
void setup_wifi() {
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED)
 {
    delay(500);
    Serial.print(".");
  }

  Serial.println("\nWiFi connected. IP address: ");
  Serial.println(WiFi.localIP());
}

// Callback function for when a message is received
void callback(char* topic, byte* message, unsigned int length) 
{
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");

  String messageString;
  for (int i = 0; i < length; i++)
 {
    messageString += (char)message[i];
  }
  Serial.println(messageString);

  // Control relays based on the message
  if (messageString.equals("1N")) 
{
    digitalWrite(15, HIGH);
  } else if (messageString.equals("1F")) {
    digitalWrite(15, LOW);
  } else if (messageString.equals("2N")) {
    digitalWrite(13, HIGH);
  } else if (messageString.equals("2F")) {
    digitalWrite(13, LOW);
  }
}

// Function to reconnect to MQTT broker
void reconnect()
 {
  while (!client.connected()) 
{
    Serial.print("Attempting MQTT connection...");
    if (client.connect("ESP32Client", mqtt_user, mqtt_password))
 {
      Serial.println("connected");
      client.subscribe(subscribe_topic);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void setup()
 {
  Serial.begin(115200);
  pinMode(15, OUTPUT);
  pinMode(13, OUTPUT);
  digitalWrite(15, LOW);
  digitalWrite(13, LOW);

  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
}

void loop()
 {
  if (!client.connected())
 {
    reconnect();
  }
  client.loop();
}


Note

ATmega328 Development Board Libraries, User Manuals and Installation guides look into the download section.
ATmega328 Development Board Install the Cloud PLC libraries(cloudplc.h) before getting start with coding. Download
ATmega328 Development Board Above download link, you will find all the IO functionalities included in the Cloud PLC library.
ATmega328 Development Board In the Arduino IDE, go to the Boards Manager, select the ESP32 board, and ensure that you have selected the board version is 1.0.4.


Controlling Relay Using WiFi AP

• This code configures the Cloud PLC as a Wi-Fi access point and sets up a web server listening on port 80.
• When a client connects and sends an HTTP request, the server reads the request and checks if it contains "ON" or "OFF" to control a relay through the Cloud_PLC_Relay_state function.
• The server responds with the relay's status and closes the connection after handling the request
• The access point's IP address is printed to the serial monitor for client connection.


Wiring Diagram

ATmega328 Development Board

ATmega328 Development Board


Code

#include "Cloud_PLC.h"
#include <WiFi.h>

  const char* apSSID = "your ssid";       //your SSID
const char* apPassword = "your password"; //Your PASSWORD
WiFiServer server(80);

  void setup()
 {
  Serial.begin(115200);
  setupAccessPoint();        // Set up ESP32 as an access point Cloud_PLC_initialisation();                         
                            // Initialize the Cloud PLC library
  server.begin();            // Start the server
  Serial.println("Server started");
}

void loop() 
{
  WiFiClient client = server.available();  // Check if a client has connected
  if (client) 
{
  while (client.connected() && !client.available()) 
{  // Wait for data from the client
      delay(1);
}

    String request = client.readStringUntil('\r');  // Read the first line of the request
    Serial.println(request);   

 if (request.indexOf("ON") != -1)
 {  // Process the request
      Cloud_PLC_Relay_state(0, HIGH);   // Turn on Relay
      client.println("Relay turned ON");
    } else if (request.indexOf("OFF") != -1)
 {
      Cloud_PLC_Relay_state(0, LOW);  // Turn off Relay
      client.println("Relay turned OFF");
    } else 
{
      client.println("Invalid command");
    }

    // Close the connection
    client.stop();
  }
}
void setupAccessPoint() 
{
  WiFi.softAP(apSSID, apPassword);  // Set up the ESP32 as an access point
  delay(100);
  Serial.println("Access Point IP Address: " + WiFi.softAPIP().toString());
}


Note

ATmega328 Development Board Libraries, User Manuals and Installation guides look into the download section.
ATmega328 Development Board Install the Cloud PLC libraries(cloudplc.h) before getting start with coding. Download
ATmega328 Development Board Above download link, you will find all the IO functionalities included in the Cloud PLC library.
ATmega328 Development Board In the Arduino IDE, go to the Boards Manager, select the ESP32 board, and ensure that you have selected the board version is 1.0.4.


Digital Input Interface - Bluetooth

• This program uses the Cloud_PLC library and Bluetooth Serial to monitor a digital input (IN1) and communicate its state.
• In the setup function, it initializes serial communication for both the Serial Monitor and Bluetooth, allowing pairing with the Bluetooth device named "Cloud_PLC."
• The loop function checks if IN1 is HIGH or LOW, prints the state to both the Serial Monitor and a paired Bluetooth device, and updates every 500 milliseconds.


Code

#include "Cloud_PLC.h"
#include "BluetoothSerial.h"
//Include the header file for Cloud_PLC library
BluetoothSerial SerialBT;

void setup()
{
  Serial.begin(115200);
  SerialBT.begin("Cloud_PLC");
  Serial.print("The device started, Now you can pair it with bluetooth");
  //Initialize serial communication at 115200 baud rate
  Cloud_PLC_initialisation();
  //Call the initialization function for Cloud_PLC
}

void loop()

{
  // Check the digital input state of DI1

  if (Cloud_PLC_Digital_Read(DI1) == HIGH)  //input channel, IN1,IN2,IN3,IN4,IN4
  {
    Serial.println("HIGH");
    SerialBT.println("HIGH");
    // Print "ON" to the Serial Monitor if IN1 is HIGH
    delay(500);

  }
  else
  {
    Serial.println("LOW");
    SerialBT.println("LOW");    // Print "OFF" to the Serial Monitor if IN1 is not
    delay(500);
    // Wait for 2000 milliseconds (2 seconds)

  }
}


Note

ATmega328 Development Board Libraries, User Manuals and Installation guides look into the download section.
ATmega328 Development Board Install the Cloud PLC libraries(cloudplc.h) before getting start with coding. Download
ATmega328 Development Board Above download link, you will find all the IO functionalities included in the Cloud PLC library.
ATmega328 Development Board In the Arduino IDE, go to the Boards Manager, select the ESP32 board, and ensure that you have selected the board version is 1.0.4.


Controlling Relay By Bluetooth

• This code sets up an Cloud PLC to control two relays via Bluetooth.
• It initializes the relays as outputs and starts Bluetooth communication with a device name "CPL_Relays."
• In the loop function, it listens for incoming Bluetooth commands to control the relays: "ON1" and "OFF1" for Relay 1, and "ON2" and "OFF2" for Relay 2. It also provides feedback over Bluetooth and prints received commands for debugging.


Code

#include <BluetoothSerial.h>
  
  // Define the relay pins
  #define RELAY1_PIN 15
  #define RELAY2_PIN 13
  
  // Create a BluetoothSerial object
  BluetoothSerial SerialBT;
  
  void setup()
  {
    // Initialize serial communication for debugging
    Serial.begin(115200);
  
    // Initialize the relay pins as outputs
    pinMode(RELAY1_PIN, OUTPUT);
    pinMode(RELAY2_PIN, OUTPUT);
  
    // Set the relays to be off initially
    digitalWrite(RELAY1_PIN, LOW);
    digitalWrite(RELAY2_PIN, LOW);
  
    // Begin serial communication over Bluetooth
    SerialBT.begin("CPL_Relays"); // Bluetooth device name
    Serial.println("Bluetooth device started, you can now pair it with Bluetooth!");
  }
  
  void loop()
     {
    // Check if data is available on the Bluetooth serial
    if (SerialBT.available()) 
     {
      // Read the incoming string
      String request = SerialBT.readStringUntil('\n');
  
 // Print the received string to the Serial Monitor (for debugging)

      Serial.print("Received: ");
      Serial.println(request);
  
      // Control the relays based on the received command
      if (request.indexOf("ON1") != -1) 
      {
        digitalWrite(RELAY1_PIN, HIGH); // Turn Relay 1 on
        SerialBT.println("Relay 1 turned ON");
      }
      else if (request.indexOf("OFF1") != -1)
      {
        digitalWrite(RELAY1_PIN, LOW); // Turn Relay 1 off
        SerialBT.println("Relay 1 turned OFF");
      }
      else if (request.indexOf("ON2") != -1) 
      {
        digitalWrite(RELAY2_PIN, HIGH); // Turn Relay 2 on
       
      SerialBT.println("Relay 2 turned ON");
      }
      else if (request.indexOf("OFF2") != -1)
      {
        digitalWrite(RELAY2_PIN, LOW); // Turn Relay 2 off
        SerialBT.println("Relay 2 turned OFF");
      }
      else 
      {
        SerialBT.println("Invalid command");
      }
    }
  }


Note

ATmega328 Development Board Libraries, User Manuals and Installation guides look into the download section.
ATmega328 Development Board Install the Cloud PLC libraries(cloudplc.h) before getting start with coding. Download
ATmega328 Development Board Above download link, you will find all the IO functionalities included in the Cloud PLC library.
ATmega328 Development Board In the Arduino IDE, go to the Boards Manager, select the ESP32 board, and ensure that you have selected the board version is 1.0.4.


Embedded Webserver

• This program sets up a web server using a Cloud PLC to control two relays through a web interface.
• In the setup function, it initializes serial communication, connects to Wi-Fi, and starts the web server.
• The loop function listens for incoming HTTP requests, parses them to control the relays based on the URL path, and serves a simple HTML page to control the relays.
• It updates the relay states and serves the appropriate HTML based on user interactions with the web page.


Wiring Diagram

ATmega328 Development Board


Code

#include <Cloud_PLC.h>

WiFiServer server(80);  // Set web server port number to 80
String header;          // Variable to store the HTTP request
const int relayPin1 = 15;  // Relay pins
const int relayPin2 = 13;  // Relay pins                     
String relayState1 = "OFF";    // Current state of the relays
String relayState2 = "OFF";

void setup()
{
  Serial.begin(115200);
  pinMode(relayPin1, OUTPUT); // Initialize the relay pins as outputs
  pinMode(relayPin2, OUTPUT);
  digitalWrite(relayPin1, LOW);
  digitalWrite(relayPin2, LOW);

  Cloud_PLC_Config_WIFI("TEST", "12345678");  // Connect to Wi-Fi network
  server.begin();  // Start the server
}
void loop()
{
  WiFiClient client = server.available();   // Listen for incoming clients
  if (client)
  { // If a new client connects,
    Serial.println("New Client.");          // Print a message out in the serial port
    String currentLine = "";                // Make a String to hold incoming data from the client
    while (client.connected())
    { // Loop while the client's connected
      if (client.available())
     
 { // If there's bytes to read from the client,
        char c = client.read();             // Read a byte, then
        Serial.write(c);                    // Print it out the serial monitor
        header += c;
        if (c == '\n')
        { // If the byte is a newline character
          if (currentLine.length() == 0)
          

{ // If the current line is blank, you got two newline characters in a row.
            // That's the end of the client HTTP request, so send a response:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            client.println("<style>body { text-align: center; font-family: Arial; } .button { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } .button2 {background-color: #ff0000;}</style></head>");
            client.println("<body><h1>Cloud PLC Relay Control</h1>");

            client.println("<p>Relay 1 - State " + relayState1 + "</p>");
            if (relayState1 == "OFF")
            {
              client.println("<p><a href=\"/relay1/on\"><button class=\"button\">ON</button></a></p>");
            } else
            {
              client.println("<p><a href=\"/relay1/off\"><button class=\"button button2\">OFF</button></a></p>");
            }
            client.println("<p>Relay 2 - State " + relayState2 + "</p>");
            if (relayState2 == "OFF")
            {
              client.println("<p><a href=\"/relay2/on\"><button class=\"button\">ON</button></a></p>");
            } else
            {
              client.println("<p><a href=\"/relay2/off\"><button class=\"button button2\">OFF</button></a></p>");
            }
            client.println("</body></html>");   
            client.println();   // The HTTP response ends with another blank line
            break;  // Break out of the while loop
          } 
         else
          { // If you got a newline, then clear currentLine
            currentLine = "";
          }
        } 
          else if (c != '\r')
        { // If you got anything else but a carriage return character,
          currentLine += c;      // Add it to the end of the currentLine
        }
        // Check if the client request is to turn relay 1 on or off
        if (header.indexOf("GET /relay1/on") >= 0)
        {
          relayState1 = "ON";
          digitalWrite(relayPin1, HIGH);
        } else if (header.indexOf("GET /relay1/off") >= 0)
        {
          relayState1 = "OFF";
          digitalWrite(relayPin1, LOW);
        }
        // Check if the client request is to turn relay 2 on or off
        if (header.indexOf("GET /relay2/on") >= 0)
        {
          relayState2 = "ON";
          digitalWrite(relayPin2, HIGH);
        } else if (header.indexOf("GET /relay2/off") >= 0)
        {
          relayState2 = "OFF";
          digitalWrite(relayPin2, LOW);
        }
      }
    }
    // Clear the header variable
    header = "";
    client.stop();  // Close the connection
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}


Note

ATmega328 Development Board Libraries, User Manuals and Installation guides look into the download section.
ATmega328 Development Board Install the Cloud PLC libraries(cloudplc.h) before getting start with coding. Download
ATmega328 Development Board Above download link, you will find all the IO functionalities included in the Cloud PLC library.
ATmega328 Development Board In the Arduino IDE, go to the Boards Manager, select the ESP32 board, and ensure that you have selected the board version is 1.0.4.