More search type here...

January 5, 2024

Running LED Knight Rider using Arduino

 Schematic


 The code:

int ledPins[] = {13, 12, 11, 10, 9, 8, 7, 6,5,4};
int numLEDs = sizeof(ledPins) / sizeof(ledPins[0]);
int delayTime = 80; // Waktu tunda dalam milidetik

void setup() {
  for (int i = 0; i < numLEDs; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
}

void loop() {
  for (int i = 0; i < numLEDs; i++) {
    digitalWrite(ledPins[i], HIGH);
    delay(delayTime);
    digitalWrite(ledPins[i], LOW);
  }
  for (int i = numLEDs - 1; i >= 0; i--) {
    digitalWrite(ledPins[i], HIGH);
    delay(delayTime);
    digitalWrite(ledPins[i], LOW);
  }
}


Use Arduino as Bateray AA Checker

 Schematic


 
Maximum input voltage measurement is 5 volt as maximum internal ADC in IC Atmega328. If want to expand measurement can use voltage divider circuit.  

The code:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 16, 2);  // Alamat I2C untuk LCD 16x2

const int sensorPin = A0;  // Pin sensor tegangan
const int redLedPin = 8;   // Pin LED merah
const int yellowLedPin = 9;  // Pin LED kuning
const int greenLedPin = 10;  // Pin LED hijau

void setup() {
  lcd.begin(16, 2);  // Inisialisasi LCD
  lcd.backlight();   // Aktifkan backlight LCD
  pinMode(redLedPin, OUTPUT);
  pinMode(yellowLedPin, OUTPUT);
  pinMode(greenLedPin, OUTPUT);
}

void loop() {
  // Baca tegangan dari sensor
  int sensorValue = analogRead(sensorPin);

  // Konversi nilai sensor menjadi tegangan (0-5V)
  float voltage = sensorValue * (5.0 / 1023.0);

  // Tampilkan tegangan di LCD
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Tegangan: ");
  lcd.print(voltage);
  lcd.print("V");
  lcd.setCursor(0, 1);
  lcd.print("Sensor: ");
  lcd.print(sensorValue);
  lcd.print(" ADC");
  // Tentukan warna LED sesuai dengan rentang tegangan
  if (voltage >= 0.0 && voltage <= 0.6) {
    digitalWrite(redLedPin, HIGH);
    digitalWrite(yellowLedPin, LOW);
    digitalWrite(greenLedPin, LOW);
  } else if (voltage > 0.6 && voltage <= 1.2) {
    digitalWrite(redLedPin, LOW);
    digitalWrite(yellowLedPin, HIGH);
    digitalWrite(greenLedPin, LOW);
  } else if (voltage > 1.2 ) {
    digitalWrite(redLedPin, LOW);
    digitalWrite(yellowLedPin, LOW);
    digitalWrite(greenLedPin, HIGH);
  }

  delay(1000);  // Tunda selama 1 detik sebelum membaca ulang tegangan
}



 

August 5, 2023

Arduino coding for display LCD 16x2 using I2C wire

 Arduino code to display text on a 16x2 LCD using the I2C wire library and an I2C LCD module (PCF8574):




First, make sure you have installed the "LiquidCrystal_I2C" library. If you haven't, you can download it from the Library Manager in the Arduino IDE.

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// Set the LCD address (0x27 or 0x3F) according to your module
#define I2C_ADDR 0x27

// Set the LCD size (16x2)
#define LCD_COLUMNS 16
#define LCD_ROWS 2

// Create an instance of the LCD object
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_ROWS);

void setup() {
  // Initialize the LCD
  lcd.begin(LCD_COLUMNS, LCD_ROWS);

  // Turn on the backlight (if available)
  lcd.backlight();

  // Write text to the LCD
  lcd.print("Hello, World!");
}

void loop() {
  // Add your code here (if needed)
}


