How to code for DHT11, pH Sensor with i2c 16x2 LCD in Arduino Uno? - arduino-uno

I'm working on my college project on which I have to measure the temperature show it on 16x2 LCD and also to switch the cooling device according to the temperature, also I have to use pH Sensor and have to display its value on 16x2. Currently I'm using the code below for Temperature and switching, but it is not working properly. It shows the temperature on the screen but also some garbage value, and also not switching properly.
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
#include <dht.h>
dht DHT;
#define DHT11_PIN 7
LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7);
const int ledPin = 6;
void setup()
{
lcd.setBacklightPin(3,POSITIVE);
lcd.setBacklight(HIGH);
lcd.begin(16, 2);
lcd.clear();
Serial.begin(9600);
for (int DigitalPin = 8; DigitalPin <= 8; DigitalPin++) {
pinMode(DigitalPin, OUTPUT);
}
}
void loop()
{
int chk = DHT.read11(DHT11_PIN);
float temp=(DHT.temperature);
float Hum=(DHT.humidity);
lcd.print("Temp C ");
lcd.setCursor(6,0);
lcd.print(temp);
lcd.setCursor(0,1);
lcd.println("Humid % ");
lcd.setCursor(6,1);
lcd.print(Hum);
delay(1000);
if (temp <= 29)
digitalWrite(8, LOW);
else if (temp>30)
digitalWrite(8, HIGH);
}

I will divide my answer into two parts:
Hardware:
Please describe your hardware configuration in order to narrow down your problem: How are you switching the relay? Is it optically coupled? Are you using a transistor? If so, what type? Does your relay have reverse diode protection? (Do not connect your relay directly to an Arduino pin)
Code
2.1. This for-loop in your setup() is incorrect:
for (int DigitalPin = 8; DigitalPin <= 8; DigitalPin++) {
pinMode(DigitalPin, OUTPUT);
}
You are indexing from 8 to 8, hence you don't need a for loop to declare a single pin as an output.
2.2. In general, you can assign your output pins to variables, or as a macro like you did for the DHT. Just be consistent. Additionally, your code needs general tidying up:
a . Start your code with all libraries calling
#include <Wire.h> // The Wire.h library is already called by the LiquidCrystal_I2C library, so you don't need to call it if you use the I2C one
#include <LCD.h> // You are using the LCD library...
#include <LiquidCrystal_I2C.h> // but also the I2C lcd library. You don't need both.
#include <dht.h> // Is this the latest version? Use Adafruit's
b. Try to group all your macros at the beginning. Declare pins or constants here:
// Using macros
#define DHT11_PIN 7
#define DigitalPin 8
#define DHT11_PIN 7
or using constants for pins. Choose one, not both:
// Group all your const int together, for the sake of clarity
const int DHT_PIN = 7;
const int DigitalPin = 8;
const int ledPin = 6;
c. I believe this constructor is not correct for the library you chose. Check the example from this library (assuming it is the same, which I believe it is)
LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7);
try with this constructor, instead:
// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);
d. The setup() function needs some changes too:
void setup()
{
// You don't seem to be using the serial library. However, if you use it, it is
// preferable to start it first.
Serial.begin(9600);
// LCD configuration
lcd.begin(16, 2); // Always call the begin() method first
lcd.setBacklightPin(3,POSITIVE); // Then, use additional configuration methods.
lcd.setBacklight(HIGH);
lcd.clear();
// Once again, please check if you are using the right library.
// It might be the cause of the garbage you see.
// Initialize the type of pin
pinMode(DigitalPin, OUTPUT);
}
e. According to Adafruit's library (please see the examples), you are missing a Macro to declare the type of DHT sensor you are using:
#define DHTTYPE DHT11
f. In your main loop() you are reading values with some strange parenthesis:
int chk = DHT.read11(DHT11_PIN);
float temp=(DHT.temperature);
float Hum=(DHT.humidity);
which, according to the latest library, should be:
// The latest library does not have this prototype: int chk = DHT.read11(DHT11_PIN); What is it for in your dht lib?
float temp = DHT.readTemperature(); // instead of: float temp=(DHT.temperature); --> which should be DHT.temperature(); in any case
float hum = DHT.readHumidity(); // instead of: float Hum=(DHT.humidity);
TL;DR: Share your hardware in order to assist you. Update your libraries, clean-up your code, and use the right methods from the latest libraries.

