Showing posts with label arduino. Show all posts
Showing posts with label arduino. Show all posts

Friday, 2 March 2018

Reading PWM Signals using Pin Change Interrupts

To Measure a PWM wave using Arduino we can follow any one of following ways

1.  built-in pulseIn function
2. Timer and External Interrupts
3. Pin Change Interrupts

Below Code is used to measure PWM width when connected to pin 9

//   Pin Change Interrupts
//PCMSKx - Pin Change Mask Register
//PCMSK0 - portB (D8-D13) (PCINT0  - PCINT6)
//PCMSK1 - portC (A0-A5)  (PCINT8  - PCINT14)
//PCMSK2 - portD (D0-D7)  (PCINT16 - PCINT23)
//PCICR -  Pin Change Interrupt Control Register
//  PCIE0 - Pin Change Interrupt Enable 0 - Port B (D8-D13)
//  PCIE1 - Pin Change Interrupt Enable 1 - Port C (A0-A5)
//  PCIE2 - Pin Change Interrupt Enable 2 - Port D (D0-D7)

volatile boolean recvPCInt = false;
volatile byte portValue;
unsigned long pwmDuration;
unsigned long pwmStart;
unsigned long pwmEnd;


//Interrupt Service Routine will fire when for PinChange in PortB
ISR(PCINT0_vect){
  recvPCInt = true;
  portValue = PINB; //PINB is used to read all port input values
}

void setup() {
cli(); //Clear all interrupts
PCICR |= 1 << PCIE0; //Enable port B Registers i.e D8-D13
PCMSK0 |= 1 << PCINT1;// Pin9
sei(); //enable all interrupts
pinMode(9,INPUT);
digitalWrite(9,HIGH);//enable pull up in pin 9
Serial.begin(9600);
}

void loop() {
  if(recvPCInt == true){
     boolean event = digitalRead(9);
     if(event == HIGH)
        {
          pwmStart = micros();
        }
       else if(event == LOW){
          pwmEnd = micros();
        Serial.println(pwmEnd-pwmStart);
       }
     recvPCInt = false;
  }
} 
 
 

Wednesday, 20 May 2015

Adding Arduino Library to proteus 8

when i googled to add arduino library to proteus8 version there are many examples came But I still faced the problem while installing arduino library in proteus version 8.

the usual procedure to add library is
1.download the library
2. paste it in your LIBRARY folder

the problem is I don't find the library folder in program files
so i clicked on the L in the P L device menu

library

and by clicking create library we can know the path where the LIBRARY folder is

Arduino Proteus8 turorial

simulation of arduino controlling relay.. step 1: when you double click on the Proteus8 icon the window open like this

home

step 2: go to FILE and click on NEW PROJECT a new project wizard is open like this new_project_wizard select a name and path for it and click next step 3: create the default schematic schematic click on the create schematic from the selected template and choose DEFAULT and select option for no pcb layout and and no firmware as shown in figures below pcb layoutfirmware and click finish finish after clicking finish we get a empty schematic like this empty schematic I assume that you installed Arduino Proteus library -- if not google it you can find many tutorials of how to do it. at the left panel we have some control tools to add components to the schematic control In above picture the highlighted one having names P L DEVICES when we click on P we have option to pick components pick devices IF you type Arduino in search bar you get the window like this arduino_pick select arduino UNO and click ok to add it to the devices for this we are gonna need following components 1.ULN2003 IC - relay driver 2.relay 3.dc source 4.ac source 5.lamp ULN2003 IC-- we can get this using search bar uln2003 and relay,lamp and ac source using keywords relay,lamp and alternator respectively but for dc source it took me some time to figure out what to do... we can get dc source from generator mode generator by clicking the symbol generator_sign and selecting DC dc_select and after aligning all these in the schematic get to this. arduino_relay to dump the code follow this procedure Using Arduino IDE type the following code void setup() { pinMode(13,OUTPUT); } void loop() { digitalWrite(13,HIGH); delay(1000); digitalWrite(13,LOW); delay(1000); } before verifying the code goto File -- Preferences in Arduino file menu select compilation as shown in fig preferences and press the verify button code_file copy the highlighted section and paste it in paste the above window comes by double clicking the arduino uno.. and run the simulation we can see the lamp is ON and OFF sequentially.

Tuesday, 19 May 2015