In this example, we use the "LiquidCrystal_I2C" library to simplify the communication between the Arduino and the I2C LCD module (PCF8574). The library provides functions like lcd.print(), lcd.setCursor(), lcd.clear(), and more to control the LCD easily.

Make sure you have connected the SDA and SCL pins of the I2C module to the corresponding pins on your Arduino. Also, don't forget to provide power and ground connections.

Before uploading the code to your Arduino, double-check the I2C address of your LCD module. If it's different from 0x27, update the line #define I2C_ADDR 0x27 with the correct address.

That's it! Now you should be able to see the "Hello, World!" message on your 16x2 LCD connected via I2C. Good luck with your project!

March 5, 2023

Color sensor calibration TCS 3200

Calibrating a color sensor like the TCS 3200 typically involves a few steps to ensure accurate color readings. Here's a general outline of the calibration process:

  1. Clean the sensor: Before calibrating the sensor, make sure it is free from dust and debris that could affect its readings. Use a clean cloth or compressed air to remove any contaminants from the sensor surface.
  2. Choose a calibration surface: Next, select a surface to use as your calibration target. Ideally, this surface should be a neutral color (e.g. white or gray) and have a matte finish to minimize reflections. You may also want to choose a surface that is representative of the types of colors you'll be measuring with the sensor.
  3. Measure the target: Place the calibration target under the sensor and measure its color using the sensor's built-in LEDs. Record the RGB values for the target color.
  4. Calculate correction factors: Compare the measured RGB values to the expected values for the target color, and calculate correction factors to adjust the sensor's readings. For example, if the sensor consistently reads red as slightly brighter than expected, you could apply a correction factor to decrease the reported red value.
  5. Apply correction factors: Once you have calculated correction factors for each color channel, apply them to the sensor's readings. You may need to adjust the correction factors over time as the sensor's performance changes or you encounter different lighting conditions.

Note that the exact calibration process may vary depending on your specific sensor and application. Be sure to consult the manufacturer's documentation for detailed instructions and recommended best practices.



To calibrate the TCS3200 color sensor, you can follow these steps:

  1. First of all, connect the TCS3200 sensor to the Arduino board and install the basic programming code which will read the colors from the sensor and display them on the serial monitor.
  2. Place the sensor on a white surface, then read the RGB color values on the serial monitor. Make sure the RGB value on white is around (255,255,255). If not, you can adjust the gain value on the sensor to optimize color readability.
  3. After setting the gain, place the sensor on a black surface and read the RGB color values on the serial monitor. Make sure the RGB value on black is around (0,0,0).
  4. After adjusting white and black, you can use other colors for reference such as red, green, blue or other colors. Make sure the resulting RGB value is as expected.
  5. Finally, you can adjust the integration time (INTEG) on the sensor to optimize color rendering. The longer the integration time, the more accurate the color reading results, but the slower the data processing speed. You can try to time the integration from 2,4,8,16, and 32 clock cycles.

Here is an example of basic program code to read RGB values on the TCS3200 color sensor:

#include <Adafruit_TCS3200.h>
Adafruit_TCS3200 colorSensor(TCS3200_S2, TCS3200_S3, TCS3200_OUT);
void setup() {
  Serial.begin(9600);
  colorSensor.begin();
}
void loop() {
  colorSensor.setResolution(TCS3200_18BIT);
  colorSensor.writeRegister(0x00, TCS3200_MEASUREMENT_MODE);
  delay(50);
   uint16_t red = colorSensor.readRed();
  uint16_t green = colorSensor.readGreen();
  uint16_t blue = colorSensor.readBlue();
  Serial.print("RGB: ");
  Serial.print(red);
  Serial.print(" ");
  Serial.print(green);
  Serial.print(" ");
  Serial.println(blue);
}

You can calibrate the sensor by changing the gain and integration time in the following sections:

colorSensor.setGain(TCS3200_GAIN_1X);
colorSensor.setIntegrationTime(TCS3200_INTEGRATIONTIME_2_4MS);

