CO2Modbus.c


1
/*
2
 * CO2Modbus.c
3
 *
4
 * Created: 19.03.2015 17:19:59
5
 *  Author: Johannes1
6
 */ 
7
8
9
#include <avr/io.h>
10
#include "uart0.h"
11
#include "uart1.h"
12
#include "util/delay.h"
13
14
uint16_t ModRTU_CRC(uint8_t buf[], int len);
15
int main(void)
16
{  
17
  uint8_t buffer[8],crc_low,crc_high,i;
18
  uint8_t receive_buffer[14];
19
  uint16_t crc;
20
  uart0_init(9600,1,1);
21
  uart1_init_x(9600,1,1,8,0,0,1,2);
22
23
  DDRH &=~(1<<PH0);
24
  DDRA &=~(1<<DDA1);
25
  //HIGH....Transmit
26
  //LOW.....Receive
27
  PORTH|=(1<<PH0);
28
  PORTA|=(1<<PA1);
29
  buffer[0]=0x01;
30
  buffer[1]=0x04;
31
  buffer[2]=0x00;
32
  buffer[3]=0x0C;
33
  buffer[4]=0x00;
34
  buffer[5]=0x01;
35
  buffer[6]=0x00;
36
  buffer[7]=0x00;
37
  
38
  crc=ModRTU_CRC(buffer,6);
39
  crc_high=crc>>8;
40
  crc_low=crc&0xFF;
41
    uart0_putCharAsHex(crc_low);
42
  uart0_putCharAsHex(crc_high);
43
  buffer[6]= crc_low;
44
  buffer[7]= crc_high;
45
  for(i=0;i<8;i++)
46
  {
47
    uart1_putc(buffer[i]);
48
  }
49
  while ( (UCSR1A & (1<<UDRE1)) == 0);
50
  //PORTH&=~(1<<PH0);
51
  //PORTA&=~(1<<PA1);
52
  
53
  for(i=0;i<8;i++)
54
  {
55
    receive_buffer[i]=uart1_getc();
56
57
    
58
  }
59
  
60
  for(i=0;i<9;i++)
61
    uart0_putCharAsHex(receive_buffer[0]);
62
  
63
    while(1)
64
    {
65
66
    }
67
}
68
69
// Compute the MODBUS RTU CRC
70
uint16_t ModRTU_CRC(uint8_t buf[], int len)
71
{
72
  uint16_t crc = 0xFFFF;
73
  
74
  for (int pos = 0; pos < len; pos++) {
75
    crc ^= (uint16_t)buf[pos];          // XOR byte into least sig. byte of crc
76
    
77
    for (int i = 8; i != 0; i--) {    // Loop over each bit
78
    if ((crc & 0x0001) != 0) {      // If the LSB is set
79
    crc >>= 1;                    // Shift right and XOR 0xA001
80
    crc ^= 0xA001;
81
  }
82
  else                            // Else LSB is not set
83
  crc >>= 1;                    // Just shift right
84
}
85
  }
86
  // Note, this number has low and high bytes swapped, so use it accordingly (or swap bytes)
87
  return crc;  
88
}