Using relay with Arduino

references :

http://www.electronics-tutorials.ws/io/io_5.html

http://www.electroschematics.com/8512/microcontroller-relay-interface-and-driver/

https://electrosome.com/interfacing-relay-8051-keil-c/

Thursday, 14 May 2015

VFD & arduino

references :

https://deltautomation.wordpress.com/2011/04/29/plc-vfd-comunication/

http://fightpc.blogspot.in/2014/10/vfd-control-with-arduino-using-rs485.html

http://www.avrfreaks.net/forum/vfd-microcontroller

controlling VFD with arduino...

i made a simple code to control VFD (change the speed and direction of ac drive) with arduino.

/*
Author : Kunchala Anil [anilkunchalaece@gmail.com]

Interfacing VFD with Arduino Via RS485 using MODBUS Protocol
MODBUS protocol
-------------------------------------------------------------------------
| Start Bit | Address | Function_Command | DATA | LRC or CRC | Stop bit |
| : | 2bytes | 2 bytes | | 2 bytes | \r\n |
-------------------------------------------------------------------------

Function Code : The format of data characters depend on function codes
The available function codes are described as follows:
0x03 : Read data from register
0x06 : Write single data to register
0x10 : Write multiple data to registers

MODBUS Protocol can be implemented in two ways ASCII or RTU(Remote Terminal Unit)
iam gonna use ASCII mode for this example

____________________________________________________________________________
| Content Address Functions
|-------------------------------------------------------------------------
| B1 B0
| 0 0 --> NO function
| Bit 0 - 1 0 1 --> Stop
| 1 0 --> Run
| 0x2000 1 1 --> Jog + Run
|
| Bit 2 - 3 Reserved
|
| B5 B4
| 0 0 --> No function
| Command Bit 4 - 5 0 1 --> FWD
| Read / Write 1 0 --> REV
| 1 1 --> Change Direction
|
| Bit 6 - 15 Reserved
|
| 0x2001 Frequency Command
|
|__________________________________________________________________________________


Command Address B15 B14 B13 B12 B11 B10 B9 B8 B7 B6 B5 B4 B3 B2 B1 B0 Hex Equalent
RUN 0x2000 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0x0012
STOP 0x2000 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1 0x0011
Format if data send to the VFD
':' --> Start bit in Ascii mode
\r\n --> Stop bit


*/

//commands values
#define VFD_START 1
#define VFD_STOP 2
#define VFD_SPEED 3

#define MAX_SIZE 20 // max size of data buffer

char speed_vfd[] = ":01062001";
const char start_vfd[] = ":010620000012C7\r\n";
const char stop_vfd[] = ":010620000011C8\r\n";
char data_buffer[MAX_SIZE];

void setup(){
Serial.begin(9600);
}//end of setup


void loop(){

serial_ask(); /* ask question the user to enter
1 to start the VFD
2 to stop the VFD
3 to set the speed of VFD */
int val = serial_check(); /* wait for user to enter the data and convert
it to Int and return value into function */
perform_action(val); /* perform the action based on the user entered value
which is passed to the function */

}//end of loop


/*
SERIAL_ASK() FUNCTION : this function is used to ask the user to enter the user choice via Serial monitor
*/
void serial_ask(){
Serial.println("Please Enter all values followed by \n");
Serial.println("Please enter the valid code to perform");
Serial.println("-------------------");
Serial.println("CODE\t ACTION");
Serial.print(VFD_START);Serial.println("\t START VFD");
Serial.print(VFD_STOP);Serial.println("\t STOP VFD");
Serial.print(VFD_SPEED);Serial.println("\t SET SPEED");
Serial.println("-------------------");
}//end of serial_ask() fucntion


/*
SERIAL_CHECK() FUNCTION : this function is used to receive the data into data_buffer
*/
int serial_check(){
while(!data_received())
{
//wait until full data is received
}//end of while
return atoi(data_buffer);
}//end of serial_check() function


boolean data_received(){
static byte index = 0;
while(!Serial.available())
{
//wait until user enter the data
}

if(Serial.available())
{
char input = Serial.read();
if(input !='\r')
{
data_buffer[index] = input;
index = index + 1;
}else
{
data_buffer[index] = 0;//null terminate the character array to make it string
index = 0;
return true;// we received the full code return true
}//end of ifelse condition
}
return false;
}//end of data_received()) function