If the color reading results are still not accurate, you can try adjusting the gain and integration time until the resulting RGB values are as expected.



February 6, 2023

Arduino code for play vocal

This code uses the SoftwareSerial library to create a serial communication between the Arduino and a Bluetooth module. The Bluetooth module should be connected to the specified RX and TX pins and set to 9600 baud rate.

Note that this code is just a basic example and may need modifications depending on the specific setup and requirements.

#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup() {
  mySerial.begin(9600);
  pinMode(9, OUTPUT);
  digitalWrite(9, LOW);
}
void loop() {
  if (mySerial.available()) {
    digitalWrite(9, HIGH);
    mySerial.write(mySerial.read());
  }
}

 

 

February 2, 2023

IOT arduino logging data to web server

To log data from an Arduino IoT device to a web server, you can follow these general steps:

  1. Connect the Arduino to the internet, either through Wi-Fi or Ethernet.
  2. Use a library such as the HTTPClient library to make HTTP requests to the server.
  3. Write code to format the data you want to log into a JSON or CSV string.
  4. Send the data as a POST request to a server-side script (e.g. PHP, Python, Node.js) that can receive and store the data in a database.
  5. On the server side, use a database management system such as MySQL or MongoDB to store the data.
  6. Optionally, you can also retrieve the data from the database and display it on a web page.
Here is an example of sending data from an Arduino to a server:

#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid     = "your_SSID";
const char* password = "your_PASSWORD";
const char* serverName = "your_SERVER_IP_ADDRESS";

void setup() {
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
}

void loop() {
  HTTPClient http;
  http.begin("http://" + String(serverName) + "/data");
  http.addHeader("Content-Type", "application/json");
  int httpResponseCode = http.POST("{\"value\":\"" + String(analogRead(A0)) + "\"}");
  String response = http.getString();
  Serial.println(httpResponseCode);
  Serial.println(response);
  http.end();
  delay(10000);
}

Here some example to temperature logging by LM35 temperature sensor:


Here is an example of how you could log temperature data from an LM35 temperature sensor connected to an Arduino to a web server:

#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid     = "your_SSID";
const char* password = "your_PASSWORD";
const char* serverName = "your_SERVER_IP_ADDRESS";
const int temperaturePin = A0;

void setup() {
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
  pinMode(temperaturePin, INPUT);
}

void loop() {
  int reading = analogRead(temperaturePin);
  float voltage = reading * 5.0 / 1024;
  float temperature = (voltage - 0.5) * 100;

  HTTPClient http;
  http.begin("http://" + String(serverName) + "/data");
  http.addHeader("Content-Type", "application/json");
  int httpResponseCode = http.POST("{\"temperature\":\"" + String(temperature) + "\"}");
  String response = http.getString();
  Serial.println(httpResponseCode);
  Serial.println(response);
  http.end();
  delay(10000);
}

This code connects to a Wi-Fi network using the WiFi.begin method and waits until the connection is established. The pinMode method is used to set the pin connected to the LM35 to INPUT mode. In the loop function, the code reads the analog value from the LM35, converts it to a temperature value, and then sends a POST request to the server containing the temperature data in JSON format. The server's response is printed to the serial monitor for debugging purposes.


Here is an example of how you could log temperature data from an LM35 temperature sensor connected to an Arduino to the Blynk cloud platform:



#include <WiFi.h>
#include <BlynkSimpleEsp32.h>

char auth[] = "your_BLYNK_AUTH_TOKEN";
char ssid[] = "your_SSID";
char pass[] = "your_PASSWORD";

const int temperaturePin = A0;

void setup() {
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
  Blynk.begin(auth, ssid, pass);
  pinMode(temperaturePin, INPUT);
}

void loop() {
  int reading = analogRead(temperaturePin);
  float voltage = reading * 5.0 / 1024;
  float temperature = (voltage - 0.5) * 100;

  Blynk.virtualWrite(V0, temperature);
  delay(1000);
}


