djc
Advanced Member level 1
Hello all,
I am writing a program for modbus protocol using Atmega8 and mikroc. I wrote a code to receive characters and store it in an array. Now i want to make a byte of these received characters. Like Received_char[0] and Received char[1] should form a byte, as this is a slave address, and pass this 8 bit byte to a CRC function. I am facing the issue of how to append these received characters to form a byte in mikroc. Plz guide me on this. Below is the code
I am writing a program for modbus protocol using Atmega8 and mikroc. I wrote a code to receive characters and store it in an array. Now i want to make a byte of these received characters. Like Received_char[0] and Received char[1] should form a byte, as this is a slave address, and pass this 8 bit byte to a CRC function. I am facing the issue of how to append these received characters to form a byte in mikroc. Plz guide me on this. Below is the code
C:
#define FOSC 8000000//1843200// Clock Speed
#define BAUD 9600
#define MYUBRR FOSC/16/BAUD-1
sbit LCD_RS at PORTD4_bit;
sbit LCD_EN at PORTD3_bit;
sbit LCD_D4 at PORTD5_bit;
sbit LCD_D5 at PORTD6_bit;
sbit LCD_D6 at PORTD7_bit;
sbit LCD_D7 at PORTB0_bit;
sbit LCD_RS_Direction at DDD4_bit;
sbit LCD_EN_Direction at DDD3_bit;
sbit LCD_D4_Direction at DDD5_bit;
sbit LCD_D5_Direction at DDD6_bit;
sbit LCD_D6_Direction at DDD7_bit;
sbit LCD_D7_Direction at DDB0_bit;
char Mydata[1],i=0,j=0,flag=0;
char Data[15];
int len=8;
char Received_Data[10];
unsigned char cur_crc;
unsigned short ModBus_CRC16( unsigned char * Buffer, unsigned short Length )
{
cur_crc=0xFFFF;
do
{
unsigned int i = 8;
cur_crc = cur_crc ^ *Buffer++;
do
{
if (0x0001 & cur_crc)
{
cur_crc >>= 1;
cur_crc ^= 0xA001;
}
else
{
cur_crc >>= 1;
}
}
while (--i);
}
while (--Length);
return cur_crc;
}
void main() {
DDRD |= 1 << PIND1;//pin1 of portD as OUTPUT
DDRD &= ~(1 << PIND0);//pin0 of portD as INPUT
PORTD |= 1 << PIND0;
Lcd_Init();
LCD_Out(1,1,"Test");
UART1_Init(9600); // initialize UART1 module
Delay_ms(100);
while(1){
if (UART1_Data_Ready()) { // If data is received,
Received_Data[i] = UART1_Read(); // read the received data,
if(Received_Data[i]=='#'){
j=i;
flag=1;
for(j=0;j<=i;j++){
UART1_Write(Received_Data[j]);
Delay_ms(2);
}
i=0;j=0;
}
else{i++;}
//i=0;
}
if(flag==1){
Mydata[0] = (Received_Data[0]-48)*10 + (Received_Data[1]-48);//Here i am processing first byte of data
IntToStr(Mydata[0], Data); //Convert it into string
UART1_Write_Text(Data); //Display it
Delay_ms(1);
ModBus_CRC16(Data,1); //Call the function to calculate CRC
IntToStr(cur_crc, Data); //Convert into string to display
LCD_Out(2,1,Data); //Display it on LCD
Delay_ms(1);
UART1_Write_Text(Data); //Display it on UART
Delay_ms(1);
flag=0;i=0;
}
}
}