void perform_action(int val){
switch(val)
{
case VFD_START:
Serial.println("VFD START");
VFD_control(start_vfd);
break;

case VFD_STOP:
Serial.println("VFD STOP");
VFD_control(stop_vfd);
break;

case VFD_SPEED:
Serial.println("SET SPEED");
set_speed();
break;

default:
error_message();

}//end of switch
}//end of perform action

void VFD_control(const char* command){
Serial.print(command);
Serial.println();
}

void set_speed(){
char freq_hex[4];//temporary string for sprintf
Serial.println("Set Speed");
Serial.println("enter the frequency");
int freq = serial_check();
Serial.print("the frequency you entered is");
Serial.println(freq);
sprintf(freq_hex,"%04X",freq);//convert it to hex using sprintf
strcat(speed_vfd,freq_hex);
cal_LRC();

}//end of set_speed() fucntion

void cal_LRC(){
int val = calculate(); //function to calculate the decimal value
convert_to_hex(val);// function to convert the decimal value to HEX
}//end of cal_LRC() fucntion


//CALCULATE() FUNCTION
int calculate(){
int val[strlen(speed_vfd)/2]; // val[] array is used to store the decimal value for two HEX digits
for (int i = 1, j = 0 ; i < strlen(speed_vfd); i = i+2, j++ ) //i = i+2 because we are finding the decimal equalent for two HEX values
{
val[j] = conv(speed_vfd[i],speed_vfd[i+1]); // function to convert Two Hex numbers into Decimal Value

}//end of for loop

int sum = find_sum(val); // function to calculate total sum of decimal equalents
return sum;
}//end of calculate() function

//FUNCTION_SUM() FUNCTION
int find_sum(const int * val) // we are passing an array to the function
{
int sum = 0;
for(int i=0;i<= (strlen(speed_vfd)/2) - 1;i++)
{
sum = sum + val[i];
}//end of for loop
return sum;
}//end of find_sum() function

//FUNCTION TO CONVERT HEX TO THE DECIMAL VALUE
int conv(char val1,char val2){
int val_a = toDec(val1); // convert to the decimal value
int val_b = toDec(val2);
return (val_a*16) + val_b; // converting decimal value into HEX decimal Equalent B1*16 + B0
}//end of conv() function

int toDec(char val){
if(val<='9')
{
return val - '0'; // please see the ASCII table for clarification
}
else
{
return val - '0'-7; // 7 is offset for capital letters please see the ASCII table
}

}//end of toDec() function

void convert_to_hex(int val){
char hex[5];
utoa((unsigned)val,hex,16); // utoa() function is used to convert unsigned int to HEX array (whatever the base we specified as third argument)

int hex_val = (int)strtol(hex,NULL,16);// strtol() is used to covert string into long int according to the given base

hex_val = ((~hex_val) + B01) & 0xff; /* finding the 2's complement of the number hex_val
'~' operator is the logical not and adding B01 to it and logical anding with 0xff
to omit any excess bites otherthan 8 bits or 1 byte
*/
Serial.print("the LRC value is : ");
Serial.println(hex_val,HEX);
char hex_val_str[4];
sprintf(hex_val_str,"%0.2X",hex_val);// putting hex value in the string back
Serial.print("the concated string is : ");
strcat(speed_vfd,hex_val_str);
char ter[] = "\r\n";
strcat(speed_vfd,ter);//adding terminators at the end STOP bits
Serial.println(speed_vfd);
}//end of convert_to_hex() fucntion


void error_message(){
Serial.println("You Entered Wrong Command");

}//end of error_message()

it actually doesn't do anything.. we can modify the code to send the modbus control to the VFD.
I don't have the hardware to test it But i made the code using VFD-m Manual
delta VFD-m

Arduino & load cell

references :

http://flowrc.co.uk/load_cell_stage_3.html

http://dailylearningnotes.blogspot.in/2010/03/working-with-load-cell-2.html

http://christian.liljedahl.dk/guides/arduino-and-load-cell


http://www.mechtechplace.net/mech-tech-electronics/building-a-low-cost-strain-gage-load-cell-amplifier/

Friday, 8 May 2015

LRC calculation for MODBUS ASCII Protocol In Arduino