Thankyou so much for your guidance, below is the working code for me:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DHT.h>
#define DHTPIN 7 //digital pin for sensor
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
void setup()
{
pinMode(8, OUTPUT); //for configuring relay output
lcd.begin(16, 2);
dht.begin();
}
void loop() {
delay(1000);
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).
if (isnan(h) || isnan(t) || isnan(f))
{
lcd.print("NO CONNECTION");
return;
}
//Hum code
lcd.setCursor(0, 0);
lcd.print("Hum:");
lcd.print(h);
lcd.print(" % ");
//Temp code
lcd.setCursor(0, 1);
lcd.print("Temp:");
lcd.print(t);
lcd.print(" C");
//To operate relay
{
if (t <= 26)
digitalWrite(8, LOW);
else if (t>27)
digitalWrite(8, HIGH);
}
}

Related

Printing the output data of a turbidity sensor with Arduino UNO

I am reading the output in voltage of a turbidity sensor : https://www.dfrobot.com/product-1394.html?tracking=5b603d54411d5 with an Arduino UNO. I want to print the value of volts outage and its NTU (turbidity units) on an LCD screen ADM1602U Sparkfun.
I cant seem to print the dtata correctly on the lCD, it opens and lights up (so I think the wiring is ok) but no data appear.
Here is the code I am using:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);
int sensorPin = A0;
int val = 0;
float volt;
float ntu;
void setup()
{
Serial.begin(9600);
lcd.init();
// Turn on the blacklight and print a message.
lcd.backlight();
}
void loop()
{
volt = ((float)analogRead(sensorPin)/1023)*5;
ntu = -1120.4*square(volt)+5742.3*volt-4353.8;
val = analogRead(volt);
Serial.println(volt);
lcd.clear();
lcd.setCursor(0,0);
lcd.print(volt);
lcd.print(" V");
lcd.setCursor(0,1);
lcd.print(ntu);
lcd.print(" NTU");
delay(10);
}
float round_to_dp( float in_value, int decimal_place )
{
float multiplier = powf( 10.0f, decimal_place );
in_value = roundf( in_value * multiplier ) / multiplier;
return in_value;
}
I used an analogread just to see if I was getting correct voltage values for the sensor and I am.
Thanks
Ok so I found the answer, the libary used was not appropriate to print on a 16x2 LCD display. The following code worked FYI:
#include <Wire.h>
#include <SoftwareSerial.h>
// Set the LCD address to 0x27 for a 16 chars and 2 line display
SoftwareSerial LCD(10, 11); // Arduino SS_RX = pin 10 (unused), Arduino SS_TX = pin 11
int sensorPin = A0;
float volt;
float ntu;
void setup()
{
Serial.begin(9600);
LCD.begin(9600); // set up serial port for 9600 baud
delay(500); // wait for display to boot
}
void loop()
{
volt = ((float)analogRead(sensorPin)/1023)*5;
ntu = -1120.4*square(volt)+5742.3*volt-4352.9;
Serial.println(volt);
// move cursor to beginning of first line
LCD.write(254);
LCD.write(128);
// clear display by sending spaces
LCD.write(" ");
LCD.write(" ");
// move cursor to beginning of first line
LCD.write(254);
LCD.write(128);
LCD.print(volt);
LCD.write(" V");
LCD.write(254);
LCD.write(192);
LCD.print(ntu);
LCD.write(" NTU");
delay(1000);
}

how to use ultrasonic sensor hc sr04 and gps neogps 6m and gsm sim900 on arduino uno