This code connects to a Wi-Fi network using the WiFi.begin method and waits until the connection is established. The Blynk.begin method is used to initialize the Blynk library with the auth token and the Wi-Fi credentials. The pinMode method is used to set the pin connected to the LM35 to INPUT mode. In the loop function, the code reads the analog value from the LM35, converts it to a temperature value, and then sends the temperature data to Blynk's virtual pin 0 using the Blynk.virtualWrite method. The data can be displayed in a Blynk app using various widgets such as a gauge or a chart.






January 19, 2023

Arduino circuit for digital clock and Coding

An Arduino circuit for a digital clock can be created using an Arduino board, a 16x2 LCD display, a real-time clock module, and a few passive components such as resistors and a capacitor. The real-time clock module, such as the DS1307, provides the timekeeping functionality, while the LCD display is used to display the current time. The Arduino board is used to control the LCD and interface with the real-time clock module. A simple circuit diagram could be:


Arduino ------------------------- LCD
|
|
R1,R2
|
|
DS1307






Arduino oding for clock display
Here is an example of Arduino code for displaying the current time on an LCD using a real-time clock module:

Copy code
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <RTClib.h>

RTC_DS1307 rtc;
LiquidCrystal_I2C lcd(0x27, 16, 2);

void setup() {
  lcd.begin();
  lcd.backlight();
  rtc.begin();
  if (!rtc.isrunning()) {
    lcd.print("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }
}

void loop() {
  DateTime now = rtc.now();
  lcd.setCursor(0, 0);
  lcd.print(now.hour(), DEC);
  lcd.print(':');
  lcd.print(now.minute(), DEC);
  lcd.print(':');
  lcd.print(now.second(), DEC);
  lcd.setCursor(0, 1);
  lcd.print(now.day(), DEC);
  lcd.print('/');
  lcd.print(now.month(), DEC);
  lcd.print('/');
  lcd.print(now.year(), DEC);
  delay(1000);
}
 

This code uses the Wire and RTClib libraries to interface with the real-time clock module. The LiquidCrystal_I2C library is used to control the LCD display. The code first checks if the real-time clock is running, and sets the time if it is not. Then, in the loop, it continuously updates the LCD display with the current time and date retrieved from the real-time clock.

Note: in the code above, you can see that the I2C address of the LCD is 0x27, if it's different for you, you need to change that to the correct one.






KALMAN FILTER IN ARDUINO without Header file kalman.h

This is a basic Kalman filter that uses a constant measurement noise and process noise. You can adjust these values to fine-tune the filter for your specific application. The filter takes a measurement (z_measured) and uses it to estimate the real value (z_real). The estimated value is then updated with each new measurement.

#define MEASUREMENT_NOISE 0.1
#define PROCESS_NOISE 0.05

double x_est_last = 0;
double P_last = 0;
double K;
double P;
double x_temp_est;
double x_est;
double z_measured = 0; // the measured value
double z_real = 0; // the real value

void KalmanFilter()
{
    x_temp_est = x_est_last;
    P = P_last + PROCESS_NOISE;
    K = P / (P + MEASUREMENT_NOISE);
    x_est = x_temp_est + K * (z_measured - x_temp_est);
    P = (1 - K) * P;
    x_est_last = x_est;
    P_last = P;
}

 


 

January 17, 2023

Arduino Code for Kalman Filter


The Kalman filter is a mathematical algorithm that uses a series of measurements observed over time, containing noise (random variations) and other inaccuracies, and produces estimates of unknown variables that tend to be more accurate than those based on a single measurement alone. It is used in a wide range of applications, including signal processing, control systems, and navigation.

The filter is named after its inventor, Rudolf Kalman, who first described it in a paper published in 1960. It is based on a series of mathematical equations that describe how the variables of interest (such as the position and velocity of an object) evolve over time, and how these variables are related to the measurements that are being made. The filter uses these equations to estimate the values of the variables based on the measurements, and then updates these estimates as new measurements become available.

The Kalman filter is particularly useful in systems where the variables of interest are subject to random variations (noise) and other inaccuracies, and where the measurements are also subject to similar errors. The filter is able to take into account the uncertainty in the measurements and the system dynamics, and produce estimates that are optimal in some sense (e.g., minimum variance).

Case Study

The LM35 is a precision temperature sensor that can be used to measure temperature in degrees Celsius. It can be used in conjunction with a Kalman filter to filter out noise and provide a more accurate temperature reading. Here is an example circuit for using an LM35 with a Kalman filter on an Arduino:

#include <Kalman.h>

Kalman kalman;
int lm35Pin = A0; // The pin the LM35 is connected to
double temperature;
double filteredTemperature;

void setup() {
  Serial.begin(9600);
  kalman.setMeasurementNoise(0.1); // Set the measurement noise variance
  kalman.setProcessNoise(0.01); // Set the process noise variance
}

void loop() {
  temperature = analogRead(lm35Pin) * 0.48828125; // Read the LM35 and convert to degrees Celsius
  filteredTemperature = kalman.updateEstimate(temperature); // Update the filtered temperature estimate
 

  Serial.print("Temperature: ");
  Serial.print(temperature);
  Serial.print("\tFiltered Temperature: ");
  Serial.println(filteredTemperature);
 
  delay(100);
}

In this example, the LM35 is connected to pin A0 on the Arduino, and the analogRead() function is used to read the voltage output of the LM35. The voltage is then converted to temperature in degrees Celsius using the LM35's voltage-to-temperature conversion factor.

The Kalman filter is used to filter out noise in the temperature measurement by updating the estimate of the temperature with the new measurement and the previous estimate.

You should adjust the measurement noise and process noise variance to match your system's characteristics and specific requirements.

It's important to note that the example code is for illustrative purposes only and may need to be modified to work with your specific hardware and application.


Here another Example Code

===========================================================

#include <Kalman.h>

Kalman kalmanX; // Create Kalman filter objects
Kalman kalmanY;

double x = 0; // Set initial values
double y = 0;
double dx, dy;

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

  // Set the measurement noise variance for each filter
  kalmanX.setMeasurementNoise(1);
  kalmanY.setMeasurementNoise(1);

  // Set the process noise variance for each filter
  kalmanX.setProcessNoise(0.01);
  kalmanY.setProcessNoise(0.01);
}

void loop() {
  x = kalmanX.updateEstimate(x + dx); // Update the estimate for x
  y = kalmanY.updateEstimate(y + dy); // Update the estimate for y

  Serial.print("X: ");
  Serial.print(x);
  Serial.print("\tY: ");
  Serial.println(y);

  delay(100);
}




March 19, 2022

How to Drive MOSFET with ARDUINO

This is example how to drive Mosfet using arduino, port to drive is port 9 as PWM can send data from 0 to 255 as analog voltage from 0 to 5V.
Video example at : https://youtu.be/-zfrnw4Iwpg


/*

Fading
This example shows how to fade an LED using the analogWrite() function.
The circuit:
(modified)
- GATE MOSFET attached from digital pin 9 to  through 100 ohm resistor.
 
created 1 Nov 2008
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
https://www.arduino.cc/en/Tutorial/BuiltInExamples/Fading
*/

int ledPin = 9; // LED connected to digital pin 9
void setup() {
// nothing happens in setup
}

void loop() {
// fade in from min to max in increments of 5 points:
for (int fadeValue = 0 ; fadeValue <= 255; fadeValue += 5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}

// fade out from max to min in increments of 5 points:
for (int fadeValue = 255 ; fadeValue >= 0; fadeValue -= 5) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
}

November 16, 2021

Fix Error Driver for USB 2.0-serial drivers - Arduino

 This Problem is:

QA:

Hi to all at arduino

just wondering if any one can help.
i have an uno r3 and a nano pro.
the uno works great no probs, connects, uploads. really happy with it.

but when i plug the nano in to xp sp2 pc via usb, it finds new hardware but wont install the drivers. i cant find these usb 2.0-serial drivers anywhere. iv tried re-installing the ftdi drivers from arduino site but the comm port still does not show up in the ide and i still have usb 2.0-serial flagged up in device manager.

again, if any ones got the answer please help.

many thanks

 

Answer:

Just download this driver CH341SER  on file ZIP on this then UNZIP then do like this

1.  Open device manager

2.  Righth clik Other devices -> USB2.0 Ser   --> update driver

3. Click update driver---> find folder (driver CH341SER)

4. Find driver foler for USB2.0

5. Finis, succes to install, OK


Now your PC ready connect to USB arduino






 




 

December 8, 2017

Audio Player dengan Arduino

Hardware Required

  • Arduino Due Board
  • 8-ohm speaker or headphones
  • Arduino shield with an SD card with cs CS 4 (like the Ethernet shield)
Komponen tambahan untuk bagian audio amplifier:
  • LM386 (low power audio amplifier)
  • 10 kohm potentiometer
  • 10 ohm resistor
  • 2 x 10 µF capacitor
  • 0.05 µF (or 0.1 µF) capacitor
  • 250 µF capacitor 
Skema

















File Audio File

File audio disimpam di SD card format file .wav  misal diberi nama (test .wav) frek sampling 44100 Hz, 16-bit stereo quality.

Code Program:
/*
  Simple Audio Player

 Demonstrates the use of the Audio library for the Arduino Due

 Hardware required :
 * Arduino shield with a SD card on CS4
 * A sound file named "test.wav" in the root directory of the SD card
 * An audio amplifier to connect to the DAC0 and ground
 * A speaker to connect to the audio amplifier

 Original by Massimo Banzi September 20, 2012
 Modified by Scott Fitzgerald October 19, 2012
 Modified by Arturo Guadalupi December 18, 2015

 This example code is in the public domain

 http://www.arduino.cc/en/Tutorial/SimpleAudioPlayer

*/


#include <SD.h>
#include <SPI.h>
#include <Audio.h>

void setup() {
  // debug output at 9600 baud
  Serial.begin(9600);

  // setup SD-card
  Serial.print("Initializing SD card...");
  if (!SD.begin(4)) {
    Serial.println(" failed!");
    while(true);
  }
  Serial.println(" done.");
  // hi-speed SPI transfers

  // 44100kHz stereo => 88200 sample rate
  // 100 mSec of prebuffering.
  Audio.begin(88200, 100);
}

void loop() {
  int count = 0;

  // open wave file from sdcard
  File myFile = SD.open("test.wav");
  if (!myFile) {
    // if the file didn't open, print an error and stop
    Serial.println("error opening test.wav");
    while (true);
  }

  const int S = 1024; // Number of samples to read in block
  short buffer[S];

  Serial.print("Playing");
  // until the file is not finished
  while (myFile.available()) {
    // read from the file into buffer
    myFile.read(buffer, sizeof(buffer));

    // Prepare samples
    int volume = 1024;
    Audio.prepare(buffer, S, volume);
    // Feed samples to audio
    Audio.write(buffer, S);

    // Every 100 block print a '.'
    count++;
    if (count == 100) {
      Serial.print(".");
      count = 0;
    }
  }
  myFile.close();

  Serial.println("End of file. Thank you for listening!");
  while (true) ;
}

Menggerakkan Servo Motor dengan Setting Potensiometer

Hardware Required

  • Arduino or Genuino Board
  • Servo Motor
  • 10k ohm potentiometer
  • hook-up wires 
Skema

CODE:
/*
 Controlling a servo position using a potentiometer (variable resistor)
 by Michal Rinott <http://people.interaction-ivrea.it/m.rinott>

 modified on 8 Nov 2013
 by Scott Fitzgerald
 http://www.arduino.cc/en/Tutorial/Knob
*/


#include <Servo.h>

Servo myservo;  // create servo object to control a servo

int potpin = 0;  // analog pin used to connect the potentiometer
int val;    // variable to read the value from the analog pin

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  val = analogRead(potpin);            // reads the value of the potentiometer (value between 0 and 1023)
  val = map(val, 0, 1023, 0, 180);     // scale it to use it with the servo (value between 0 and 180)
  myservo.write(val);                  // sets the servo position according to the scaled value
  delay(15);                           // waits for the servo to get there
}