In MODBUS Ascii mode each 8 bit data is the combination of two ascii characters
for ex: a 1 byte data 64H is shown as '64' in ASCII, consist of '6'(36 Hex) and '4'(34 Hex) (i still need to figure out the difference between those and standard ASCII values)

to calculate LRC for frame ":010304010001"
we need to add 01H + 03H + 04H + 01H + 00H + 01H = 0aH,
the 2's complement negation of 0aH is f6H

code to perform this is

/*
Author : Kunchala Anil
Calculating the LRC of HEXA numbers used in MODBUS ASCII

In MODBUS ASCII protocol : is used as starting word
The special function used in this code is utoa() and strlen() and sprintf()

utoa() --> unsigned integer to String for base conversion

syntax : utoa((unsigned int)val , string , base)

where val : is the value to be converted into base N format
string : is the temporary string to store the converted value
base : base is the Radix which val is converted (in this code it is 16)

strtol() --> string to long int

syntax : strtol(str,end_ptr,radix)
str : string to be converted
end_ptr : end pointer (NULL)
base : radix of the system

sprintf() --> string print function

syntax : sprintf(str,format)
str : destination string where output is stored

*/
char a[] = ":010304010001"; // ASCII string lrc being added

void setup(){
Serial.begin(9600); // start the serial communication
Serial.print("The string to which LRC is calculated is : ");
Serial.println(a);
int val = calculate(); //function to calculate the decimal value
convert_to_hex(val);// function to convert the decimal value to HEX
}//end of setup()

void loop(){
//do nothing here
}//end of loop()

//CALCULATE() FUNCTION
int calculate(){
int val[strlen(a)/2]; // val[] array is used to store the decimal value for two HEX digits
for (int i = 1, j = 0 ; i < strlen(a); i = i+2, j++ ) //i = i+2 because we are finding the decimal equalent for two HEX values
{
val[j] = conv(a[i],a[i+1]); // function to convert Two Hex numbers into Decimal Value

}//end of for loop

int sum = find_sum(val); // function to calculate total sum of decimal equalents
return sum;
}//end of calculate() function

//FUNCTION_SUM() FUNCTION
int find_sum(const int * val) // we are passing an array to the function
{
int sum = 0;
for(int i=0;i<= (strlen(a)/2) - 1;i++)
{
sum = sum + val[i];
}//end of for loop
return sum;
}//end of find_sum() function

//FUNCTION TO CONVERT HEX TO THE DECIMAL VALUE
int conv(char val1,char val2){
int val_a = toDec(val1); // convert to the decimal value
int val_b = toDec(val2);
return (val_a*16) + val_b; // converting decimal value into HEX decimal Equalent B1*16 + B0
}//end of conv() function

int toDec(char val){
if(val<='9')
{
return val - '0'; // please see the ASCII table for clarification
}
else
{
return val - '0'-7; // 7 is offset for capital letters please see the ASCII table
}

}//end of toDec() function

void convert_to_hex(int val){
char hex[5];
utoa((unsigned)val,hex,16); // utoa() function is used to convert unsigned int to HEX array (whatever the base we specified as third argument)
int hex_val = (int)strtol(hex,NULL,16);// strtol() is used to covert string into long int according to the given base
hex_val = ((~hex_val) + B01) & 0xff; /* finding the 2's complement of the number hex_val
'~' operator is the logical not and adding B01 to it and logical anding with 0xff
to omit any excess bites otherthan 8 bits or 1 byte
*/
Serial.print("the LRC value is : ");
Serial.println(hex_val,HEX);
char hex_val_str[4];
sprintf(hex_val_str,"%0.2x",hex_val);// putting hex value in the string back
Serial.print("the concated string is : ");
strcat(a,hex_val_str);
char ter[] = "\r\n";
strcat(a,ter);//adding terminators at the end or STOP bits
Serial.println(a);
}//end of convert_to_hex() fucntion


output
LRC_output

Playing with Strings, HEX and Integer values.

In the past few days I have tough time converting Inter values into Hex values and how to store them in strings.
If once i stored them How to get their Hex representation Back..

first of all.. Int is a Data type where HEX is a Data representation
so if i wanted to convert Int To HEX and send the value through Serial Hardware
i can do something like this

int val = 100;
void setup(){
Serial.begin(9600);
Serial.print(val);
}
void loop(){
}


output:
3e8