I’m trying to send an sms with the location when the ultrasonic sensor measures a certain distance but when I add the gpsSerial(9600) line in the void setup, the ultrasonic sensor readings become inconsistent such as it reads 24 cm then skips to 18 cm then back to 24 cm. i would really appreciate it if anyone familiar with arduino or has faced this problem before would help me out. here is my code:
#include <TinyGPS.h>
#include <SoftwareSerial.h>
#include "NewPing.h"
#define TRIGGER_PIN 7
#define ECHO_PIN 8
#define MAX_DISTANCE 100
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
float duration, distance;
SoftwareSerial gsmSerial(2, 3);
SoftwareSerial gpsSerial(5, 4);
TinyGPS gps; //Creates a new instance of the TinyGPS object
bool newData = false;
void setup()
{
Serial.begin(9600);
gsmSerial.begin(9600);
gpsSerial.begin(9600);
}
void loop()
{
// Send ping, get distance in cm
distance = sonar.ping_cm();
if (distance < 4 )
{
//sendSMS();
Serial.println("Bin is full!!, SMS SENT!!");
Serial.println(distance);
delay(1200);
}
else
{
Serial.println(distance);
delay(2000);
}
delay(2000);
}
void sendSMS(){
// For one second we parse GPS data and report some key values
for (unsigned long start = millis(); millis() - start < 1000;)
{
while (gpsSerial.available())
{
char c = gpsSerial.read();
//Serial.print(c);
if (gps.encode(c))
newData = true;
}
}
if (newData) //If newData is true
{
float flat, flon;
unsigned long age;
gps.f_get_position(&flat, &flon, &age);
gsmSerial.print("AT+CMGF=1\r");
delay(400);
gsmSerial.println("AT + CMGS = \"+26xxxxxxxx\"");// recipient's mobile
number
delay(300);
gsmSerial.print("BIN IS FULL!, PLEASE COLLECT # https://www.google.com
/maps/?q=");
gsmSerial.print(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flat, 6);
gsmSerial.print(",");
gsmSerial.print(flon == TinyGPS::GPS_INVALID_F_ANGLE ? 0.0 : flon, 6);
delay(200);
gsmSerial.println((char)26); // End AT command with a ^Z, ASCII code
26
delay(2000);
gsmSerial.println();
}
}
I've tried to reproduce your problem on Arduino Uno with HC SR04, but with no success – my measurements were stable (more than 100 same measurements in a row). I have even set the sensor to 24 cm distance from the measured obstacle. I used a code derived from what you have provided:
#include <SoftwareSerial.h>
#include "NewPing.h"
#define TRIGGER_PIN 7
#define ECHO_PIN 8
#define MAX_DISTANCE 100
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
float duration, distance;
SoftwareSerial gsmSerial(2, 3);
SoftwareSerial gpsSerial(5, 4);
void setup() {
Serial.begin(9600);
gsmSerial.begin(9600);
gpsSerial.begin(9600);
}
void loop() {
// Send ping, get distance in cm
distance = sonar.ping_cm();
if (distance < 4 ) {
Serial.println("Bin is full!!, SMS SENT!!");
Serial.println(distance);
}
else {
Serial.println(distance);
}
delay(2000);
}
My conclusion is your code is fine and the problem is HW related. Check the wiring and if possible, try to use another HC-SR04 sensor.
BTW1: During testing, I was sending data to gpsSerial (rx) just to be sure, it is not caused by the GPS module sending some periodic data.
BTW2: How do you power the GPS and GSM module? Are you using Arduino to power these? If yes, this also can be the source of your problems since these modules could drain large peak currents and Arduino as source is not powerful enough ...

how use the MPU 6050 in ultra low power mode

I'm currently trying to set up a fermentation specific gravity monitor, using a tilt sensor. The process can take several weeks, and must be contained in a sterile container, so must be battery powerered. I'm using a slightly modified ESP8266-01, which enters sleep mode then wakes once an hour to take a measurement, transmit the data, and return to sleep mode. I'm using an MPU6050 for the tilt sensor. Firstly, I can't seem to put the mpu into sleep mode when the esp is off, it always seems to take around 4mA, and secondly, I only need one axis, is it possible to disable everything else to limit power consumption further? I can't seem to find anything in the manual to disable axis, only to calibrate them. my code is below
experimenting with the registers below seem to make no difference, adding them, taking them out altogether, still takes around 4mA. Tried setting to 1 to put the mpu to sleep at the end of the cycle but makes no difference.
Wire.write(0x6B);
Wire.write(0);
I'm very new to this and im struggling to interpret the manual when it refers to bit6 in addr 6b, how do i set bit 6?
If i could restict the mpu to only 1 axis, no acceleration, and to deep sleep inbetween measurements I should be able to get the power consumption around 0.5mA which gives me agood battery life using a single 18650. Any advice would be greatly appreciated!
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include "MPU6050.h"
#include "I2Cdev.h"
#include "Wire.h"
// Update these with values suitable for your network.
const char* ssid = "****";
const char* password = "******";
IPAddress server(192, 168, 1, 90);
WiFiClient espClient5;
PubSubClient client(espClient5);
long lastMsg = 0;
char msg[50];
const uint8_t scl = 5; //D1
const uint8_t sda = 4; //D2
int val;
int prevVal = 0;
String pubString;
char gravity[50];
MPU6050 mpu;
const int sleepTimeS = 10; //only 10 seconds for testing purposes, set to
1hr when operational
int counter=0;
int16_t ax, ay, az;
int16_t gx, gy, gz;
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) { //not
required in this application
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "test";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("AliveRegister", "FermentMon");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
#define ONE_WIRE_BUS 2 // D4 on physical board
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature DS18B20(&oneWire);
float prevTemp = 0;
void setup() {
counter = 0;
Serial.begin(9600);
Wire.begin(0,2);
Wire.write(0x6B); //PWR_MGMT_1 register
Wire.write(0); // set to zero wakes teh 6050
Wire.endTransmission(true);
delay(100);
setup_wifi();
client.setServer(server, 1883);
client.setCallback(callback);
if (!client.connected()) {
reconnect();
}
Serial.println("Initialize MPU");
mpu.initialize();
Serial.println(mpu.testConnection() ? "Connected" : "Connection failed");
float temp;
DS18B20.requestTemperatures();
temp = DS18B20.getTempCByIndex(0); // first temperature sensor
char buff[100];
dtostrf(temp, 0, 2, buff);
temp = temp + 0.5;
int tRound = int(temp);
client.publish("Fermenter/temperature", buff);
Serial.print("Fermenter Temperature: ");
Serial.println(temp);
prevTemp = tRound;
mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
val = map(ax, -17000, 17000, 0, 180);
pubString = String(val);
pubString.toCharArray(gravity, pubString.length() + 1);
client.publish("Fermenter/angle", gravity);
Serial.print("Gravity angle: ");
Serial.println(val);
delay(500);
// counter = counter+1;
Serial.println("sleep mode");
Wire.write(0x6B); //PWR_MGMT_1 register
Wire.write(1); // set to zero wakes teh 6050
// sleep
ESP.deepSleep(sleepTimeS * 1000000);
delay(2000);
}
void loop() {
client.loop();
}
I'm very new to this and im struggling to interpret the manual when it refers to bit6 in addr 6b, how do i set bit 6?
Setting a bit is simple.
Use the follow functions to avoid any brain storming.
// Write register bit
void writeRegisterBit(uint8_t reg, uint8_t pos, bool state)
{
uint8_t value;
value = readRegister8(reg);
if (state)
{
value |= (1 << pos);
}
else
{
value &= ~(1 << pos);
}
writeRegister8(reg, value);
}
// Write 8-bit to register
void writeRegister8(uint8_t reg, uint8_t value)
{
Wire.beginTransmission(MPU_addr);
#if ARDUINO >= 100
Wire.write(reg);
Wire.write(value);
#else
Wire.send(reg);
Wire.send(value);
#endif
Wire.endTransmission();
}
Example Usage: writeRegisterBit(MPU6050_REG_INT_PIN_CFG, 5, 1); //Register 37;Interrupt Latch Enable
For your application:
void acclSetSleepEnabled(bool state)
{
writeRegisterBit(MPU6050_REG_PWR_MGMT_1, 6, state);
}
If i could restict the mpu to only 1 axis, no acceleration, and to deep sleep inbetween measurements I should be able to get the power consumption around 0.5mA which gives me agood battery life using a single 18650
To enter low power accelerometer mode use the following function:
void lowPowerAccel(uint8_t frequency) {
uint8_t value;
value = readRegister8(MPU6050_REG_PWR_MGMT_2);
value &= 0b00111000;
value |= (frequency << 6) | 0b111;
writeRegister8(MPU6050_REG_PWR_MGMT_2, value);
value = readRegister8(MPU6050_REG_PWR_MGMT_1);
value &= 0b10010111;
value |= 0b00111000;
writeRegister8(MPU6050_REG_PWR_MGMT_1, value);
}
This lowPowerAccel function also puts the gyro to standy mode. The function needs a wake up frequency parameter.
This is defined as follows:
/*
* LP_WAKE_CTRL | Wake-up Frequency
* -------------+------------------
* 0 | 1.25 Hz
* 1 | 2.5 Hz
* 2 | 5 Hz
* 3 | 10 H
*/
#define LP_WAKE_CTRL_1_25 0x00
#define LP_WAKE_CTRL_2_5 0x01
#define LP_WAKE_CTRL_5 0x02
#define LP_WAKE_CTRL_10 0x03
I hope, I could answer some of your questions.
Good luck! :)
Are you using a breakout board for the MPU6050? e.g. GY-521. Often they use linear regulators and leds which will consume additional power. It may be necessary to remove these and run the IMU from a direct power source.
Each register in the MPU6050 is 8 bits wide. When setting an individual bit to a desired value you can either use bitwise manipulation (not practical here as we aren't directly interacting with the registers) or directly set all of the bits in the register to the register's new state e.g. 0b00100000 ~ 0x20. Instead of writing a 1 to 0x6B when attempting to put the MPU6050 to sleep you should be writing 0x20.
https://www.invensense.com/wp-content/uploads/2015/02/MPU-6000-Register-Map1.pdf
Referencing page 40-42, if you want to take things a step further you can disable the temperature sensor, accelerometers, and redundant gyroscope axes to save power while the device is active.

Atmel Studio- ATmega128 bootloader

I am trying to write a customized boot-loader for ATmega AVR's. I write a code, and it work perfectly in small AVR's like ATmega32A and ATmega8A. But when i want to use it in ATmega128A, it writes nothing in flash segment.
I'm sure Fuses are correct, ATmega103 mode is disabled, and the program starts at boot section, but it does nothing..
Before calling function "boot_program_page" I set PORTC and turn some LED's on, and after that I cleared PORTC and LED's goes off. so the code in executing completely too.
The function I am using is an example provided in avr/boot.h.
It should write some data ( 0x00 actually ) in page 0 of flash memory..
here is my code :
#define F_CPU 8000000UL
#include <inttypes.h>
#include <avr/io.h>
#include <avr/boot.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <util/delay.h>
void boot_program_page (uint32_t page, uint8_t *buf);
int main(void)
{
uint8_t data[SPM_PAGESIZE] = {0};
uint32_t page = 0;
DDRC = 255;
PORTC = 255;
page *= (uint32_t)SPM_PAGESIZE;
boot_program_page(page,data);
_delay_ms(1000);
PORTC = 0;
while (1)
{
}
}
void boot_program_page (uint32_t page, uint8_t *buf)
{
uint16_t i;
uint8_t sreg;
// Disable interrupts.
sreg = SREG;
cli();
eeprom_busy_wait ();
boot_page_erase (page);
boot_spm_busy_wait (); // Wait until the memory is erased.
for (i=0; i<SPM_PAGESIZE; i+=2)
{
// Set up little-endian word.
uint16_t w = *buf++;
w += (*buf++) << 8;
boot_page_fill (page + i, w);
}
boot_page_write (page); // Store buffer in flash page.
boot_spm_busy_wait(); // Wait until the memory is written.
// Reenable RWW-section again. We need this if we want to jump back
// to the application after bootloading.
boot_rww_enable ();
// Re-enable interrupts (if they were ever enabled).
SREG = sreg;
}

Smallest (code-wise) bit - banged serial interface on PIC10

I need to interface to a PIC10 micro with some serial interface. Since these small devices lack hardware support for SPI I2C and UART a Software solution is inevitable.
However, since I need to preserve as much of the Programm memory to store (static) configuration and identify information to be retrieved via said interface, what would probably be the smallest solution?
I will need to program this in ASM since there seems no good C compiler for PIC10. However, this will be my first real encounter with ASM to speak of.
Try this download which contains code samples and says:
"Listed below are five PIC UART software routines to use with PIC microprocessors that have no hardware UART"
Link rot has broken the original link try this link.
In my opinion the xc8 compiler works pretty well, also for the PIC10.
Here is an example in C:
#include <xc.h>
#ifndef _XTAL_FREQ
#define _XTAL_FREQ 4000000
#endif
#define Baudrate 1200 //bps
#define OneBitDelay (1000000/Baudrate)
#define DataBitCount 8 // no parity, no flow control
#define UART_RX RA1 // UART RX pin
#define UART_TX RA0 // UART TX pin
#define UART_RX_DIR TRISA1 // UART RX pin direction register
#define UART_TX_DIR TRISA0 // UART TX pin direction register
//Function Declarations
void InitSoftUART(void);
unsigned char UART_Receive(void);
void UART_Transmit(const char);
__CONFIG(FOSC_INTOSC & MCLRE_OFF & WDTE_OFF & LVP_OFF & CP_OFF &
WRT_OFF & PWRTE_OFF & WRT_OFF & BOREN_ON & LPBOR_ON & BORV_LO);
void main()
{
unsigned char ch = 0;
ANSELA = 0x00; // Set ports as digital I/O, not analog input
ADCON = 0x00; // Shut off the A/D Converter
FVRCON = 0x00; // Shut off the Voltage Reference
PORTA = 0x00; // Make all pins 0
InitSoftUART(); // Intialize Soft UART
InitSoftUART(); // Intialize Soft UART
while(1)
{
ch = UART_Receive(); // Receive a character from UART
UART_Transmit(ch); // Echo back that character
}
}
void InitSoftUART(void) // Initialize UART pins to proper values
{
UART_TX = 1; // TX pin is high in idle state
UART_RX_DIR = 1; // Input
UART_TX_DIR = 0; // Output
}
unsigned char UART_Receive(void)
{
// Pin Configurations
// GP1 is UART RX Pin
unsigned char DataValue = 0;
//wait for start bit
while(UART_RX==1);
__delay_us(OneBitDelay);
__delay_us(OneBitDelay/2); // Take sample value in the mid of bit duration
for ( unsigned char i = 0; i < DataBitCount; i++ )
{
if ( UART_RX == 1 ) //if received bit is high
{
DataValue += (1<<i);
}
__delay_us(OneBitDelay);
}
// Check for stop bit
if ( UART_RX == 1 ) //Stop bit should be high
{
__delay_us(OneBitDelay/2);
return DataValue;
}
else //some error occurred !
{
__delay_us(OneBitDelay/2);
return 0x000;
}
}
void UART_Transmit(const char DataValue)
{
/* Basic Logic
TX pin is usually high. A high to low bit is the starting bit and
a low to high bit is the ending bit. No parity bit. No flow control.
BitCount is the number of bits to transmit. Data is transmitted LSB first.
*/
// Send Start Bit
UART_TX = 0;
__delay_us(OneBitDelay);
for ( unsigned char i = 0; i < DataBitCount; i++ )
{
//Set Data pin according to the DataValue
if( ((DataValue>>i)&0x1) == 0x1 ) //if Bit is high
{
UART_TX = 1;
}
else //if Bit is low
{
UART_TX = 0;
}
__delay_us(OneBitDelay);
}
//Send Stop Bit
UART_TX = 1;
__delay_us(OneBitDelay);
}
Source for this code is the :Microchip forum

Resources