Ping Ultrasonic Range Finder

Hardware Required

  • Arduino or Genuino Board
  • Ultrasonic Range Finder
  • hook-up wires 
  • The SEN136B5B is an ultrasonic range finder from Seeedstudio. It detects the distance of the closest object in front of the sensor (from 3 cm up to 400 cm).

Circuit

 

CODE

/*
  Ping))) Sensor

  This sketch reads a PING))) ultrasonic rangefinder and returns the distance
  to the closest object in range. To do this, it sends a pulse to the sensor to
  initiate a reading, then listens for a pulse to return. The length of the
  returning pulse is proportional to the distance of the object from the sensor.

  The circuit:
 - +V connection of the PING))) attached to +5V
 - GND connection of the PING))) attached to ground
 - SIG connection of the PING))) attached to digital pin 7

  created 3 Nov 2008
  by David A. Mellis
  modified 30 Aug 2011
  by Tom Igoe

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/Ping
*/

// this constant won't change. It's the pin number of the sensor's output:
const int pingPin = 7;

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop() {
  // establish variables for duration of the ping, and the distance result
  // in inches and centimeters:
  long duration, inches, cm;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH pulse
  // whose duration is the time (in microseconds) from the sending of the ping
  // to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);

  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();

  delay(100);
}

long microsecondsToInches(long microseconds) {
  // According to Parallax's datasheet for the PING))), there are 73.746
  // microseconds per inch (i.e. sound travels at 1130 feet per second).
  // This gives the distance travelled by the ping, outbound and return,
  // so we divide by 2 to get the distance of the obstacle.
  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the object we
  // take half of the distance travelled.
  return microseconds / 29 / 2;
}
 