ok HEX representation of 1000 is 3e8 and it is converted and send through serial hardware.
But what if we wanted to store that Equivalent Hex value into some variable or assign that value to another variable?

So we need a way to store that converted Hex value. but to which data type we need to store the HEX value?
like i said before HEX is not a datatype it is a data representation. even though it is holding a integer value we cannot assign it to the int datatype because of characters A to Z.

One possible solution is using strings.so we need to perform the conversion and store that value in string

hopefully there is a function call that will do the work for us it isutoa()
utoa --> unsigned int to String Base conversion
syntax : utoa((unsigned int) val,string,base)
where val is the val converted to Hex format
string is char string which holds output after conversion
base is radix for conversion 0,8,16

utoa()

Convert an unsigned integer into a string, using a given base

Synopsis:
#include

char* utoa( unsigned int value,
char* buffer,
int radix );
Arguments:
value
The value to convert into a string.
buffer
A buffer in which the function stores the string. The size of the buffer must be at least:
8 × sizeof( int ) + 1

bytes when converting values in base 2 (binary).

radix
The base to use when converting the number.



simple code to demonstarte this conversion is

int val = 1000;

void setup(){
char str[4];
utoa((unsigned int) val,str,16);
Serial.print("the val is : ");
Serial.println(val);
Serial.print("the HEX converted string is : ");
Serial.println(str);
}

void loop(){
}


output:
the val is : 1000
the HEX converted string is : 3e8

we commonly use 2 bytes or 4 bytes as HEX representation.. so if we wanted to represent 1000 in HEX 4 byte format we write something like 03e8. we add zero before MSB to make it 4 bytes But Arduino doesn't it do that automatically for us. so we somehow has to tell Arduino that we need to print fixed bytes representation because this will cause major problem if we wanted to send the hex value in the middle of string.

this is done using sprintf() function
sprinf() : string print function which is used to store the string in specified format

which dones same duty as printf but rather than printing to standard io it format the data and store it in string

syntax:sprintf(str,format,arguments)
where str is the string where formatted data is stored
format is used to specify the format
arguments is the arguments supplied to arguments

Here format is the key thing that do the job
that can be explained using the following c program

#include
int main() {
int data = 29;
printf("%x\n", data); // just print data
printf("%0x\n", data); // just print data ('0' on its own has no effect)
printf("%8x\n", data); // print in 8 width and pad with blank spaces
printf("%0.8x\n", data); // print in 8 width and pad with 0's
getch();

return 0;
}


and the result is
sprintf format

code to convert int to hex and store to the string with 4 bytes representation is

int a = 1000;
void setup(){
Serial.begin(9600);
char str[4];
sprintf(str,"%0.4x",a);
Serial.print("the HEX converted string is : ");
Serial.println("str");
}

void loop(){
}


those are used when we wanted to use functions like strcat() to concate strings

But what if we have a HEX string and wanted to get the int value back from the string. in this case atoi() won't help us because it only convert integer string not HEX string

in this code strtol() will be useful.
strtol --> string into long integer
convert a string into long integer according to the given Base.

syntax: strtol(str,end_ptr,base)
str : string which converted
end_ptr: end pointer
base : radix of values stored in string
it returns the long int value we need to cast to int if wanted to assign it to int variable
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes as many characters as possible that are valid following a syntax that depends on the base parameter, and interprets them as a numerical value. Finally, a pointer to the first character following the integer representation in str is stored in the object pointed by endptr.


char str[] = "03e8";
void setup(){
Serial.begin(9600);
int val = (int)strtol(str,NULL,16);
Serial.println(val);
}
void loop(){
}


Output:
1000

the functions do our bidding is:
utoa -- unsigned int to ascii string with base
utoa(int val, char* str, radix)

strtol -- string to long int
strtol(str,end_ptr,radix)

sprintf -- string printf
sprintf(string,format)

Wednesday, 6 May 2015

converting Decimal to HEX values in Arduino

while i am searching for a way to send the HEX values rather than Int / char values using Arduino Serial communication. i find that Serial.print() will do the work for me.

void setup(){
int a = 17;
Serial.begin(9600);
Serial.print("value of a :"); Serial.println(a);
Serial.print("HEX equalent of a :"); Serial.println(a,HEX);


}

void loop(){
//do nothing
}

and the output is like
hex equa

it is good enough to do the work for me But there is a chance of error if i wanted to send a value in the middle of array.

