LED on off Simple
int LED=13;
void setup() {
// put your setup code here, to run once:
pinMode(LED,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(LED,LOW);
delay(100);
digitalWrite(LED,HIGH);
delay(100);
}
LED Using PWM
// Define the analog input pin for the sensor
int sensorPin = A0;
// Define the digital output pin for the LED
int LED = 13;
// Variable to store the sensor reading
int sensorValue = 0;
// Variable to store the PWM value for the LED
int PWMin;
void setup() {
// Set the LED pin as OUTPUT
pinMode(LED, OUTPUT);
}
void loop() {
// Read the analog value from the sensor
sensorValue = analogRead(sensorPin);
// Map the sensor value to a PWM range (0 to 255)
PWMin = map(sensorValue, 0, 1023, 0, 255);
// Apply the PWM value to control the LED brightness
analogWrite(5, PWMin);
}
3_TX_RX_Last_Version
// Include the SoftwareSerial library to enable software-based serial
communication
#include <SoftwareSerial.h>
// Create a SoftwareSerial object named myserial with RX on pin 2 and
TX on pin 3
SoftwareSerial myserial(11,12);
// Variables for handling LED state and communication
bool LEDVal;
char RxDta;
int LEDOut = 13; // Connect the LED to pin 13
int ButtonIn = 4; // Connect the button to pin 4
bool buttonPressed = false;
// The setup function runs once when you press reset or power the
board
void setup() {
// Set LEDOut and ButtonIn pins as output and input, respectively
pinMode(LEDOut, OUTPUT);
pinMode(ButtonIn, INPUT);
// Initialize SoftwareSerial communication with a baud rate of 9600
myserial.begin(9600);
// Initialize LEDVal to false and turn off the LED initially
LEDVal = false;
digitalWrite(LEDOut, LEDVal);
}
// The loop function runs repeatedly
void loop() {
// Check if the button connected to ButtonIn is pressed
if (!digitalRead(ButtonIn) == LOW) {
buttonPressed = true; // Button is pressed
// Delay for 2 seconds to check if the button is held
delay(200);
// Check again if the button is still pressed after 2 seconds
if (digitalRead(ButtonIn) == LOW) {
myserial.print('A'); // Send 'A' over serial
}
} else {
buttonPressed = false; // Button is not pressed
}
// Check if there is data available to read from SoftwareSerial
if (myserial.available() > 0) {
RxDta = (char)myserial.read();
// If the received character is 'A', toggle LED state and update
the LED
if (RxDta == 'A') {
LEDVal = true;
digitalWrite(LEDOut, LEDVal);
}
// Delay for 1 second (1000 milliseconds)
delay(1000);
digitalWrite(LEDOut, LOW); // Turn off the LED
RxDta = 'B'; // Reset RxDta
}
}
4_DHTtester_With_Comments
// REQUIRES the following Arduino libraries:
// DHT Sensor Library:
// Adafruit Unified Sensor Lib
#include "DHT.h"
#define DHTPIN 2 // Define the pin to which the DHT sensor is
connected
// Define the type of DHT sensor (DHT11 in this case)
#define DHTTYPE DHT11 // DHT 11
/* How connect wires!!!
________________________________________________________
Connect pin 1 (on the left) of the sensor to +5V
Connect pin 2 of the sensor to whatever your DHTPIN is
Connect pin 3 (on the right) of the sensor to GROUND (if your sensor
has 3 pins)
Connect pin 4 (on the right) of the sensor to GROUND and leave the
pin 3 EMPTY (if your sensor has 4 pins)
________________________________________________________
*/
// Initialize DHT sensor.
// Create a DHT object.
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// Start serial communication
Serial.begin(9600);
// Print a message to the serial monitor
Serial.println(F("DHTxx test!"));
/* IMPORTANT
______________________________________________________
In Arduino programming, the F() macro is used to store string
literals (constant strings) in flash memory (program memory) instead
of RAM.
Without the F() macro, the string would be stored in RAM, which is
more limited than flash memory on most Arduino boards.
______________________________________________________
*/
// Initialize the DHT sensor
dht.begin();
}
void loop() {
// Wait a few seconds between measurements.
delay(2000);
// Read humidity and temperature values from the DHT sensor
// Reading temperature or humidity takes about 250 milliseconds!
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
// Check if any of the sensor readings are NaN (Not a Number).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Calculate heat index based on temperature and humidity
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
// Print the sensor readings and calculated heat index to the serial
monitor
Serial.print(F("Humidity: "));
Serial.print(h);
Serial.print(F("% Temperature: "));
Serial.print(t);
Serial.print(F("°C "));
Serial.print(f);
Serial.print(F("°F Heat index: "));
Serial.print(hic);
Serial.print(F("°C "));
Serial.print(hif);
Serial.println(F("°F"));}
5_Clock
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// OLED display dimensions
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
// The pins for I2C are defined by the Wire-library.
// On an Arduino UNO: A4(SDA), A5(SCL)
// On an Arduino MEGA 2560: 20(SDA), 21(SCL)
#define OLED_RESET -1 // Reset pin # (or -1 if
sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C // See datasheet for Address;
0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire,
OLED_RESET);
unsigned long MilSeconds = 0,Second = 0, Min = 0, Hours = 0 ;
void setup() {
Serial.begin(115200);
// Initialize the SSD1306 display
if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;)
; // Don't proceed, loop forever
}
}
void loop() {
// Update time values based on millis()
MilSeconds = millis() % 1000;//Just used to print time one time only
every 1 Second
Second = millis() / 1000;
Min = millis() / 60000;
Hours = millis() / 360000;
// Update display when milliseconds reach zero
if (MilSeconds == 0) {
// Clear the display buffer
display.clearDisplay();
// Set cursor position and display time in HH:MM:SS format
display.setCursor(1, 10);
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
display.print(" ");
// Add leading zeros for formatting
if (Hours % 24 < 10) {
display.print("0");
}
display.print((Hours) % 24, 1);
display.print(":");
if (Min % 60 < 10) {
display.print("0");
}
display.print(Min % 60, 1);
display.print(":");
if (Second % 60 < 10) {
display.print("0");
}
display.print(Second % 60, 1);
// Display the updated content
display.display();
}
}
Stop_Watch_on_OLED_and_Serial
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
#define SCREEN_ADDRESS 0x3C
// Initialize the SSD1306 display with specified dimensions and reset
pin
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire,
OLED_RESET);
int sw = 3; // Switch input pin
int value; // Variable to store switch value
int i = 0; // State variable for the stopwatch
unsigned long imsec = 0;
unsigned long isec = 0;
unsigned long imin = 0;
unsigned long ihours = 0;
unsigned long sec = 0;
unsigned long min = 0;
unsigned long hours = 0;
void setup() {
Serial.begin(115200);
// Initialize the SSD1306 display
if (!display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;)
; // Loop indefinitely if display initialization fails
}
display.display();
pinMode(sw, INPUT);
}
void printTime(unsigned long msec,unsigned long Sec, unsigned long
Min, unsigned long Hours) {
if(msec==0){
display.clearDisplay();
display.setCursor(1, 10);
display.setTextSize(2);
display.setTextColor(SSD1306_WHITE);
display.print(" ");
if(Hours % 24<10){ display.print("0");}
display.print(Hours % 24, 1);
display.print(":");
if(Min % 60<10){ display.print("0");}
display.print(Min % 60, 1);
display.print(":");
if(Sec % 60<10){ display.print("0");}
display.print(Sec % 60, 1);
display.display();
Serial.print(Hours % 24);
Serial.print(":");
Serial.print(Min % 60);
Serial.print(":");
Serial.println(Sec % 60);
}
}
void loop() {
imsec = millis()%1000;
switch (i) {
case 0:
// Display initial time
printTime(imsec,0, 0, 0);
value = digitalRead(sw);
if (value == 0) {
delay(200);
isec = millis() ;
imin = millis() ;
ihours = millis() ;
i++;
}
break;
case 1:
// Running stopwatch
sec = millis()-isec ;
min = millis()-imin ;
hours = millis()-ihours ;
printTime(imsec,sec / 1000, (min / 1000) / 60, (hours / 1000) /
3600);
value = digitalRead(sw);
if (value == 0) {
delay(200);
i++;
}
break;
case 2:
// Pause display
printTime(imsec,sec / 1000, (min / 1000) / 60, (hours / 1000) /
3600);
value = digitalRead(sw);
if (value == 0) {
delay(200);
i = 0;
}
break;
}
}
7_Resistance_Meater
int v1,v2;
float vx,vy;
float I;
float Resistance;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
Resistance =0;
for(int x=0;x<50;x++){
v1=analogRead(A0);
v2=analogRead(A1);
vx=5.0-(v1*5.0/1023.0);// fixed resistor to measuer current
vy=(v1-v2)*5.0/1023.0; // variable resistor
I=vx/1000.0;
Resistance+=(vy/I);
}
Serial.print("Resistance = ");
Serial.print(Resistance/50.0);
Serial.println(" Ω");
delay(500);
}
8_Frequancy_Counter_Simple
// Define the pin for frequency measurement
const int FreqPin = 3;
// Variables to keep track of frequency counting
long Cnt;
bool Prevstate, CurrentState;
long T;
void setup() {
// Set up the pin mode for input
pinMode(FreqPin, INPUT);
// Initialize serial communication for debugging
Serial.begin(115200);
// Initialize variables
Cnt = 0; // Counter for frequency measurement
Prevstate = false; // Previous state of the input pin
CurrentState = 0; // Current state of the input pin
T = micros(); // Initialize time for one-second intervals
}
void loop() {
// Read the current state of the input pin
CurrentState = digitalRead(FreqPin);
// Check for a rising or falling edge and increment count
if (CurrentState != Prevstate) {
Cnt++;
}
// Update the previous state for the next iteration
Prevstate = CurrentState;
// Check if one second has elapsed
if (micros() - T > 1000000) {
// Calculate and print the frequency to the Serial Monitor
Serial.println(Cnt / 2.0);
// Reset the count and update the time for the next second
Cnt = 0;
T = micros();
}
}
9_Frequency_Counter_Final
// Frequency Counter using Arduino
// D4 and D3 generate a 1 Hz and 250 Hz square wave, respectively.
// Input frequency to be measured is connected to pin D5.
// Variable to store overflow count
byte overF = 0;
// Variables to store frequency and period
unsigned long freq;
double period;
void setup() {
// Initialize serial communication
Serial.begin(115200);
// Configure Timer0 for 1 Hz PWM on D4
OCR0A = 249;
TCCR0A = _BV(WGM00) | _BV(WGM01) | _BV(COM0A0); // Set fast PWM mode
and clear on compare match
TCCR0B = _BV(WGM02) | _BV(CS02) | _BV(CS01); // Set prescaler to
256, start Timer0
pinMode(6, OUTPUT); // Configure D4 as output
// Configure Timer2 for 250 Hz PWM on D3
OCR2A = 249;
OCR2B = 125;
TCCR2A = _BV(COM2B1) | _BV(COM2B0) | _BV(WGM21) | _BV(WGM20); // Set
fast PWM mode and non-inverting mode
TCCR2B = _BV(WGM22) | _BV(CS22) | _BV(CS21); // Set
prescaler to 256, start Timer2
pinMode(3, OUTPUT); // Configure D3 as output
// Configure Timer1 for frequency measurement on D5
OCR1A = 32767; // Set comparison value for Timer1
TCCR1A = _BV(WGM10) | _BV(WGM11) | _BV(COM1A0); // Set fast PWM mode
and clear on compare match
TCCR1B = _BV(WGM12) | _BV(WGM13) | _BV(CS12) | _BV(CS11); // Set
prescaler to 256, start Timer1
pinMode(9, OUTPUT); // Configure D5 as output
// Print initialization message
Serial.println("Frequency Counter");
}
// Function to measure the frequency on D5
void ReadFreq() {
// Wait for the input signal to go high
while (digitalRead(6)) {}
// Wait for the input signal to go low
while (!digitalRead(6)) {}
// Start the count
TIFR1 = _BV(OCF1A); // Reset the Timer1 overflow interrupt flag
OCR1A = 32767; // Set comparison value for Timer1
TCNT1 = 0; // Reset Timer1 counter
overF = 0; // Reset overflow count
// Wait for the input signal to go high again
while (digitalRead(6)) {
// Check for Timer1 overflow
if (TIFR1 & (1 << OCF1A)) {
++overF;
TIFR1 = _BV(OCF1A); // Reset the Timer1 overflow interrupt flag
}
}
// Measurement complete, calculate frequency and period
freq = (unsigned long)TCNT1 + ((unsigned long)overF * 32768);
period = 1000000 / (double)freq;
if (freq == 0) {
period = 0;
}
}
void loop() {
// Call the function to measure frequency
ReadFreq();
// Print the measured frequency
Serial.print("F= ");
Serial.println(freq);
}
10_PF_Capacitor_Meter
// Variable declarations
float Cx; // Calculated capacitance
float Co; // Reference capacitance
long Vo; // Voltage across the capacitor
int DPin = A2; // Digital pin for charging the capacitor
int AIn = A0; // Analog pin for reading the voltage across the
capacitor
void setup() {
pinMode(AIn, INPUT); // Set the analog pin as input
pinMode(DPin, OUTPUT); // Set the digital pin as output for
charging
digitalWrite(DPin, LOW); // Set the charging pin low initially
Serial.begin(115200); // Initialize serial communication
Co = 23.2; // Reference capacitance value
Serial.println("Reading PF capacitance"); // Serial print for
initialization
delay(1000); // Delay for 1 second
}
void loop() {
Vo = 0.0; // Initialize voltage variable
// Perform 100 readings to average
for (int i = 0; i < 100; i++) {
pinMode(AIn, INPUT); // Set analog pin as input
digitalWrite(DPin, HIGH); // Start charging the capacitor
Vo = Vo + analogRead(AIn); // Read the voltage across the
capacitor
pinMode(AIn, OUTPUT); // Discharge the A/D capacitor
digitalWrite(DPin, LOW); // Stop charging the capacitor
}
Vo = Vo / 100; // Average the 100 readings
// Check for saturation (Vo > 1022) and limit to 1022
if (Vo > 1022) {
Vo = 1022;
}
// Calculate capacitance using the formula
Cx = Co * Vo / (1023 - Vo);
// Ensure Cx is not negative
if (Cx <= 0) {
Cx = 0.0;
}
// Print the calculated capacitance to the serial monitor
Serial.println(Cx);
delay(1000); // Delay for 1 second before the next iteration
}
11_Capacitor_Meter_RC_Method
// Variable declarations
float Ce; // Initial offset capacitance
float Cx; // Calculated capacitance
int Rext; // External resistor value
int DigPin = A5; // Digital pin for controlling the circuit
int AngPin = A0; // Analog pin for measuring voltage across the
capacitor
long Tm; // Time variable
String Txt; // String for storing capacitance unit ("nF" or "uF")
void setup() {
// Set pin modes and initial values
pinMode(DigPin, OUTPUT); // Digital pin for charging the capacitor
pinMode(AngPin, INPUT); // Analog pin for reading the voltage
digitalWrite(DigPin, LOW); // Set charging pin low initially
Ce = 0.0; // Initialize initial offset capacitance
Rext = 10; // Set external resistor value
Serial.begin(115200); // Initialize serial communication
delay(1000); // Delay for 1 second
}
void loop() {
digitalWrite(DigPin, HIGH); // Start charging the capacitor
Tm = micros(); // Record the current time in
microseconds
// Wait until the voltage across the capacitor reaches 3.16 volts
while (analogRead(AngPin) < 646) {}
Tm = micros() - Tm; // Calculate the time taken for the capacitor to
charge
Cx = (float)(Tm / Rext) - Ce; // Calculate capacitance using the
time constant formula
// Alternatively, you can use the following line to calculate
capacitance:
// Cx = (1.0 * Tm / Rext) - Ce;
Txt = " nF"; // Default unit is nanofarads
// Convert to microfarads if capacitance is greater than 1000 nF
if (Cx > 1000) {
Txt = " uF";
Cx = Cx / 1000;
}
// Print the capacitance value to the serial monitor with two
decimal places
Serial.print("Capacitance Value= ");
Serial.print(Cx, 2);
Serial.println(Txt);
digitalWrite(DigPin, LOW); // Stop charging the capacitor
delay(2000); // Delay for 2 seconds before the next iteration
}