April 22, 2014

PARKING ALARM CAR


/* THIS IS PARKING ALARM SYSTEM MODIFICATION FROM PING SENSOR from ARDUINO.CC    THIS PROGRAM USING PING SENSOR+LCD+TONE
   MODIFICATION BY: ARDUINOEASYPROJECT.BLOGSPOT.COM
    
   The circuit PING SENSOR:
    * +V connection of the PING attached to +5V
    * GND connection of the PING attached to ground
    * SIG connection of the PING attached to digital pin 7

   The circuit Piezo:
    * attached to pin 9
    * attached to ground
 */


const int pingPin = 7;
float sinVal;
int toneVal;
int PiezoPin = 9;  //Output to piezo pin 9

void setup()
{
  Serial.begin(9600);
  pinMode(PiezoPin, OUTPUT);  
}

void loop()
{
  long duration, inches, cm;
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);
 
  Serial.print(inches);                  // THIS SERIAL JUST FOR DEVELOPER TO TEST
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
 
  if (cm <= 25)   // YOU CAN CHANGE THE DISTANCE WARNING AT THIS
    {
    for (int x=0; x<270; x=x+10)
      {
      sinVal = (sin(x*(3.1412/180)));
      toneVal = 2000+(int(sinVal*1000));
      Serial.println(sinVal);
      tone(PiezoPin, toneVal);
      delay(5);
      }
    }
  else
  { noTone(PiezoPin); }
  delay(100);
}

long microsecondsToInches(long microseconds)
{
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{
   return microseconds / 29 / 2;
}



This arduino parking alarm system will generate alarm sound when the car move to close the object around 25 cm. It is easy to change save distance, just set the cm variable in the program that you want.