the problem arise when we wanted to print leading zeros for fixed two byte and 4 byte HEX values
if we wanted to print values 1 and 1000,we get hex equivalents as
leading zero problem

which is printed by omitting zero's. and doesn't specify the no of HEX digits in outputs

so serial.print(var,HEX) won't print the HEX values with Leading zeros. we need to find a way to do it.

In C there is a function called sprintf() which will be the saviour of our day.
It is used to format a string which is used to print at the output

the syntax of sprintf is
sprintf(char *str,const char* format)

But first we wanted to print hex values so we need to know the different HEX format specifiers.
we can simply know by compiling and running this simple code

#include
int main() {
int data = 29;
printf("%x\n", data); // just print data
printf("%0x\n", data); // just print data ('0' on its own has no effect)
printf("%8x\n", data); // print in 8 width and pad with blank spaces
printf("%08x\n", data); // print in 8 width and pad with 0's

return 0;

and the result is
HEX format specifier

by using both format specifiers and sprintf we can print the hex value as it is

void setup(){
Serial.begin(9600);
int a = 0x0094;
Serial.println(a);
Serial.print("serialprint using HEx : ");
Serial.println(a,HEX);
print_hex(a);
}
void loop(){

}

void print_hex(int val){
char str[20];
sprintf(str,"%04x",val);
Serial.print("serialprint using print_hex function : ");
Serial.println(str);
}//end of printhex() function


and the output is
print_hex function


But what if we wanted to convert a decimal value to HEX and sent it as HEX?
we can use the below code to do that.

/*
Author : Kunchala Anil
converting Decimal value into HEX
*/
#define max_hex_length 4

char data_buffer[20];
int hex[4];

void setup(){
Serial.begin(9600);
}//end of main()


void loop(){
int a = serial_ask();
Serial.print("the value you entered is :");
Serial.println(a);
convert_to_hex(a);

}//end of loop

void convert_to_hex(int a){
for (int i=0; i = 0; j--){
if (hex[j] <= 9){
Serial.print(hex[j]);
}
else{
switch(hex[j]){
case 10 :
Serial.print('a');
break;

case 11 :
Serial.print('b');
break;

case 12 :
Serial.print('c');
break;

case 13 :
Serial.print('d');
break;

case 14 :
Serial.print('e');
break;

case 15 :
Serial.print('f');
break;

default :
Serial.println("something wrong");
}//end of switch
}//end of If Else Condition

}//end of for loop
Serial.println();

}//end of convert_to_hex() function


int serial_ask(){
Serial.println("enter the Integer decimal value coverted to the HEX");

while(!data_received()){
//wait until full data is received
}
return(atoi(data_buffer));

}//end of serial_ask() fucntion

boolean data_received(){
while(!Serial.available()){
//wait until user enters the data
}
if(Serial.available()){
static byte index = 0;
char input = Serial.read();
if(input != '\r'){
data_buffer[index] = input;
index ++;
}
else {
data_buffer[index] = 0;//terminating with NULL to make char array as string
index = 0;
return true;

}//end of If Else condition

}//end of IF condition
return false;
}//end of data_received() function



and the output is
dec to hex

Tuesday, 21 April 2015

Points to Remember when Writing a C program

When Declaring a Variable :
Declaration must be placed after the opening braces of the main() function.all declarations must come before the first executable(non-declaration) statements of the program.

all types of variables must be declared before they are used.


When Naming a Variable :
1.Variable name must begin with a letter of alphabet.In C underscore(_) is considered as a letter
2.Compiler treats uppercase and lowercase letters as different
3.No special characters, such as blank space,period,semicolon,comma, or slash are permitted in variable names

what is a variable ?
it is a symbolic name for a memory location in which assigned value is stored

Comments:
It is easier to put in the comments as you code the program rather than after the entire program has been completed.

Variable Initialization :
It is not sufficient to declare a variable before it is used, the variable must also be initialized.
the compiler doesn't automatically assign 0 to it when it is created.


void main(){
int a;
printf("%d",a);
getch();
}


prints the garbage value.when i try to run the output is

init_garbage


Integer Truncation Error :
fractional parts are truncated into integers which leads to horrendous errors\



Note: printf the letter f in that stands for either function or formatted

[In Progress]

Saturday, 11 April 2015

Error "avrdude: stk500_getsync(): not in sync: resp=0x00" How to get Rid of it

when the error avrdude: stk500_getsync(): not in sync: resp=0x00 comes in screen
error

it is usually comes because of selecting the wrong com port in the arduino tools menu
we can usually see which port we connected by the following method

go to the control panel --> Hardware and Sounds --> device manager --> Ports(Com & LPT)
COM port

and set the correct the com port in Arduino Tools Menu. OR may be due to selection of other Arduino Board

Friday, 10 April 2015

Friday, 20 February 2015

Arduino as Voltmeter

First let's forget about Arduino
Voltmeter is used to measure voltage between two points. we always measure/connect the voltmeter parallel to the load.

do you ever get the doubt
why do i always connect voltmeter in Parallel to the load not in Series?

voltmeter

simple answer for that is the voltage is same in the parallel circuit. The same voltage that represent in load is same that will go through the voltmeter (But Why? I didn't understand the answer for it)


Using Arduino to Measure Voltage :
Arduino ADC's are capable of Measuring voltage with-in range of 0-5 volts. so if we wanted to measure voltage below 0-5 volts we simply connect the point where we wanted to measure voltage and two grounds and by performing analogRead() we can know the voltage at that point.

But What if we wanted to measure the voltage greater than 5 volts using Arduino?
we can don this by using Voltage Divider.
Voltage divider is nothing more than two resistors connected in series with battery. As Name implies the two resistors in series are used to divide the applied voltage.
voltage divider

the applied voltage V = Vr1 + Vr2

Vr1 = V * R1 /(R1 + R2)
Vr2 = V * R2/(R1 + R2)

which is also known as voltage divider rule.

from the above formula's if we know the voltage at the One resistor we can find the overall voltage supplied to the voltage divider circuit.
from Ohm's law. v directly proportional to R.
by using different combinations of Resistor we can reduce the voltage at the measuring point at which Arduino is used to measure the voltage at R2,by using that value we can measure the overall voltage with the help of the above formula.
Arduino Voltmeter
typical combinations of R1 and R2 is 100k and 10k respectively for 0 to 55 volts measurement

Arduino ADC has an 10 Bit Resolution or 4.9 mv for unit.

The code to find the voltage is

#define R1 100000 // Value of R1 Resistor
#define R2 10000 // Value of R2 Resistor
void setup(){
Serial.begin(9600); // start the serial communication
pinMode(A0,INPUT);
}//end of setup
void loop(){
int vr2 = analogRead(A0);
vr2 = vr2 * 0.0049;
Serial.print("The voltage is");
Serial.print(vr2*(R1+R2)/R2);
}

Monday, 17 November 2014

Serial Communication on Arduino

Just I wanted to you know guy's  whatever i write here not is my own brain....
its just a collection of so many resources..... using my own words... I will to try to make it simple.. and reply me if there is any mistakes.. and those mistakes are most welcomed.

It took me almost two weeks to understand a bit of Serial Communication Fundamentals... I thought these are worth mentioning

Ok.. First of all we can communicate with arduino usb cable connected to Pc using digital pins 0 and 1. arduino provides an serial monitor to communicate with it.
In Arduino Uno digital Pins 0 and 1 are called Hardware serial. they communicate with built-in UART in arduino.

we need to know two commands( I don't know they are called commands? tell me if you know) to receive the data from arduino serial.
1.Serial.available()
2.Serial.read()

One Quick Point: Whatever we Send or Receive from the serial is a character. a byte of data.

when we call Serial.available(), it returns us the number of bytes in the Serial Buffer and '0' if there is nothing.

Serial.read(), will returns a single byte or character from the serial buffer and we receive the oldest entry in the buffer.

we can send the data using Serial.print() command.

so if we want to send a data from arduino to pc via Serial communication.. the program will look like this.

void setup(){
Serial.begin(9600); //start the Serial communication 9600 is baud rate. baud rate : bits per second
Serial.println("Arduino");//print the data
}
void loop(){
// here loop doing nothing....
}


I don't know why we write void setup() and void loop().... these are just one of the rules and regulations you have to follow otherwise you won't survive in arduino world. there are reasons for them But I dont wanna know.. why.. I dont wanna go that deep in the arduino ocean.. I am just here touching the water.. I dont wanna go and drown my self in ... I dont even know how to swim yet.
Ok.. now back to the Serial.print("");
when we call the serial.print(""), it will write the data into serialbuffer and send the data byte by byte using interrupts.. and again i dont want to go deep. I wanted to you to know that arduino just load it to that buffer and serial interrupts take care of it. so arduino wont wait until it sends finishing.
we can check this using Serial.flush()
Quick point : Serial.flush() is only for Transmitter Section. It just wait till the transmitter is fully transferred.
To receive data serially first we need to check is there any data available on serial buffer.
we can do this by using Serial.available() command.
Quick point: we don't have control over the serial communication
so to receive data serially the program is like

void setup(){
Serial.begin(9600); start serial communication with 9600 baud rate
}
void loop(){
while(Serial.available()){
//wait until user enters data or serial data available
}
char in_byte = serial.read();
Serial.println(in_byte);
}


the above code just receives one byte from Serial and prints it in Serial monitor.

what if we wanted to receive more than one byte.
Quick note: if we used baud rate 9600, then to receive 1 byte it takes 10 micro seconds(approximately).
But to execute a instruction arduino takes less than 50 nano seconds. so it with in the time of receiving a single character, arduino will execute a 100's of executions. So it will be a waste of time to wait for all the serial data to come.

So we dont want waste the arduino time.
so we want to send a signal that all the data is received on arduino and then only we have to read the data. otherwise we will be reading whatever it is present in the buffer, it may be half of our required data or full data if we are lucky... I dont considered myself as lucky.. so i don't wanted to go on that way.
So lets write our program.....
goal of the program : we have to read the full data (Complete String) from the serial Buffer.
Quick note : when we press the "Enter". we are actually sending a carriage return. so by default when we enter data we are sending a data + carriage return
Ok.. lets start the coding.
first we need to have a buffer to store the data which is received in the serial buffer. so we need to initialize the buffer

#define data_buffer_size 40 // maximum number of bytes we may receive
char data_buffer[data_buffer_size +1 ] // +1 is for Null character


quick note: in c++ we have to add a null character '0' at the end of the character array, so the compiler will recognize it as end of the array (I am not sure if is it write or wrong let me know if it is wrong)

after that we need to write the setup() function.. goes like this.

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

if you wanted to learn arduino, besides books.. Arduino forum is a great resource.. there are so many people like us struggling with this little board and its coding..
many users are providing help and showing a way to solve our problems...
there is post by robin2. which is really helpful if you are new to programming language like me Planning and Implementing an Arduino Program.

In loop() function


void loop(){
const String question_1 = "Please enter the Data_1 "; // specifying the question to be asked
ask_user_ques(question_1); // this function is used to ask the user question. it passes argument question to the function where it is printed on serial monitor
while(!get_the_response()){;//get_the_response() function is used to check whether data is fully received or not. if total data is received it stored in the data buffer for further use
//wait until get_the_response() returns true
}///end of the while function
// here we received the full data so display it
Serial.print("the data you entered is --------> \t"); // "\t" leaves the Tab space
Serial.print(data_buffer);// print the received data
Serial.println("") // print a line
}//end of the loop function


//here we are going to define our two functions
void ask_user_ques(String question){
Serial.println(question); // print the data on the serial monitor
return;
}//end of the ask_user_ques() function


boolean get_the_response(){
char in_byte; // variable to assign the received character
byte byte_index; // to indicate the number of bytes
while(!Serial.available()){
//wait until user enters the data
// note the "!" sign
}//end of while loop
while(Serial.available()){ // this loop continuously checks is there any data available in the Serial buffer and run the loop until it is empty.
in_char = Serial.read(); // read the character from the serial buffer. we can only read one character at a time
if (in_char == '\r'){ // if received character is the end character... we can change this to our requirements
data_buffer[byte_index] = 0; // terminating the character array with Null Terminator
byte_index = 0// resetting the byte_index so it can read from the stating
return true; // we received the all data return true. so we can read the data from data_buffer variable
}//end of the if
else {// if we received anything else other than ending character
data_buffer[byte_index] = in_char; // add the received character into the data buffer
byte_index++;// increment the byte index which is equal to byte_index = byte_index+1
}
}// end of the while loop
return false; // we do not received the full data Yet.. So Return false
}// end of get_the_response() functtion

this is my first i hope you understand it. if you don't.. please let me know.......