2 Commits ef229fb1d7 ... e413326128

Author SHA1 Message Date
  vreiling e413326128 ADC 7 years ago
  vreiling 2bd6d374d8 ADC für MPC5646C 7 years ago

+ 69 - 70
BMS Master/.project

@@ -1,70 +1,69 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
-	<name>BMS Master</name>
-	<comment></comment>
-	<projects>
-	</projects>
-	<buildSpec>
-		<buildCommand>
-			<name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
-			<triggers>clean,full,incremental,</triggers>
-			<arguments>
-				<dictionary>
-					<key>?name?</key>
-					<value></value>
-				</dictionary>
-				<dictionary>
-					<key>org.eclipse.cdt.make.core.append_environment</key>
-					<value>true</value>
-				</dictionary>
-				<dictionary>
-					<key>org.eclipse.cdt.make.core.buildArguments</key>
-					<value>-j8</value>
-				</dictionary>
-				<dictionary>
-					<key>org.eclipse.cdt.make.core.buildCommand</key>
-					<value>${GNU_Make_Install_Dir}mingw32-make</value>
-				</dictionary>
-				<dictionary>
-					<key>org.eclipse.cdt.make.core.buildLocation</key>
-					<value>${ProjDirPath}/RAM</value>
-				</dictionary>
-				<dictionary>
-					<key>org.eclipse.cdt.make.core.contents</key>
-					<value>org.eclipse.cdt.make.core.activeConfigSettings</value>
-				</dictionary>
-				<dictionary>
-					<key>org.eclipse.cdt.make.core.enableAutoBuild</key>
-					<value>false</value>
-				</dictionary>
-				<dictionary>
-					<key>org.eclipse.cdt.make.core.enableCleanBuild</key>
-					<value>true</value>
-				</dictionary>
-				<dictionary>
-					<key>org.eclipse.cdt.make.core.enableFullBuild</key>
-					<value>true</value>
-				</dictionary>
-				<dictionary>
-					<key>org.eclipse.cdt.make.core.stopOnError</key>
-					<value>true</value>
-				</dictionary>
-				<dictionary>
-					<key>org.eclipse.cdt.make.core.useDefaultBuildCmd</key>
-					<value>true</value>
-				</dictionary>
-			</arguments>
-		</buildCommand>
-		<buildCommand>
-			<name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
-			<triggers>full,incremental,</triggers>
-			<arguments>
-			</arguments>
-		</buildCommand>
-	</buildSpec>
-	<natures>
-		<nature>org.eclipse.cdt.core.cnature</nature>
-		<nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
-		<nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
-	</natures>
-</projectDescription>
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+	<name>BMS Master</name>
+	<comment></comment>
+	<projects>
+	</projects>
+	<buildSpec>
+		<buildCommand>
+			<name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
+			<arguments>
+				<dictionary>
+					<key>?name?</key>
+					<value></value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.append_environment</key>
+					<value>true</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.buildArguments</key>
+					<value>-j8</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.buildCommand</key>
+					<value>${GNU_Make_Install_Dir}mingw32-make</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.buildLocation</key>
+					<value>${ProjDirPath}/RAM</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.contents</key>
+					<value>org.eclipse.cdt.make.core.activeConfigSettings</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.enableAutoBuild</key>
+					<value>false</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.enableCleanBuild</key>
+					<value>true</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.enableFullBuild</key>
+					<value>true</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.stopOnError</key>
+					<value>true</value>
+				</dictionary>
+				<dictionary>
+					<key>org.eclipse.cdt.make.core.useDefaultBuildCmd</key>
+					<value>true</value>
+				</dictionary>
+			</arguments>
+		</buildCommand>
+		<buildCommand>
+			<name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
+			<triggers>full,incremental,</triggers>
+			<arguments>
+			</arguments>
+		</buildCommand>
+	</buildSpec>
+	<natures>
+		<nature>org.eclipse.cdt.core.cnature</nature>
+		<nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
+		<nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
+	</natures>
+</projectDescription>

+ 163 - 163
BMS Master/Project_Headers/BMS_CANx_Tools.h

@@ -1,163 +1,163 @@
-//##############################################################################
-//
-// FILE:	BMS_CANx_Tools.h
-//
-// TITLE:	Header for BMS_CANx_Tools.c
-//
-//Modified for Use in RCT Project
-//##############################################################################
-//
-//==============================================================================
-// Change History:
-//==============================================================================
-// Datum:   | Name | Version:| Change / Cause:                            | No
-//------------------------------------------------------------------------------
-//          |      |         |                                            | 002
-//------------------------------------------------------------------------------
-// 01.08.13 |  VR  |   1.1   | IAA Project                                | 001
-//------------------------------------------------------------------------------
-// 20.04.12 |  TM  |   1.0   | New Build                                  | 000
-//==============================================================================
-//==============================================================================
-// Comment Change / Cause:
-//==============================================================================
-// Change: 003                                                           // 003
-//----------------------
-//                                                       
-//
-//==============================================================================
-// Change: 002                                                           // 002
-//----------------------
-//                                           
-//
-//==============================================================================
-// Change: 001                                                           // 001
-//----------------------
-// 
-//
-//==============================================================================
-
-#ifndef __CAN_MASTER_H__
-#define __CAN_MASTER_H__
-
-
-
-
-#ifdef __cplusplus
-    extern "C" {
-#endif
-    
-
-
-// ***** External **************************************************************
-//extern CAN_MAILBOX	CAN_TxMB_BalancingCtrl_100;
-//
-//extern CAN_MAILBOX	CAN_TxMB_NLG5_CTL_618;
-//
-//extern CAN_MAILBOX	CAN_TxMB_BMU_DICO_18FF9F1E;
-//extern CAN_MAILBOX	CAN_TxMB_BMU1_EVCU1_18FF9E1E;
-//extern CAN_MAILBOX	CAN_RxMB_DICO1_EVCU_18FF8F03;
-//extern CAN_MAILBOX	CAN_RxMB_DICO2_EVCU_18FF8D03;
-//extern CAN_MAILBOX	CAN_RxMB_EVCU1_BMU_0CFF3D27;
-    
-
-
-
-
-extern MASTER_X_BMS_TELEGRAM	TelegramTxContainer[16];
-extern CAN_MAILBOX* MB_Container[16];
-
-// Mailboxes for Automatic CAN Id Initialization
-
-extern CAN_MAILBOX CAN_TxMB_System300;
-extern CAN_MAILBOX CAN_TxMB_System30A;
-extern CAN_MAILBOX CAN_TxMB_Master0A;
-
-
-
-
-// ***** Funktion Prototypes ***************************************************
-uint16_t 	CAN_Tx_Balance				( uint16_t i);
-void		check_and_save_Voltage		( CAN_MAILBOX *p_MBox, uint16_t SlaveNr, uint16_t SlaveOffset );
-void		check_and_save_Status		( CAN_MAILBOX *p_MBox, uint16_t SlaveNr );
-void		check_and_save_UI			( CAN_MAILBOX *p_MBox );
-void		check_and_save_Temperature	( CAN_MAILBOX *p_MBox, uint16_t SlaveNr, uint16_t SlaveOffset );
-int16_t 	check_Voltage_Border		( uint16_t Row, uint16_t Index );
-int16_t 	check_Status_Border			( uint16_t Row, uint16_t Index );
-int16_t 	check_UI_Border				( uint16_t Row  );
-int16_t 	check_Temperature_Border	( uint16_t Row, uint16_t Index );
-uint16_t 	Sum_Cell_Voltage			( uint16_t Row );
-uint16_t 	Test_MAX_LOAD_CELL_VOLTAGE	( uint16_t Row );
-uint16_t 	Search_MIN_CELL_VOLTAGE		( uint16_t Row );
-
-
-uint16_t 	CAN_Tx_NLG5_CTL_618			( void );
-void 		check_and_save_NLG5_ST		( CAN_MAILBOX *p_MBox );
-
-uint16_t 	CAN_Tx_BMU_DICO				( void );   
-uint16_t 	CAN_Tx_BMU1_EVCU1			( void ); 
-uint16_t 	check_and_save_DICO1_EVCU	( CAN_MAILBOX *p_MBox ); 
-uint16_t 	check_and_save_DICO2_EVCU	( CAN_MAILBOX *p_MBox );           
-uint16_t 	check_and_save_EVCU1_BMU	( CAN_MAILBOX *p_MBox );    
-
-uint16_t CAN_Rx_readout_Mailbox(CAN_MAILBOX *p_MBox,uint8_t *eight_byte_field);
-
-
-
-// ***** Global Prototypes *****************************************************
-uint16_t 	CAN0_init						(void);
-uint16_t 	CAN0_rx_test					(void); 
-uint16_t 	CAN0_tx_test					(uint8_t slave_nr,uint8_t *four_byte_field);
-//uint16_t	CAN0_tx_send_request_telegram	(uint8_t slaveNr);
-uint16_t	CAN0_tx_send_request_telegram	(BMS_CAN0_SLAVE_t* Slave,uint8_t MasterAlive);
-uint16_t 	CAN0_init_telegrams				(MASTER_X_BMS_TELEGRAM* telegram_ptr,uint8_t nrOfSlaves);
-uint16_t	CAN0_is_state_active			(uint8_t* activeSlaves,uint8_t nrOfActiveSlaves,uint8_t nrOfCurrentSlave);
-
-
-uint8_t 	CAN0_check_if_UI_Board_rec(BMS_CAN0_SLAVE_t* Slave,BMS_CAN0_UI_t* UI_Board);
-uint16_t 	CAN0_check_if_slave_rec			(BMS_CAN0_SLAVE_t* Slave);
-uint16_t 	saveSlaveX0_Master_telegram		(BMS_CAN0_SLAVE_t* Slave);
-uint16_t 	saveSlaveX1_Master_telegram		(BMS_CAN0_SLAVE_t* Slave);
-uint16_t 	saveSlaveX2_Master_telegram		(BMS_CAN0_SLAVE_t* Slave);
-uint16_t 	saveSlaveX3_Master_telegram		(BMS_CAN0_SLAVE_t* Slave);
-uint16_t 	saveSlaveX4_Master_telegram		(BMS_CAN0_SLAVE_t* Slave);
-uint16_t 	saveSlaveX5_Master_telegram		(BMS_CAN0_SLAVE_t* Slave);
-uint16_t 	saveSlaveX6_Master_telegram		(BMS_CAN0_SLAVE_t* Slave);
-uint16_t 	saveSlaveUI_Master_telegram(BMS_CAN0_SLAVE_t* Slave,BMS_CAN0_UI_t* UI_Board);
-uint16_t 	saveSlaveX7_Master_telegram		(BMS_CAN0_SLAVE_t* Slave);
-
-uint16_t 	CAN0_DEBUG_data_check_if_slave_rec(BMS_CAN0_SLAVE_t* Slave,BMS_CAN0_SLAVE_t* DummySlave);
-uint8_t 	CAN0_DEBUG_data_check_if_UI_Board_rec(BMS_CAN0_SLAVE_t* Slave,BMS_CAN0_SLAVE_t* DummySlave,BMS_CAN0_UI_t* UI_Board,BMS_CAN0_UI_t* Dummy_UI_Board);
-uint16_t 	CAN0_DEBUG_slave_check_if_slave_rec(BMS_CAN0_SLAVE_t* Slave,BMS_CAN0_SLAVE_t* DummySlave);
-uint8_t 	CAN0_DEBUG_slave_check_if_UI_Board_rec(BMS_CAN0_SLAVE_t* Slave,BMS_CAN0_SLAVE_t* DummySlave,BMS_CAN0_UI_t* UI_Board,BMS_CAN0_UI_t* Dummy_UI_Board);
-uint16_t 	CAN0_update						(void);
-
-uint16_t 	CAN1_init						(void);
-uint16_t 	CAN1_update						(void);
-int16_t 	CAN1_tx_Data_to_Inverter		(uint32_t timestamp,BMS_CAN1_INVERTER_TX* data);
-uint16_t 	CAN1_init_tx_structure			(BMS_CAN1_INVERTER_TX* tx_struct);
-int16_t 	CAN1_send_request_telegram(uint32_t requestId) ;
-uint16_t 	CAN1_wait_for_response(float* value); 
-uint32_t delay_CAN1_ms(uint32_t timestamp,uint32_t delay_ms);
-uint16_t CAN_Tx_MasterX_BMS(MASTER_CAN0_STRUCT_t* s, uint8_t SlaveNummer, uint8_t MasterAlive, uint8_t SetMode, uint32_t Balancer );
-
-uint16_t CAN_Tx_System300( uint16_t IDSEARCH );
-uint16_t CAN_Tx_MasterXA();
-uint32_t CAN0_check_serial_nr_rec_Can_init(MASTER_CAN0_STRUCT_t*s ,uint8_t SlaveNr);
-uint16_t CAN_Tx_System30A( uint8_t *pSERNr );
-
-
-
-
-#ifdef __cplusplus
-    }
-#endif
-
-    
-    
-#endif  /* ifndef*/
-
-    
-    
-// ***** End BMS_CANx_Tools.h **************************************************
-    
+//##############################################################################
+//
+// FILE:	BMS_CANx_Tools.h
+//
+// TITLE:	Header for BMS_CANx_Tools.c
+//
+//Modified for Use in RCT Project
+//##############################################################################
+//
+//==============================================================================
+// Change History:
+//==============================================================================
+// Datum:   | Name | Version:| Change / Cause:                            | No
+//------------------------------------------------------------------------------
+//          |      |         |                                            | 002
+//------------------------------------------------------------------------------
+// 01.08.13 |  VR  |   1.1   | IAA Project                                | 001
+//------------------------------------------------------------------------------
+// 20.04.12 |  TM  |   1.0   | New Build                                  | 000
+//==============================================================================
+//==============================================================================
+// Comment Change / Cause:
+//==============================================================================
+// Change: 003                                                           // 003
+//----------------------
+//                                                       
+//
+//==============================================================================
+// Change: 002                                                           // 002
+//----------------------
+//                                           
+//
+//==============================================================================
+// Change: 001                                                           // 001
+//----------------------
+// 
+//
+//==============================================================================
+
+#ifndef __CAN_MASTER_H__
+#define __CAN_MASTER_H__
+
+
+
+
+#ifdef __cplusplus
+    extern "C" {
+#endif
+    
+
+
+// ***** External **************************************************************
+//extern CAN_MAILBOX	CAN_TxMB_BalancingCtrl_100;
+//
+//extern CAN_MAILBOX	CAN_TxMB_NLG5_CTL_618;
+//
+//extern CAN_MAILBOX	CAN_TxMB_BMU_DICO_18FF9F1E;
+//extern CAN_MAILBOX	CAN_TxMB_BMU1_EVCU1_18FF9E1E;
+//extern CAN_MAILBOX	CAN_RxMB_DICO1_EVCU_18FF8F03;
+//extern CAN_MAILBOX	CAN_RxMB_DICO2_EVCU_18FF8D03;
+//extern CAN_MAILBOX	CAN_RxMB_EVCU1_BMU_0CFF3D27;
+    
+
+
+
+
+extern MASTER_X_BMS_TELEGRAM	TelegramTxContainer[16];
+extern CAN_MAILBOX* MB_Container[16];
+
+// Mailboxes for Automatic CAN Id Initialization
+
+extern CAN_MAILBOX CAN_TxMB_System300;
+extern CAN_MAILBOX CAN_TxMB_System30A;
+extern CAN_MAILBOX CAN_TxMB_Master0A;
+
+
+
+
+// ***** Funktion Prototypes ***************************************************
+uint16_t 	CAN_Tx_Balance				( uint16_t i);
+void		check_and_save_Voltage		( CAN_MAILBOX *p_MBox, uint16_t SlaveNr, uint16_t SlaveOffset );
+void		check_and_save_Status		( CAN_MAILBOX *p_MBox, uint16_t SlaveNr );
+void		check_and_save_UI			( CAN_MAILBOX *p_MBox );
+void		check_and_save_Temperature	( CAN_MAILBOX *p_MBox, uint16_t SlaveNr, uint16_t SlaveOffset );
+int16_t 	check_Voltage_Border		( uint16_t Row, uint16_t Index );
+int16_t 	check_Status_Border			( uint16_t Row, uint16_t Index );
+int16_t 	check_UI_Border				( uint16_t Row  );
+int16_t 	check_Temperature_Border	( uint16_t Row, uint16_t Index );
+uint16_t 	Sum_Cell_Voltage			( uint16_t Row );
+uint16_t 	Test_MAX_LOAD_CELL_VOLTAGE	( uint16_t Row );
+uint16_t 	Search_MIN_CELL_VOLTAGE		( uint16_t Row );
+
+
+uint16_t 	CAN_Tx_NLG5_CTL_618			( void );
+void 		check_and_save_NLG5_ST		( CAN_MAILBOX *p_MBox );
+
+uint16_t 	CAN_Tx_BMU_DICO				( void );   
+uint16_t 	CAN_Tx_BMU1_EVCU1			( void ); 
+uint16_t 	check_and_save_DICO1_EVCU	( CAN_MAILBOX *p_MBox ); 
+uint16_t 	check_and_save_DICO2_EVCU	( CAN_MAILBOX *p_MBox );           
+uint16_t 	check_and_save_EVCU1_BMU	( CAN_MAILBOX *p_MBox );    
+
+uint16_t CAN_Rx_readout_Mailbox(CAN_MAILBOX *p_MBox,uint8_t *eight_byte_field);
+
+
+
+// ***** Global Prototypes *****************************************************
+uint16_t 	CAN0_init						(void);
+uint16_t 	CAN0_rx_test					(void); 
+uint16_t 	CAN0_tx_test					(uint8_t slave_nr,uint8_t *four_byte_field);
+//uint16_t	CAN0_tx_send_request_telegram	(uint8_t slaveNr);
+uint16_t	CAN0_tx_send_request_telegram	(BMS_CAN0_SLAVE_t* Slave,uint8_t MasterAlive);
+uint16_t 	CAN0_init_telegrams				(MASTER_X_BMS_TELEGRAM* telegram_ptr,uint8_t nrOfSlaves);
+uint16_t	CAN0_is_state_active			(uint8_t* activeSlaves,uint8_t nrOfActiveSlaves,uint8_t nrOfCurrentSlave);
+
+
+uint8_t 	CAN0_check_if_UI_Board_rec(BMS_CAN0_SLAVE_t* Slave,BMS_CAN0_UI_t* UI_Board);
+uint16_t 	CAN0_check_if_slave_rec			(BMS_CAN0_SLAVE_t* Slave);
+uint16_t 	saveSlaveX0_Master_telegram		(BMS_CAN0_SLAVE_t* Slave);
+uint16_t 	saveSlaveX1_Master_telegram		(BMS_CAN0_SLAVE_t* Slave);
+uint16_t 	saveSlaveX2_Master_telegram		(BMS_CAN0_SLAVE_t* Slave);
+uint16_t 	saveSlaveX3_Master_telegram		(BMS_CAN0_SLAVE_t* Slave);
+uint16_t 	saveSlaveX4_Master_telegram		(BMS_CAN0_SLAVE_t* Slave);
+uint16_t 	saveSlaveX5_Master_telegram		(BMS_CAN0_SLAVE_t* Slave);
+uint16_t 	saveSlaveX6_Master_telegram		(BMS_CAN0_SLAVE_t* Slave);
+uint16_t 	saveSlaveUI_Master_telegram(BMS_CAN0_SLAVE_t* Slave,BMS_CAN0_UI_t* UI_Board);
+uint16_t 	saveSlaveX7_Master_telegram		(BMS_CAN0_SLAVE_t* Slave);
+
+uint16_t 	CAN0_DEBUG_data_check_if_slave_rec(BMS_CAN0_SLAVE_t* Slave,BMS_CAN0_SLAVE_t* DummySlave);
+uint8_t 	CAN0_DEBUG_data_check_if_UI_Board_rec(BMS_CAN0_SLAVE_t* Slave,BMS_CAN0_SLAVE_t* DummySlave,BMS_CAN0_UI_t* UI_Board,BMS_CAN0_UI_t* Dummy_UI_Board);
+uint16_t 	CAN0_DEBUG_slave_check_if_slave_rec(BMS_CAN0_SLAVE_t* Slave,BMS_CAN0_SLAVE_t* DummySlave);
+uint8_t 	CAN0_DEBUG_slave_check_if_UI_Board_rec(BMS_CAN0_SLAVE_t* Slave,BMS_CAN0_SLAVE_t* DummySlave,BMS_CAN0_UI_t* UI_Board,BMS_CAN0_UI_t* Dummy_UI_Board);
+uint16_t 	CAN0_update						(void);
+
+uint16_t 	CAN1_init						(void);
+uint16_t 	CAN1_update						(void);
+int16_t 	CAN1_tx_Data_to_Inverter		(uint64_t timestamp,BMS_CAN1_INVERTER_TX* data);
+uint16_t 	CAN1_init_tx_structure			(BMS_CAN1_INVERTER_TX* tx_struct);
+int16_t 	CAN1_send_request_telegram(uint32_t requestId) ;
+uint16_t 	CAN1_wait_for_response(float* value); 
+uint32_t delay_CAN1_ms(uint64_t timestamp,uint32_t delay_ms);
+uint16_t CAN_Tx_MasterX_BMS(MASTER_CAN0_STRUCT_t* s, uint8_t SlaveNummer, uint8_t MasterAlive, uint8_t SetMode, uint32_t Balancer );
+
+uint16_t CAN_Tx_System300( uint16_t IDSEARCH );
+uint16_t CAN_Tx_MasterXA();
+uint32_t CAN0_check_serial_nr_rec_Can_init(MASTER_CAN0_STRUCT_t*s ,uint8_t SlaveNr);
+uint16_t CAN_Tx_System30A( uint8_t *pSERNr );
+
+
+
+
+#ifdef __cplusplus
+    }
+#endif
+
+    
+    
+#endif  /* ifndef*/
+
+    
+    
+// ***** End BMS_CANx_Tools.h **************************************************
+    

+ 237 - 237
BMS Master/Project_Headers/BMS_Master.h

@@ -1,237 +1,237 @@
-//##############################################################################
-//
-// FILE:	BMS_Master.h
-//
-// TITLE:	Central Header & Main Header
-//
-//
-//##############################################################################
-//
-//==============================================================================
-// Change History:
-//==============================================================================
-// Datum:   | Name | Version:| Change / Cause:                            | No
-//------------------------------------------------------------------------------
-//          |      |         |                                            | 002
-//------------------------------------------------------------------------------
-// 07.02.14 |  VR  |   1.1   | upgrade 2 CoreWarrior 10.5 id: 130916      | 001
-//------------------------------------------------------------------------------
-// 20.04.12 |  TM  |   1.0   | New Build                                  | 000
-//==============================================================================
-//==============================================================================
-// Comment Change / Cause:
-//==============================================================================
-// Change: 003                                                           // 003
-//----------------------
-//                                                       
-//
-//==============================================================================
-// Change: 002                                                           // 002
-//----------------------
-//                                           
-//
-//==============================================================================
-// Change: 001                                                           // 001
-//----------------------
-// 
-//
-//==============================================================================
-
-#ifndef __BMS_MASTER_H__
-#define __BMS_MASTER_H__
-
-
-
-// ***** Includes **************************************************************
-#include "MPC5646C.h"
-#include "Typedefs.h"
-#include "IntcInterrupts.h"
-#include "Device.h"
-#include "FlexCAN.h"
-#include "BMS_Typedefs.h"
-#include "BMS_CANx_Tools.h"
-#include "BMS_CAN0_gen_test_data.h"
-#include "DSPI.h"
-#include "FRAM.h"
-#include "BoardPeripherals.h"
-#include "MultitaskOS.h"
-#include "RelaisLEDs.h"
-#include "BMS_Defines.h"
-
-#include "UartToUsb.h"
-#include "LIN_Uart.h"
-#include "DebugUndTest.h"
-#include "TempSensorSpi.h"
-#include "utils.h"
-
-#include "BMS_SoC_estimator.h"
-
-
-
-// ***** global Variables **********************************************************
-extern 	BSD_t	 	  gBSD;
-extern 	BSE_t		  gBSE;
-extern  uint8_t	      gMaxDischargeCurrent;
-extern 	FramStatus_t  Fram_S;
-extern	uint32_t	  gEvent;
-extern  uint32_t	  gErrorEvent;
-extern  uint8_t       gCANErrorInsert;
-extern  MASTER_CAN0_STRUCT_t gDUMMY_data_struct;
-extern CAN_MAILBOX CAN_Tx0_RCT_INVERTER;
-extern CAN_MAILBOX CAN_Tx1_RCT_INVERTER; 
-extern CAN_MAILBOX CAN_Rx_RCT_INVERTER;
-
-
-
-// ***** Local Prototypes ******************************************************
-
-	
-	uint16_t init_master_CAN0_fsm(MASTER_CAN0_STRUCT_t* s,BMS_SLAVE_CONFIGURATION_t* cellConfig,BMS_UI_CONFIGURATION_t* uiConfig);
-	uint16_t Master_CAN0_fsm(MASTER_CAN0_STRUCT_t* s,uint32_t time);
-	uint16_t init_master_operation_fsm(BMS_MASTER_OPERATION_t* opFsm);
-	uint16_t Master_operation_fsm(MASTER_CAN0_STRUCT_t* canFsm,uint32_t time,BMS_MASTER_OPERATION_t* opFsm);
-	void set_slave_cell_connection_state(MASTER_CAN0_STRUCT_t* s,uint8_t slaveNr,CELL_STATE_t* cell_state);
-	void set_slave_temp_connection_state(MASTER_CAN0_STRUCT_t* s,uint8_t slaveNr,TEMP_SENSOR_STATE_t* temp_state);
-	uint8_t check_slave_data(MASTER_CAN0_STRUCT_t* s,
-			BMS_CAN0_SLAVE_t* Slave,
-			BMS_CAN0_SLAVE_t* tempSlave,
-			int8_t overTemp_charge,
-			int8_t overTemp_discharge,
-			int8_t underTemp_charge,
-			int8_t underTemp_discharge,
-			uint16_t overVoltage,uint16_t underVoltage) ;
-	void initCellConfig(BMS_SLAVE_CONFIGURATION_t* cellConfig);
-	void initUiConfig(BMS_UI_CONFIGURATION_t* uiConfig) ;
-	
-	int16_t CAN1_request_float_value(uint32_t timestamp,float* value,uint32_t requestId) ;
-	uint16_t CAN2_init( void );
-	uint16_t CAN2_update( void );
-	uint32_t set_balancer_off(MASTER_CAN0_STRUCT_t* s) ;
-	uint32_t BMS_set_Error_check_if_stable_discharge(MASTER_CAN0_STRUCT_t* s); 
-	
-	
-	uint8_t check_UI_data(BMS_CAN0_SLAVE_t* Slave, BMS_CAN0_SLAVE_t* tempSlave,BMS_CAN0_UI_t* ui,BMS_CAN0_UI_t* tempUI);
-	uint32_t calc_block_voltage(BMS_CAN0_SLAVE_t* Slave);
-	uint32_t set_block_min_max_temp(BMS_CAN0_SLAVE_t* Slave);
-	uint32_t calc_system_voltage(MASTER_CAN0_STRUCT_t* s);
-	void calc_system_SoC(MASTER_CAN0_STRUCT_t* s);
-	void refresh_inverter_tx_data(MASTER_CAN0_STRUCT_t* s);
-	uint8_t check_if_all_values_are_initialized(MASTER_CAN0_STRUCT_t* s);
-	void shuffle_lsb_msb_can1(uint8_t* value);
-	uint16_t Master_CAN1_fsm(MASTER_CAN0_STRUCT_t* s,MASTER_CAN1_STRUCT_t* can1Fsm,uint32_t time);
-	uint16_t Master_CAN1_fsm_init(MASTER_CAN1_STRUCT_t* can1Fsm);
-	uint32_t Master_CAN1_Inverter_fsm(MASTER_CAN0_STRUCT_t* s,MASTER_CAN1_INVERTER_STRUCT_t* fsmStruct) ;
-	uint32_t set_balancer(MASTER_CAN0_STRUCT_t* s) ;
-
-	
-	uint32_t Master_Balancer_fsm(MASTER_CAN0_STRUCT_t* s);
-	uint32_t calc_min_max_voltage_slave(BMS_CAN0_SLAVE_t* Slave) ;
-	uint32_t calc_min_max_voltage_system(MASTER_CAN0_STRUCT_t* s) ;
-	uint32_t balance_cell(BMS_CAN0_SLAVE_t* Slave,uint8_t cell_nr);
-	uint32_t set_system_min_max_temp(MASTER_CAN0_STRUCT_t* s);
-	uint32_t set_system_min_max_heatsink_temp(MASTER_CAN0_STRUCT_t* s);
-	
-	uint16_t CAN0_clear_all_interrupt_flags();
-	uint32_t generateCellInfoPkg(MASTER_CAN0_STRUCT_t* s, uint8_t cellIndex,BMS_CAN1_INVERTER_CELL_DATA_t* txPkg); 
-	
-
-	uint8_t get_nr_of_connected_slaves(MASTER_CAN0_STRUCT_t* s);
-
-
-	uint32_t ErrorStackPushSlaveError(MASTER_CAN0_STRUCT_t* s,uint8_t slaveNr,uint32_t ErrorCode,uint8_t CellNr,uint8_t ErrorClass); 
-	uint32_t ErrorStackPushUiError(MASTER_CAN0_STRUCT_t* s,uint32_t ErrorCode,uint8_t ErrorClass);
-	uint32_t ErrorStackPushMasterError(MASTER_CAN0_STRUCT_t* s,uint32_t ErrorCode,uint8_t ErrorClass);
-	uint32_t ErrorStackGenerateStatusPkg(uint8_t* targetBuffer,uint8_t* ErrorCode);
-	uint32_t ErrorStackCheckBufferForError(MASTER_CAN0_STRUCT_t* s,uint32_t ErrorWord,uint8_t ErrorClass) ;
-	uint32_t ErrorStackCheckForActiveErrors(MASTER_CAN0_STRUCT_t* s,uint8_t ErrorClass); 
-	uint32_t ErrorStackClearBuffer(MASTER_CAN0_STRUCT_t* s);
-	uint32_t ErrorStackCheckForActiveErrors(MASTER_CAN0_STRUCT_t* s,uint8_t ErrorClass);
-	
-	uint32_t BMS_Clear_Error_Buffer(MASTER_CAN0_STRUCT_t* s,uint8_t ErrorClass);
-	
-	
-	uint32_t BMS_Master_ES1_fsm(MASTER_CAN0_STRUCT_t* s);
-	uint32_t BMS_Master_ES2_fsm(MASTER_CAN0_STRUCT_t* s);
-	uint32_t BMS_Master_ES3_fsm(MASTER_CAN0_STRUCT_t* s);
-	
-	
-	uint32_t BMS_Set_Error_check_Voltage_level_min(MASTER_CAN0_STRUCT_t* s);
-	
-	
-	uint16_t Master_CAN0_ERROR_fsm(MASTER_CAN0_STRUCT_t* s,uint32_t time);
-
-	
-	int32_t checkIfInverterHasPower(MASTER_CAN0_STRUCT_t* s);
-	uint32_t OPModeFSM(MASTER_CAN0_STRUCT_t* s);
-	uint32_t RunningModeFSM(MASTER_CAN0_STRUCT_t* s);
-	
-	uint32_t write_fram_byte(uint8_t byte,uint32_t timeout,const vuint16_t Addr);
-	uint32_t write_fram_word(uint16_t word,uint32_t timeout,const vuint16_t Addr);
-	uint32_t write_fram_float(float float_value,uint32_t timeout,const vuint16_t Addr); 
-	uint32_t read_fram_byte(uint8_t* word,uint32_t timeout,const vuint16_t Addr);
-	uint32_t read_fram_word(uint16_t* word,uint32_t timeout,const vuint16_t Addr);
-	uint32_t read_fram_float(float* word,uint32_t timeout,const vuint16_t Addr);
-	uint32_t write_fram_set_SoC(float SoC) ;
-	uint32_t read_fram_get_startup_state(MASTER_CAN0_STRUCT_t* s);
-	float 	read_fram_get_SoC() ;
-	uint32_t write_fram_set_startup_state(MASTER_CAN0_STRUCT_t* s) ;
-	uint32_t write_fram_clear_startup_state();
-	uint32_t write_fram_uint32(uint32_t word,uint32_t timeout,const vuint16_t Addr);
-	uint32_t read_fram_uint32(uint32_t* word,uint32_t timeout,const vuint16_t Addr);
-	uint32_t write_fram_write_error(uint32_t Error,uint8_t ErrorLevel,uint8_t ErrorNr);
-	uint32_t read_fram_read_error_buffer(MASTER_CAN0_STRUCT_t* s) ;
-	uint32_t write_fram_clear_error_buffer(MASTER_CAN0_STRUCT_t* s) ;
-	uint32_t readMasterTempSensorFsm(MASTER_CAN0_STRUCT_t* s) ;
-
-	
-	uint32_t startup_BMS(MASTER_CAN0_STRUCT_t* s) ;
-	
-	
-	int32_t bms_SoC_init_estimator_FRAM(MASTER_SOC_ESTIMATOR_t* cell_SoC, uint16_t voltage);
-	
-	uint32_t BMS_Set_Error_check_System_voltage_level_max(MASTER_CAN0_STRUCT_t* s);
-	uint32_t BMS_Set_Error_check_Voltage_level_max(MASTER_CAN0_STRUCT_t* s) ;
-	uint32_t BMS_set_Error_check_if_stable_charge(MASTER_CAN0_STRUCT_t* s) ;
-	
-	uint32_t BMS_Set_Error_Check_derating(MASTER_CAN0_STRUCT_t* s);
-	uint32_t BMS_Clear_Error_State_Slave(MASTER_CAN0_STRUCT_t* s,BMS_ERROR_STATE_t* error_state);
-	uint32_t BMS_Clear_Error_State_check_restore_timeout(MASTER_CAN0_STRUCT_t* s) ;
-	uint32_t BMS_Clear_Error_State_Master(MASTER_CAN0_STRUCT_t* s,BMS_ERROR_STATE_t* error_state,uint8_t Error_nr,uint8_t Error_class) ;
-	uint32_t BMS_Clear_Error_init_recovery_struct(MASTER_CAN0_STRUCT_t* s);
-	uint32_t BMS_RCT_init_fsm(MASTER_CAN0_STRUCT_t* s);
-	
-	uint32_t BMS_RCT_Inverter_fsm (MASTER_CAN0_STRUCT_t* s);
-	uint32_t ErrorStackCheckifUmin1ErrorRecoveryPending(MASTER_CAN0_STRUCT_t* s);
-	uint32_t ErrorStackCheckifUmin2ErrorRecoveryPending(MASTER_CAN0_STRUCT_t* s);
-	uint32_t ErrorStackCheckifAnyErrorRecoveryPending(MASTER_CAN0_STRUCT_t* s);
-	
-	uint32_t initUIFifo(MASTER_CAN0_STRUCT_t* s);
-	uint32_t popUIFiFo(MASTER_CAN0_STRUCT_t* s) ;
-	uint32_t BMS_Set_Error_CAN1_Timeout(MASTER_CAN0_STRUCT_t* s) ;
-	
-	uint32_t BMS_Can_ID_init_recofigure_CAN_IDs(MASTER_CAN0_STRUCT_t* s) ;
-	uint32_t BMS_Can_ID_init_fsm (MASTER_CAN0_STRUCT_t* s);
-	uint32_t BMS_Can_ID_init_init_startupConfig (MASTER_CAN0_STRUCT_t* s);
-	
-	uint32_t Master_CAN1_select_comm_mode (MASTER_CAN0_STRUCT_t* s,MASTER_CAN1_INVERTER_STRUCT_t* fsmStruct) ;
-	uint32_t Master_CAN1_Fast_request_fsm (MASTER_CAN0_STRUCT_t* s,MASTER_CAN1_INVERTER_STRUCT_t* fsmStruct) ;
-	uint32_t pushInverterCurrentFIFO(MASTER_CAN0_STRUCT_t* s);
-	uint32_t BMS_Set_Error_Check_current_consitency(MASTER_CAN0_STRUCT_t* s);
-	uint32_t BMS_Set_Error_Check_voltage_inconsitency(MASTER_CAN0_STRUCT_t* s);
-	
-	uint32_t initSoCFifo(MASTER_CAN0_STRUCT_t* s); 
-	uint32_t pushSoCFiFo(MASTER_SOC_ESTIMATOR_t* est);
-
-	
-
-// ***** Global Prototypes *****************************************************
-	void 	  SwitchRelais  ( uint8_t, uint8_t );
-
-	
-
-#endif  /* ifndef*/
-
-	
-	
-// ***** End BMS_Master.h ******************************************************
-	
+//##############################################################################
+//
+// FILE:	BMS_Master.h
+//
+// TITLE:	Central Header & Main Header
+//
+//
+//##############################################################################
+//
+//==============================================================================
+// Change History:
+//==============================================================================
+// Datum:   | Name | Version:| Change / Cause:                            | No
+//------------------------------------------------------------------------------
+//          |      |         |                                            | 002
+//------------------------------------------------------------------------------
+// 07.02.14 |  VR  |   1.1   | upgrade 2 CoreWarrior 10.5 id: 130916      | 001
+//------------------------------------------------------------------------------
+// 20.04.12 |  TM  |   1.0   | New Build                                  | 000
+//==============================================================================
+//==============================================================================
+// Comment Change / Cause:
+//==============================================================================
+// Change: 003                                                           // 003
+//----------------------
+//                                                       
+//
+//==============================================================================
+// Change: 002                                                           // 002
+//----------------------
+//                                           
+//
+//==============================================================================
+// Change: 001                                                           // 001
+//----------------------
+// 
+//
+//==============================================================================
+
+#ifndef __BMS_MASTER_H__
+#define __BMS_MASTER_H__
+
+
+
+// ***** Includes **************************************************************
+#include "MPC5646C.h"
+#include "Typedefs.h"
+#include "IntcInterrupts.h"
+#include "Device.h"
+#include "FlexCAN.h"
+#include "BMS_Typedefs.h"
+#include "BMS_CANx_Tools.h"
+#include "BMS_CAN0_gen_test_data.h"
+#include "DSPI.h"
+#include "FRAM.h"
+#include "BoardPeripherals.h"
+#include "MultitaskOS.h"
+#include "RelaisLEDs.h"
+#include "BMS_Defines.h"
+#include "ADC_1.h"
+#include "UartToUsb.h"
+#include "LIN_Uart.h"
+#include "DebugUndTest.h"
+#include "TempSensorSpi.h"
+#include "utils.h"
+
+#include "BMS_SoC_estimator.h"
+
+
+
+// ***** global Variables **********************************************************
+extern 	BSD_t	 	  gBSD;
+extern 	BSE_t		  gBSE;
+extern  uint8_t	      gMaxDischargeCurrent;
+extern 	FramStatus_t  Fram_S;
+extern	uint32_t	  gEvent;
+extern  uint32_t	  gErrorEvent;
+extern  uint8_t       gCANErrorInsert;
+extern  MASTER_CAN0_STRUCT_t gDUMMY_data_struct;
+extern CAN_MAILBOX CAN_Tx0_RCT_INVERTER;
+extern CAN_MAILBOX CAN_Tx1_RCT_INVERTER; 
+extern CAN_MAILBOX CAN_Rx_RCT_INVERTER;
+
+
+
+// ***** Local Prototypes ******************************************************
+
+	
+	uint16_t init_master_CAN0_fsm(MASTER_CAN0_STRUCT_t* s,BMS_SLAVE_CONFIGURATION_t* cellConfig,BMS_UI_CONFIGURATION_t* uiConfig);
+	uint16_t Master_CAN0_fsm(MASTER_CAN0_STRUCT_t* s,uint32_t time);
+	uint16_t init_master_operation_fsm(BMS_MASTER_OPERATION_t* opFsm);
+	uint16_t Master_operation_fsm(MASTER_CAN0_STRUCT_t* canFsm,uint32_t time,BMS_MASTER_OPERATION_t* opFsm);
+	void set_slave_cell_connection_state(MASTER_CAN0_STRUCT_t* s,uint8_t slaveNr,CELL_STATE_t* cell_state);
+	void set_slave_temp_connection_state(MASTER_CAN0_STRUCT_t* s,uint8_t slaveNr,TEMP_SENSOR_STATE_t* temp_state);
+	uint8_t check_slave_data(MASTER_CAN0_STRUCT_t* s,
+			BMS_CAN0_SLAVE_t* Slave,
+			BMS_CAN0_SLAVE_t* tempSlave,
+			int8_t overTemp_charge,
+			int8_t overTemp_discharge,
+			int8_t underTemp_charge,
+			int8_t underTemp_discharge,
+			uint16_t overVoltage,uint16_t underVoltage) ;
+	void initCellConfig(BMS_SLAVE_CONFIGURATION_t* cellConfig);
+	void initUiConfig(BMS_UI_CONFIGURATION_t* uiConfig) ;
+	
+	int16_t CAN1_request_float_value(uint64_t timestamp,float* value,uint32_t requestId) ;
+	uint16_t CAN2_init( void );
+	uint16_t CAN2_update( void );
+	uint32_t set_balancer_off(MASTER_CAN0_STRUCT_t* s) ;
+	uint32_t BMS_set_Error_check_if_stable_discharge(MASTER_CAN0_STRUCT_t* s); 
+	
+	
+	uint8_t check_UI_data(BMS_CAN0_SLAVE_t* Slave, BMS_CAN0_SLAVE_t* tempSlave,BMS_CAN0_UI_t* ui,BMS_CAN0_UI_t* tempUI);
+	uint32_t calc_block_voltage(BMS_CAN0_SLAVE_t* Slave);
+	uint32_t set_block_min_max_temp(BMS_CAN0_SLAVE_t* Slave);
+	uint32_t calc_system_voltage(MASTER_CAN0_STRUCT_t* s);
+	void calc_system_SoC(MASTER_CAN0_STRUCT_t* s);
+	void refresh_inverter_tx_data(MASTER_CAN0_STRUCT_t* s);
+	uint8_t check_if_all_values_are_initialized(MASTER_CAN0_STRUCT_t* s);
+	void shuffle_lsb_msb_can1(uint8_t* value);
+	uint16_t Master_CAN1_fsm(MASTER_CAN0_STRUCT_t* s,MASTER_CAN1_STRUCT_t* can1Fsm,uint32_t time);
+	uint16_t Master_CAN1_fsm_init(MASTER_CAN1_STRUCT_t* can1Fsm);
+	uint32_t Master_CAN1_Inverter_fsm(MASTER_CAN0_STRUCT_t* s,MASTER_CAN1_INVERTER_STRUCT_t* fsmStruct) ;
+	uint32_t set_balancer(MASTER_CAN0_STRUCT_t* s) ;
+
+	
+	uint32_t Master_Balancer_fsm(MASTER_CAN0_STRUCT_t* s);
+	uint32_t calc_min_max_voltage_slave(BMS_CAN0_SLAVE_t* Slave) ;
+	uint32_t calc_min_max_voltage_system(MASTER_CAN0_STRUCT_t* s) ;
+	uint32_t balance_cell(BMS_CAN0_SLAVE_t* Slave,uint8_t cell_nr);
+	uint32_t set_system_min_max_temp(MASTER_CAN0_STRUCT_t* s);
+	uint32_t set_system_min_max_heatsink_temp(MASTER_CAN0_STRUCT_t* s);
+	
+	uint16_t CAN0_clear_all_interrupt_flags();
+	uint32_t generateCellInfoPkg(MASTER_CAN0_STRUCT_t* s, uint8_t cellIndex,BMS_CAN1_INVERTER_CELL_DATA_t* txPkg); 
+	
+
+	uint8_t get_nr_of_connected_slaves(MASTER_CAN0_STRUCT_t* s);
+
+
+	uint32_t ErrorStackPushSlaveError(MASTER_CAN0_STRUCT_t* s,uint8_t slaveNr,uint32_t ErrorCode,uint8_t CellNr,uint8_t ErrorClass); 
+	uint32_t ErrorStackPushUiError(MASTER_CAN0_STRUCT_t* s,uint32_t ErrorCode,uint8_t ErrorClass);
+	uint32_t ErrorStackPushMasterError(MASTER_CAN0_STRUCT_t* s,uint32_t ErrorCode,uint8_t ErrorClass);
+	uint32_t ErrorStackGenerateStatusPkg(uint8_t* targetBuffer,uint8_t* ErrorCode);
+	uint32_t ErrorStackCheckBufferForError(MASTER_CAN0_STRUCT_t* s,uint32_t ErrorWord,uint8_t ErrorClass) ;
+	uint32_t ErrorStackCheckForActiveErrors(MASTER_CAN0_STRUCT_t* s,uint8_t ErrorClass); 
+	uint32_t ErrorStackClearBuffer(MASTER_CAN0_STRUCT_t* s);
+	uint32_t ErrorStackCheckForActiveErrors(MASTER_CAN0_STRUCT_t* s,uint8_t ErrorClass);
+	
+	uint32_t BMS_Clear_Error_Buffer(MASTER_CAN0_STRUCT_t* s,uint8_t ErrorClass);
+	
+	
+	uint32_t BMS_Master_ES1_fsm(MASTER_CAN0_STRUCT_t* s);
+	uint32_t BMS_Master_ES2_fsm(MASTER_CAN0_STRUCT_t* s);
+	uint32_t BMS_Master_ES3_fsm(MASTER_CAN0_STRUCT_t* s);
+	
+	
+	uint32_t BMS_Set_Error_check_Voltage_level_min(MASTER_CAN0_STRUCT_t* s);
+	
+	
+	uint16_t Master_CAN0_ERROR_fsm(MASTER_CAN0_STRUCT_t* s,uint32_t time);
+
+	
+	int32_t checkIfInverterHasPower(MASTER_CAN0_STRUCT_t* s);
+	uint32_t OPModeFSM(MASTER_CAN0_STRUCT_t* s);
+	uint32_t RunningModeFSM(MASTER_CAN0_STRUCT_t* s);
+	
+	uint32_t write_fram_byte(uint8_t byte,uint32_t timeout,const vuint16_t Addr);
+	uint32_t write_fram_word(uint16_t word,uint32_t timeout,const vuint16_t Addr);
+	uint32_t write_fram_float(float float_value,uint32_t timeout,const vuint16_t Addr); 
+	uint32_t read_fram_byte(uint8_t* word,uint32_t timeout,const vuint16_t Addr);
+	uint32_t read_fram_word(uint16_t* word,uint32_t timeout,const vuint16_t Addr);
+	uint32_t read_fram_float(float* word,uint32_t timeout,const vuint16_t Addr);
+	uint32_t write_fram_set_SoC(float SoC) ;
+	uint32_t read_fram_get_startup_state(MASTER_CAN0_STRUCT_t* s);
+	float 	read_fram_get_SoC() ;
+	uint32_t write_fram_set_startup_state(MASTER_CAN0_STRUCT_t* s) ;
+	uint32_t write_fram_clear_startup_state();
+	uint32_t write_fram_uint32(uint32_t word,uint32_t timeout,const vuint16_t Addr);
+	uint32_t read_fram_uint32(uint32_t* word,uint32_t timeout,const vuint16_t Addr);
+	uint32_t write_fram_write_error(uint32_t Error,uint8_t ErrorLevel,uint8_t ErrorNr);
+	uint32_t read_fram_read_error_buffer(MASTER_CAN0_STRUCT_t* s) ;
+	uint32_t write_fram_clear_error_buffer(MASTER_CAN0_STRUCT_t* s) ;
+	uint32_t readMasterTempSensorFsm(MASTER_CAN0_STRUCT_t* s) ;
+
+	
+	uint32_t startup_BMS(MASTER_CAN0_STRUCT_t* s) ;
+	
+	
+	int32_t bms_SoC_init_estimator_FRAM(MASTER_SOC_ESTIMATOR_t* cell_SoC, uint16_t voltage);
+	
+	uint32_t BMS_Set_Error_check_System_voltage_level_max(MASTER_CAN0_STRUCT_t* s);
+	uint32_t BMS_Set_Error_check_Voltage_level_max(MASTER_CAN0_STRUCT_t* s) ;
+	uint32_t BMS_set_Error_check_if_stable_charge(MASTER_CAN0_STRUCT_t* s) ;
+	
+	uint32_t BMS_Set_Error_Check_derating(MASTER_CAN0_STRUCT_t* s);
+	uint32_t BMS_Clear_Error_State_Slave(MASTER_CAN0_STRUCT_t* s,BMS_ERROR_STATE_t* error_state);
+	uint32_t BMS_Clear_Error_State_check_restore_timeout(MASTER_CAN0_STRUCT_t* s) ;
+	uint32_t BMS_Clear_Error_State_Master(MASTER_CAN0_STRUCT_t* s,BMS_ERROR_STATE_t* error_state,uint8_t Error_nr,uint8_t Error_class) ;
+	uint32_t BMS_Clear_Error_init_recovery_struct(MASTER_CAN0_STRUCT_t* s);
+	uint32_t BMS_RCT_init_fsm(MASTER_CAN0_STRUCT_t* s);
+	
+	uint32_t BMS_RCT_Inverter_fsm (MASTER_CAN0_STRUCT_t* s);
+	uint32_t ErrorStackCheckifUmin1ErrorRecoveryPending(MASTER_CAN0_STRUCT_t* s);
+	uint32_t ErrorStackCheckifUmin2ErrorRecoveryPending(MASTER_CAN0_STRUCT_t* s);
+	uint32_t ErrorStackCheckifAnyErrorRecoveryPending(MASTER_CAN0_STRUCT_t* s);
+	
+	uint32_t initUIFifo(MASTER_CAN0_STRUCT_t* s);
+	uint32_t popUIFiFo(MASTER_CAN0_STRUCT_t* s) ;
+	uint32_t BMS_Set_Error_CAN1_Timeout(MASTER_CAN0_STRUCT_t* s) ;
+	
+	uint32_t BMS_Can_ID_init_recofigure_CAN_IDs(MASTER_CAN0_STRUCT_t* s) ;
+	uint32_t BMS_Can_ID_init_fsm (MASTER_CAN0_STRUCT_t* s);
+	uint32_t BMS_Can_ID_init_init_startupConfig (MASTER_CAN0_STRUCT_t* s);
+	
+	uint32_t Master_CAN1_select_comm_mode (MASTER_CAN0_STRUCT_t* s,MASTER_CAN1_INVERTER_STRUCT_t* fsmStruct) ;
+	uint32_t Master_CAN1_Fast_request_fsm (MASTER_CAN0_STRUCT_t* s,MASTER_CAN1_INVERTER_STRUCT_t* fsmStruct) ;
+	uint32_t pushInverterCurrentFIFO(MASTER_CAN0_STRUCT_t* s);
+	uint32_t BMS_Set_Error_Check_current_consitency(MASTER_CAN0_STRUCT_t* s);
+	uint32_t BMS_Set_Error_Check_voltage_inconsitency(MASTER_CAN0_STRUCT_t* s);
+	
+	uint32_t initSoCFifo(MASTER_CAN0_STRUCT_t* s); 
+	uint32_t pushSoCFiFo(MASTER_SOC_ESTIMATOR_t* est);
+
+	
+
+// ***** Global Prototypes *****************************************************
+	void 	  SwitchRelais  ( uint8_t, uint8_t );
+
+	
+
+#endif  /* ifndef*/
+
+	
+	
+// ***** End BMS_Master.h ******************************************************
+	

+ 102 - 102
BMS Master/Project_Headers/FlexCAN.h

@@ -1,102 +1,102 @@
-//==============================================================================
-// Purpose:     allgemeines CAN Interface für FlexCAN von MPC5646
-//
-// Created on:  20.04.2012 by IPE
-//
-// History
-//		20.04.2012 neu, T.Maurer
-//==============================================================================
-
-
-
-#ifndef __FLEXCAN_H__
-#define __FLEXCAN_H__
-
-#ifdef __cplusplus
-    extern "C" {
-#endif
-
-
-    
-
-// Constants
-#define CAN_DATA_ARR_LEN	8	//Max Anzahl der Datenbytes der CAN-Schittstelle
-
-
-
-//==============================================================================
-//== API ==
-
-
-//Return-Werte der Funktionen
-#define CAN_OK		0
-#define CAN_ERROR	-1
-
-
-
-// Globale Datentypen
-
-//CAN_CONFIG
-//Konfiguration des CAN-Moduls
-typedef struct {
-	volatile struct FLEXCAN_tag *CAN_Modul;											//Adresse des FlexCAN-Moduls
-	enum {CAN0_PortB0_1=0, CAN1_PortC10_11, CAN2_PortE8_9, CAN3_PortF8_9 } Port;	//Auswahl der Rx/Tx-Port-Pins für ein CAN-Modul
-	enum {TxPushPull=0,Tx_OpenDrain} TxPortType;									//Tx Pin wird als Push-Pull (CMOS) oder Open-Drain konfiguriert
-	enum {RxMask_Global=0,RxMask_Individual} RxMaskType;							//Auswahl zwischen globaler RxMaske oder individueller RxMaske
-	uint32_t GlobalRxMask;															//globale RxMaske des Moduls; nur von Bedeutung wenn in RxMaskType "RxMask_Global" ausgewählt
-	enum {CANBaud_1000kHz_OSC_40MHz=0, CANBaud_500kHz_OSC_40MHz, CANBaud_250kHz_OSC_40MHz, CANBaud_125kHz_OSC_40MHz} BaudConfig;
-} CAN_CONFIG;
-
-
-//CAN_MAILBOX
-//Konfiguration und ID der MessageBox
-typedef struct {
-	CAN_CONFIG *p_CAN_Config;
-	uint8_t MBNumber;		//Message Buffer Number, 0..63
-	enum {MB_Tx,MB_Rx} Direction;
-	uint8_t RemoteEn;		//Remote Frame Transmission Ein, aktiviert den RTR-Modus der MB
-	uint8_t DataBytes;		//Anzahl der Datenbytes, max=8
-	uint8_t Interrupt;		//Empfang oder Senden generiert einen Interrupt
-	uint32_t AcceptMask;	//individuelle RxMaske der MsgBox; ohne Bedeutung,wenn in CAN_CONFIG RxMask_Global oder wenn es eine Tx-MB ist
-	enum {SHORT_ID, LONG_ID} IDE;
-	uint32_t ID;			//ID : Rx -> ID oder maskierte ID zur CAN-Nachrichten-Filterung. Nur die in AcceptMask/GlobalRxMask selektierten Bits werden beachtet
-} CAN_MAILBOX;
-
-
-
-// Global functions
-
-extern int8_t CAN_Init(CAN_CONFIG *config);
-//Initialisierung der Kontrollregister des CAN-Moduls
-//return: CAN_OK oder CAN_ERROR
-
-extern int8_t CAN_Init_Mailbox(CAN_MAILBOX *mbox);
-//Initialisierung der Message-Buffer und ihrer Einstellungen
-//return: CAN_OK oder CAN_ERROR
-
-extern int8_t CAN_Write(CAN_MAILBOX *mbox, uint8_t *data);
-//schreiben auf einen Tx-MessageBuffer
-//return: CAN_OK oder CAN_ERROR
-
-extern int8_t CAN_Write_dataset(CAN_MAILBOX *mbox, uint8_t* data,uint32_t timestamp);
-
-extern int8_t CAN_Read(CAN_MAILBOX *mbox, uint8_t *data);
-//lesen von einem Message-Buffer
-//return: CAN_OK oder CAN_ERROR
-
-extern int8_t CAN_Abort(CAN_MAILBOX *mbox);
-//Abbruch eines Sende-Prozesses
-//Gibt CAN_ERROR zurück, wenn mbox eine Rx-MB ist
-
-extern uint8_t CAN_Get_error_Register(CAN_CONFIG *config,uint32_t* can_esr);
-
-extern int8_t CAN_Check_error_Register(CAN_CONFIG *config) ;
-
-//==============================================================================
-
-
-#ifdef __cplusplus
-    }
-#endif
-
-#endif  /* ifndef*/
+//==============================================================================
+// Purpose:     allgemeines CAN Interface für FlexCAN von MPC5646
+//
+// Created on:  20.04.2012 by IPE
+//
+// History
+//		20.04.2012 neu, T.Maurer
+//==============================================================================
+
+
+
+#ifndef __FLEXCAN_H__
+#define __FLEXCAN_H__
+
+#ifdef __cplusplus
+    extern "C" {
+#endif
+
+
+    
+
+// Constants
+#define CAN_DATA_ARR_LEN	8	//Max Anzahl der Datenbytes der CAN-Schittstelle
+
+
+
+//==============================================================================
+//== API ==
+
+
+//Return-Werte der Funktionen
+#define CAN_OK		0
+#define CAN_ERROR	-1
+
+
+
+// Globale Datentypen
+
+//CAN_CONFIG
+//Konfiguration des CAN-Moduls
+typedef struct {
+	volatile struct FLEXCAN_tag *CAN_Modul;											//Adresse des FlexCAN-Moduls
+	enum {CAN0_PortB0_1=0, CAN1_PortC10_11, CAN2_PortE8_9, CAN3_PortF8_9 } Port;	//Auswahl der Rx/Tx-Port-Pins für ein CAN-Modul
+	enum {TxPushPull=0,Tx_OpenDrain} TxPortType;									//Tx Pin wird als Push-Pull (CMOS) oder Open-Drain konfiguriert
+	enum {RxMask_Global=0,RxMask_Individual} RxMaskType;							//Auswahl zwischen globaler RxMaske oder individueller RxMaske
+	uint32_t GlobalRxMask;															//globale RxMaske des Moduls; nur von Bedeutung wenn in RxMaskType "RxMask_Global" ausgewählt
+	enum {CANBaud_1000kHz_OSC_40MHz=0, CANBaud_500kHz_OSC_40MHz, CANBaud_250kHz_OSC_40MHz, CANBaud_125kHz_OSC_40MHz} BaudConfig;
+} CAN_CONFIG;
+
+
+//CAN_MAILBOX
+//Konfiguration und ID der MessageBox
+typedef struct {
+	CAN_CONFIG *p_CAN_Config;
+	uint8_t MBNumber;		//Message Buffer Number, 0..63
+	enum {MB_Tx,MB_Rx} Direction;
+	uint8_t RemoteEn;		//Remote Frame Transmission Ein, aktiviert den RTR-Modus der MB
+	uint8_t DataBytes;		//Anzahl der Datenbytes, max=8
+	uint8_t Interrupt;		//Empfang oder Senden generiert einen Interrupt
+	uint32_t AcceptMask;	//individuelle RxMaske der MsgBox; ohne Bedeutung,wenn in CAN_CONFIG RxMask_Global oder wenn es eine Tx-MB ist
+	enum {SHORT_ID, LONG_ID} IDE;
+	uint32_t ID;			//ID : Rx -> ID oder maskierte ID zur CAN-Nachrichten-Filterung. Nur die in AcceptMask/GlobalRxMask selektierten Bits werden beachtet
+} CAN_MAILBOX;
+
+
+
+// Global functions
+
+extern int8_t CAN_Init(CAN_CONFIG *config);
+//Initialisierung der Kontrollregister des CAN-Moduls
+//return: CAN_OK oder CAN_ERROR
+
+extern int8_t CAN_Init_Mailbox(CAN_MAILBOX *mbox);
+//Initialisierung der Message-Buffer und ihrer Einstellungen
+//return: CAN_OK oder CAN_ERROR
+
+extern int8_t CAN_Write(CAN_MAILBOX *mbox, uint8_t *data);
+//schreiben auf einen Tx-MessageBuffer
+//return: CAN_OK oder CAN_ERROR
+
+extern int8_t CAN_Write_dataset(CAN_MAILBOX *mbox, uint8_t* data,uint64_t timestamp);
+
+extern int8_t CAN_Read(CAN_MAILBOX *mbox, uint8_t *data);
+//lesen von einem Message-Buffer
+//return: CAN_OK oder CAN_ERROR
+
+extern int8_t CAN_Abort(CAN_MAILBOX *mbox);
+//Abbruch eines Sende-Prozesses
+//Gibt CAN_ERROR zurück, wenn mbox eine Rx-MB ist
+
+extern uint8_t CAN_Get_error_Register(CAN_CONFIG *config,uint32_t* can_esr);
+
+extern int8_t CAN_Check_error_Register(CAN_CONFIG *config) ;
+
+//==============================================================================
+
+
+#ifdef __cplusplus
+    }
+#endif
+
+#endif  /* ifndef*/

+ 76 - 76
BMS Master/Project_Headers/MultitaskOS.h

@@ -1,76 +1,76 @@
-//##############################################################################
-//
-// FILE:	MultitaskOS.h
-//
-// TITLE:	Real Time 1 ms Generator
-//
-//
-//##############################################################################
-//
-//==============================================================================
-// Change History:
-//==============================================================================
-// Datum:   | Name | Version:| Change / Cause:                            | No
-//------------------------------------------------------------------------------
-//          |      |         |                                            | 002
-//------------------------------------------------------------------------------
-// 05.07.13 |  VR  |   1.1   | Change for ReilingOS                       | 001
-//------------------------------------------------------------------------------
-// 02.05.12 |  TM  |   1.0   | New Build                                  | 000
-//==============================================================================
-//==============================================================================
-// Comment Change / Cause:
-//==============================================================================
-// Change: 003                                                           // 003
-//----------------------
-//                                                       
-//
-//==============================================================================
-// Change: 002                                                           // 002
-//----------------------
-//                                           
-//
-//==============================================================================
-// Change: 001                                                           // 001
-//----------------------
-// 
-//
-//==============================================================================
-
-#ifndef __MULTITASKOS_H__
-#define __MULTITASKOS_H__
-
-
-
-#ifdef __cplusplus
-    extern "C" {
-#endif
-
-
-
-// ***** Defines ***************************************************************
-    #define SYSCLK_KHZ 120000
-
-
-    
-// ***** External Variables ****************************************************    
-extern	uint32_t	Global_1msCounter;
-extern	uint32_t	Global_1msCounterCopy;
-extern	uint32_t	Global_1msCounterDelta;
-extern  uint32_t    gISO_R;
-
-
-
-// ***** Function Prototypes ***************************************************
-void	MultitaskOS_init	(void);
-void	ISR_Timer_OS		(void);
-
-
-
-#ifdef __cplusplus
-    }
-#endif
-
-    
-    
-#endif  /* ifndef*/
+//##############################################################################
+//
+// FILE:	MultitaskOS.h
+//
+// TITLE:	Real Time 1 ms Generator
+//
+//
+//##############################################################################
+//
+//==============================================================================
+// Change History:
+//==============================================================================
+// Datum:   | Name | Version:| Change / Cause:                            | No
+//------------------------------------------------------------------------------
+//          |      |         |                                            | 002
+//------------------------------------------------------------------------------
+// 05.07.13 |  VR  |   1.1   | Change for ReilingOS                       | 001
+//------------------------------------------------------------------------------
+// 02.05.12 |  TM  |   1.0   | New Build                                  | 000
+//==============================================================================
+//==============================================================================
+// Comment Change / Cause:
+//==============================================================================
+// Change: 003                                                           // 003
+//----------------------
+//                                                       
+//
+//==============================================================================
+// Change: 002                                                           // 002
+//----------------------
+//                                           
+//
+//==============================================================================
+// Change: 001                                                           // 001
+//----------------------
+// 
+//
+//==============================================================================
+
+#ifndef __MULTITASKOS_H__
+#define __MULTITASKOS_H__
+
+
+
+#ifdef __cplusplus
+    extern "C" {
+#endif
+
+
+
+// ***** Defines ***************************************************************
+    #define SYSCLK_KHZ 120000
+
+
+    
+// ***** External Variables ****************************************************    
+extern	uint64_t	Global_1msCounter;
+extern	uint32_t	Global_1msCounterCopy;
+extern	uint32_t	Global_1msCounterDelta;
+extern  uint32_t    gISO_R;
+
+
+
+// ***** Function Prototypes ***************************************************
+void	MultitaskOS_init	(void);
+void	ISR_Timer_OS		(void);
+
+
+
+#ifdef __cplusplus
+    }
+#endif
+
+    
+    
+#endif  /* ifndef*/

+ 127 - 122
BMS Master/Project_Headers/typedefs.h

@@ -1,122 +1,127 @@
-/**************************************************************************
- * FILE NAME: $RCSfile: typedefs.h,v $       COPYRIGHT (c) Freescale 2005 *
- * DESCRIPTION:                                     All Rights Reserved   *
- * This file defines all of the data types for the Motorola header file.  *
- *========================================================================*
- * ORIGINAL AUTHOR: Jeff Loeliger (r12110)                                *
- * $Log: typedefs.h,v $
- * Revision 1.1  2010/07/21 13:28:05  dmihail1
- * Add to DataBase: 'runtime' folder
- * See: MTWX40737, MTWX40738, MTWX40743, MTWX42016
- *
- * Revision 1.7  2007/05/02 22:46:00  dfreeland
- * Use latest web version
- *
- * Revision 1.4  2006/03/27 09:59:34  r47354
- * change __GHS__ to __ghs__. As per bug 13213
- *
- * Revision 1.3  2005/02/22 13:09:38  r47354
- * Fix copyright date.
- *
- * Revision 1.2  2004/11/17 12:43:12  r12110
- * -Removed #ifdef DEBUG from around initial comment block.
- *
- * Revision 1.1  2004/11/17 12:38:48  r12110
- * -Initial version checked into CVS.
- * -Updated copyright from Motorola to Freescale.
- *
- *........................................................................*
- * 0.1   J. Loeliger  17/Feb/03    Initial version of file.               *
- * 0.2   J. Loeliger  06/Mar/03    Added DCC support.                     *
- * 0.3   J. Loeliger  07/May/03    Change to fully use ISO data types.    *
- * 0.4   J. Loeliger  17/Jun/03    Change name to motint.h and merge      *
- *                                  MPC5500 and MAC7100 files.            *
- * 0.5   J. Loeliger  04/Nov/03    Changed name to typedefs.h.            *
- * 0.6   J. Loeliger  09/May/04    Changed to support GHS and GCC.        *
- **************************************************************************/
-
-#ifndef _TYPEDEFS_H_
-#define _TYPEDEFS_H_
-
-#ifdef __MWERKS__    //Metrowerk CodeWarrior
-    #include <stdint.h>
-
-    // Standard typedefs used by header files, based on ISO C standard
-    typedef volatile int8_t vint8_t;
-    typedef volatile uint8_t vuint8_t;
-
-    typedef volatile int16_t vint16_t;
-    typedef volatile uint16_t vuint16_t;
-
-    typedef volatile int32_t vint32_t;
-    typedef volatile uint32_t vuint32_t;
-
-#else
-#ifdef __ghs__    //GreenHills
-    #include <stdint.h>
-
-    // Standard typedefs used by header files, based on ISO C standard
-    typedef volatile int8_t vint8_t;
-    typedef volatile uint8_t vuint8_t;
-
-    typedef volatile int16_t vint16_t;
-    typedef volatile uint16_t vuint16_t;
-
-    typedef volatile int32_t vint32_t;
-    typedef volatile uint32_t vuint32_t;
-
-#else
-
-    // This is needed for compilers that don't have a stdint.h file
-
-    typedef signed char int8_t;
-    typedef unsigned char uint8_t;
-    typedef volatile signed char vint8_t;
-    typedef volatile unsigned char vuint8_t;
-
-    typedef signed short int16_t;
-    typedef unsigned short uint16_t;
-    typedef volatile signed short vint16_t;
-    typedef volatile unsigned short vuint16_t;
-
-    typedef signed int int32_t;
-    typedef unsigned int uint32_t;
-    typedef volatile signed int vint32_t;
-    typedef volatile unsigned int vuint32_t;
-
-#endif
-#endif
-#endif
-
-/*********************************************************************
- *
- * Copyright:
- *	Freescale Semiconductor, INC. All Rights Reserved.
- *  You are hereby granted a copyright license to use, modify, and
- *  distribute the SOFTWARE so long as this entire notice is
- *  retained without alteration in any modified and/or redistributed
- *  versions, and that such modified versions are clearly identified
- *  as such. No licenses are granted by implication, estoppel or
- *  otherwise under any patents or trademarks of Freescale
- *  Semiconductor, Inc. This software is provided on an "AS IS"
- *  basis and without warranty.
- *
- *  To the maximum extent permitted by applicable law, Freescale
- *  Semiconductor DISCLAIMS ALL WARRANTIES WHETHER EXPRESS OR IMPLIED,
- *  INCLUDING IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A
- *  PARTICULAR PURPOSE AND ANY WARRANTY AGAINST INFRINGEMENT WITH
- *  REGARD TO THE SOFTWARE (INCLUDING ANY MODIFIED VERSIONS THEREOF)
- *  AND ANY ACCOMPANYING WRITTEN MATERIALS.
- *
- *  To the maximum extent permitted by applicable law, IN NO EVENT
- *  SHALL Freescale Semiconductor BE LIABLE FOR ANY DAMAGES WHATSOEVER
- *  (INCLUDING WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS,
- *  BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR OTHER
- *  PECUNIARY LOSS) ARISING OF THE USE OR INABILITY TO USE THE SOFTWARE.
- *
- *  Freescale Semiconductor assumes no responsibility for the
- *  maintenance and support of this software
- *
- ********************************************************************/
-
-
+/**************************************************************************
+ * FILE NAME: $RCSfile: typedefs.h,v $       COPYRIGHT (c) Freescale 2005 *
+ * DESCRIPTION:                                     All Rights Reserved   *
+ * This file defines all of the data types for the Motorola header file.  *
+ *========================================================================*
+ * ORIGINAL AUTHOR: Jeff Loeliger (r12110)                                *
+ * $Log: typedefs.h,v $
+ * Revision 1.1  2010/07/21 13:28:05  dmihail1
+ * Add to DataBase: 'runtime' folder
+ * See: MTWX40737, MTWX40738, MTWX40743, MTWX42016
+ *
+ * Revision 1.7  2007/05/02 22:46:00  dfreeland
+ * Use latest web version
+ *
+ * Revision 1.4  2006/03/27 09:59:34  r47354
+ * change __GHS__ to __ghs__. As per bug 13213
+ *
+ * Revision 1.3  2005/02/22 13:09:38  r47354
+ * Fix copyright date.
+ *
+ * Revision 1.2  2004/11/17 12:43:12  r12110
+ * -Removed #ifdef DEBUG from around initial comment block.
+ *
+ * Revision 1.1  2004/11/17 12:38:48  r12110
+ * -Initial version checked into CVS.
+ * -Updated copyright from Motorola to Freescale.
+ *
+ *........................................................................*
+ * 0.1   J. Loeliger  17/Feb/03    Initial version of file.               *
+ * 0.2   J. Loeliger  06/Mar/03    Added DCC support.                     *
+ * 0.3   J. Loeliger  07/May/03    Change to fully use ISO data types.    *
+ * 0.4   J. Loeliger  17/Jun/03    Change name to motint.h and merge      *
+ *                                  MPC5500 and MAC7100 files.            *
+ * 0.5   J. Loeliger  04/Nov/03    Changed name to typedefs.h.            *
+ * 0.6   J. Loeliger  09/May/04    Changed to support GHS and GCC.        *
+ **************************************************************************/
+
+#ifndef _TYPEDEFS_H_
+#define _TYPEDEFS_H_
+
+#ifdef __MWERKS__    //Metrowerk CodeWarrior
+    #include <stdint.h>
+
+    // Standard typedefs used by header files, based on ISO C standard
+    typedef volatile int8_t vint8_t;
+    typedef volatile uint8_t vuint8_t;
+
+    typedef volatile int16_t vint16_t;
+    typedef volatile uint16_t vuint16_t;
+
+    typedef volatile int32_t vint32_t;
+    typedef volatile uint32_t vuint32_t;
+
+#else
+#ifdef __ghs__    //GreenHills
+    #include <stdint.h>
+
+    // Standard typedefs used by header files, based on ISO C standard
+    typedef volatile int8_t vint8_t;
+    typedef volatile uint8_t vuint8_t;
+
+    typedef volatile int16_t vint16_t;
+    typedef volatile uint16_t vuint16_t;
+
+    typedef volatile int32_t vint32_t;
+    typedef volatile uint32_t vuint32_t;
+
+#else
+
+    // This is needed for compilers that don't have a stdint.h file
+
+    typedef signed char int8_t;
+    typedef unsigned char uint8_t;
+    typedef volatile signed char vint8_t;
+    typedef volatile unsigned char vuint8_t;
+
+    typedef signed short int16_t;
+    typedef unsigned short uint16_t;
+    typedef volatile signed short vint16_t;
+    typedef volatile unsigned short vuint16_t;
+
+    typedef signed int int32_t;
+    typedef unsigned int uint32_t;
+    typedef volatile signed int vint32_t;
+    typedef volatile unsigned int vuint32_t;
+    
+    typedef signed long long int64_t;
+    typedef unsigned long long uint64_t;
+    typedef volatile signed long long vint64_t;
+    typedef volatile unsigned long long vuint64_t;
+        
+#endif
+#endif
+#endif
+
+/*********************************************************************
+ *
+ * Copyright:
+ *	Freescale Semiconductor, INC. All Rights Reserved.
+ *  You are hereby granted a copyright license to use, modify, and
+ *  distribute the SOFTWARE so long as this entire notice is
+ *  retained without alteration in any modified and/or redistributed
+ *  versions, and that such modified versions are clearly identified
+ *  as such. No licenses are granted by implication, estoppel or
+ *  otherwise under any patents or trademarks of Freescale
+ *  Semiconductor, Inc. This software is provided on an "AS IS"
+ *  basis and without warranty.
+ *
+ *  To the maximum extent permitted by applicable law, Freescale
+ *  Semiconductor DISCLAIMS ALL WARRANTIES WHETHER EXPRESS OR IMPLIED,
+ *  INCLUDING IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A
+ *  PARTICULAR PURPOSE AND ANY WARRANTY AGAINST INFRINGEMENT WITH
+ *  REGARD TO THE SOFTWARE (INCLUDING ANY MODIFIED VERSIONS THEREOF)
+ *  AND ANY ACCOMPANYING WRITTEN MATERIALS.
+ *
+ *  To the maximum extent permitted by applicable law, IN NO EVENT
+ *  SHALL Freescale Semiconductor BE LIABLE FOR ANY DAMAGES WHATSOEVER
+ *  (INCLUDING WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS,
+ *  BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR OTHER
+ *  PECUNIARY LOSS) ARISING OF THE USE OR INABILITY TO USE THE SOFTWARE.
+ *
+ *  Freescale Semiconductor assumes no responsibility for the
+ *  maintenance and support of this software
+ *
+ ********************************************************************/
+
+

+ 92 - 0
BMS Master/Sources/ADC_1.c

@@ -0,0 +1,92 @@
+// ----------------------------------------------------------------------------
+// ADC_1.c  
+// ----------------------------------------------------------------------------
+// Beschreibung:	ADC_1 - Interner 12 Bit ADC
+//
+// Revision:		06. Januar 2017, neu	Reiling, IPE
+//					
+// ----------------------------------------------------------------------------
+
+#include "BMS_Master.h"
+
+
+int8_t ADC_1_init(void)
+{
+	int8_t ret = 0;
+    
+	SIU.PCR[20].R = 0x2000;       /* Initialize PB[4] as ADC1 CH0 */
+	SIU.PCR[21].R = 0x2000;       /* Initialize PB[5] as ADC1 CH1 */
+	SIU.PCR[22].R = 0x2000;       /* Initialize PB[6] as ADC1 CH2 */
+	SIU.PCR[23].R = 0x2000;       /* Initialize PB[7] as ADC1 CH3 */
+	SIU.PCR[48].R = 0x2000;       /* Initialize PD[0] as ADC1 CH4 */
+	SIU.PCR[49].R = 0x2000;       /* Initialize PD[1] as ADC1 CH5 */
+	SIU.PCR[50].R = 0x2000;       /* Initialize PD[2] as ADC1 CH6 */
+	SIU.PCR[51].R = 0x2000;       /* Initialize PD[3] as ADC1 CH7 */
+	SIU.PCR[52].R = 0x2000;       /* Initialize PD[4] as ADC1 CH8 */
+	SIU.PCR[53].R = 0x2000;       /* Initialize PD[5] as ADC1 CH9 */
+	SIU.PCR[54].R = 0x2000;       /* Initialize PD[6] as ADC1 CH10 */
+	SIU.PCR[55].R = 0x2000;       /* Initialize PD[7] as ADC1 CH11 */
+	ADC_1.MCR.R   = 0x20000000;   /* Initialize ADC1 for scan mode */
+	ADC_1.CTR0.R  = 0x0000001F;   /* Conversion times: INPSAMP=31, INPCMP=4, INPLATCH=0, SHIFT=No  */
+	
+	return ret;
+}
+
+
+
+int8_t ADC_1_run(uint8_t Channel, uint16_t* Result)
+{
+	uint16_t  	i, j;
+	uint32_t    Dummy=0;
+	int8_t   	ret=NoError;
+	    
+	if( Channel > 11)                          		/* only AIN0 to AIN11 allowed */
+		ret = ADCwrongCH;
+	else {
+		ADC_1.NCMR0.R = 0x001 << Channel;   		/* Select ADC1 Channel input for conversion */
+		
+		ADC_1.MCR.B.NSTART = 1;               		/* Trigger normal conversions for ADC1 */
+		for(i=0; i<64; i++){          	            /* 64 times Over-Sampling Loop */
+			for(j=0;j<32; j++){                     /* TimeOut Loop */
+				if(j>30) return ADCtimeout;       	/* if TimeOut occurred end funktion */
+				if(ADC_1.ISR.B.ECH == 1) break;     /* if 1st chain to complete then end TimeOut Loop */
+			}
+			Dummy += ADC_1.CDR[Channel].B.CDATA;	/* Read ADC1 conversion result data */
+		}
+		ADC_1.MCR.B.NSTART = 0;               		/* Stop ADC1 */
+		*Result = (uint16_t)(Dummy >> 2);           /* Result: 16 Bit */
+	}
+	return ret;
+}	
+
+
+
+int8_t CheckSupplyVoltages(uint16_t* U12, uint16_t* U33)
+{
+	uint32_t U12work=0, U33work=0;
+	uint16_t i, j;
+	int8_t   ret=NoError;
+	
+	ADC_1.NCMR0.R = 0x003;                  		/* Select ADC1 Channel input for conversion */
+	
+	ADC_1.MCR.B.NSTART = 1;               			/* Trigger normal conversions for ADC1 */
+	for(i=0; i<128; i++){          	            	/* 64 times Over-Sampling Loop */
+		for(j=0;j<32; j++){                     	/* TimeOut Loop */
+			if(j>30) return ADCtimeout;          	/* if TimeOut occurred end funktion */
+			if(ADC_1.ISR.B.ECH == 1) break;       	/* if 1st chain to complete then end TimeOut Loop */
+		}			
+		U12work += ADC_1.CDR[0].B.CDATA;			/* Read ADC1 conversion result data */
+		U33work += ADC_1.CDR[1].B.CDATA;			/* Read ADC1 conversion result data */
+	}
+	ADC_1.MCR.B.NSTART = 0;               			/* Stop ADC1 */
+	
+	*U12 = (uint16_t)((1977 * U12work) >> 16);      /* U12=12000mV, Q=12Bit, R1=91k, R2=24k  */
+	*U33 = (uint16_t)(( 551 * U33work) >> 16);      /* U33=3300mV,  Q=12Bit, R1=18k, R2=56k  */	
+	
+	if(*U12 < U12under)	ret = Under12V;
+	if(*U12 > U12over)	ret = Over12V;
+	if(*U33 < U33under)	ret = Under3_3V;
+	if(*U33 > U33over)	ret = Over3_3V;
+    
+	return ret;
+}

+ 163 - 163
BMS Master/Sources/BMS_CAN1_Tools.c

@@ -1,163 +1,163 @@
-///##############################################################################
-//
-// FILE:	BMS_CAN1_Tools.c
-//
-// TITLE:	CAN 1 
-//			CAN_Tx_NLG5_CTL_618
-//			check_and_save_NLG5_ST
-//
-//
-//##############################################################################
-//
-//==============================================================================
-// Change History:
-//==============================================================================
-// Datum:   | Name | Version:| Change / Cause:                            | No
-//------------------------------------------------------------------------------
-//          |      |         |                                            | 002
-//------------------------------------------------------------------------------
-//          |      |         |                                            | 001
-//------------------------------------------------------------------------------
-// 31.07.13 |  VR  |   1.0   | New Build                                  | 000
-//==============================================================================
-//==============================================================================
-// Comment Change / Cause:
-//==============================================================================
-// Change: 003                                                           // 003
-//----------------------
-//                                                       
-//
-//==============================================================================
-// Change: 002                                                           // 002
-//----------------------
-//                                           
-//
-//==============================================================================
-// Change: 001                                                           // 001
-//----------------------
-// 
-//
-//==============================================================================
-
-#include "BMS_Master.h"
-
-
-//quick and dirty loesung
-//extern CAN_MAILBOX CAN_Tx0_RCT_INVERTER;
-//extern CAN_MAILBOX CAN_Tx1_RCT_INVERTER; 
-//extern CAN_MAILBOX CAN_Rx_RCT_INVERTER;
-
-// ***** CAN_Tx_NLG5_CTL ********************************************************
-uint16_t CAN_Tx_NLG5_CTL_618( void )
-{
-	uint8_t  	Data[7];
-	uint16_t   	ReturnResult = CAN_OK;
-
-
-	Data[0]  = (uint8_t)(0x80);										// CAN enable
-	Data[1]  = (uint8_t)((NLG5_MAINS_CURRENT >> 8) & 0xFF);			// Mains Current Maximum
-	Data[2]  = (uint8_t)(NLG5_MAINS_CURRENT & 0xFF);				
-	Data[3]  = (uint8_t)((NLG5_OUTPUT_VOLTAGE >> 8) & 0xFF);			// Output Voltage Command
-	Data[4]  = (uint8_t)(NLG5_OUTPUT_VOLTAGE & 0xFF);				
-	Data[5]  = (uint8_t)((NLG5_OUTPUT_CURRENT >> 8) & 0xFF);			// Output Current Command
-	Data[6]  = (uint8_t)(NLG5_OUTPUT_CURRENT & 0xFF);				
-		
-	//ReturnResult = CAN_Write( &CAN_TxMB_NLG5_CTL_618, &Data[0] );
-
-	return ReturnResult;
-}
-
-int16_t CAN1_tx_Data_to_Inverter(uint32_t timestamp,BMS_CAN1_INVERTER_TX* data) {
-	int16_t   	ReturnResult = CAN_OK;
-	//uint8_t		test[8]= {0,0,0,0,0,0,0,0};
-	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.maxBatteryChargeCurrent),Global_1msCounter);
-	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.maxBatteryChargeVoltage),Global_1msCounter);
-	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.maxBatteryDischargeCurrent),Global_1msCounter);
-	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.minBatteryDischargeVoltage),Global_1msCounter);
-	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryCurrent),Global_1msCounter);
-	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryVoltage),Global_1msCounter);
-	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batterySOCtarget),Global_1msCounter);
-	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batterySOC),Global_1msCounter);
-	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryCapacity),Global_1msCounter);
-	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryTemperature),Global_1msCounter);
-	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batterySOH),Global_1msCounter);
-	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryStatus),Global_1msCounter);
-	//ReturnResult =CAN_Write(&CAN_Tx0_RCT_INVERTER,test);
-	return ReturnResult;
-}
-
-uint32_t delay_CAN1_ms(uint32_t timestamp,uint32_t delay_ms) {
-	while(timestamp + delay_ms >Global_1msCounter) {
-		// do nothing
-	}
-	return Global_1msCounter;
-}
-
-int16_t CAN1_request_float_value(uint32_t timestamp,float* value,uint32_t requestId) {
-	static BMS_CAN1_INVERTER_REQUEST request_telegram;
-	static BMS_CAN1_INVERTER_FLOAT_t received_telegram;	
-	int16_t   	ReturnResult = CAN_OK;
-	request_telegram.valueId=CAN1_TX_REQUESTED_VALUE_ID_ID ;
-	request_telegram.requestId=requestId;
-	ReturnResult =CAN_Write(&CAN_Tx1_RCT_INVERTER, (uint8_t*)&request_telegram);
-	if(ReturnResult != CAN_OK) {
-		return CAN_ERROR;
-	}
-	// wait 2ms for response
-	while(timestamp + CAN1_TX_TIMEOUT >= Global_1msCounter) {
-		if(CHECKBIT( CAN_1.IFRL.R, 2 )) {
-			// answer received
-			ReturnResult = CAN_Read(&CAN_Rx_RCT_INVERTER, (uint8_t*)&received_telegram);
-			*value=received_telegram.value;
-			return CAN_OK;
-		}
-	return CAN_ERROR;	
-	}
-}
-
-int16_t CAN1_send_request_telegram(uint32_t requestId) {
-	static BMS_CAN1_INVERTER_REQUEST request_telegram;
-	int16_t   	ReturnResult = CAN_OK;
-	request_telegram.valueId=CAN1_TX_REQUESTED_VALUE_ID_ID ;
-	request_telegram.requestId=requestId;
-	
-	shuffle_lsb_msb_can1((uint8_t*)&(request_telegram.valueId));
-	shuffle_lsb_msb_can1((uint8_t*)&(request_telegram.requestId));
-	ReturnResult =CAN_Write(&CAN_Tx1_RCT_INVERTER, (uint8_t*)&request_telegram);
-	return ReturnResult;
-}
-
-uint16_t CAN1_wait_for_response(float* value) {
-	static BMS_CAN1_INVERTER_FLOAT_t received_telegram;	
-	int16_t   	ReturnResult = CAN_OK;
-	if(CHECKBIT( CAN_1.IFRL.R, 2 )) {
-		// answer received
-		ReturnResult = CAN_Read(&CAN_Rx_RCT_INVERTER, (uint8_t*)&received_telegram);
-		shuffle_lsb_msb_can1((uint8_t*)&(received_telegram.value));
-		*value=received_telegram.value;
-		return TRUE;
-	}
-	return FALSE;
-}
-
-
-
-// ***** check_and_save_NLG5_ST ************************************************
-void check_and_save_NLG5_ST( CAN_MAILBOX *p_MBox )
-{
-	uint8_t		Data[8];											// Receive Dummy
-	NLG5_ST_t	gNLG5_ST;
-	
-	
-	if( CAN_Read(p_MBox, &Data[0] ) != CAN_ERROR )
-	{
-		gNLG5_ST.NLG5_STB1.R = ( uint8_t )Data[0];
-		gNLG5_ST.NLG5_STB2.R = ( uint8_t )Data[1];
-		gNLG5_ST.NLG5_STB3.R = ( uint8_t )Data[2];
-		gNLG5_ST.NLG5_STB4   =            Data[3];
-	}
-}
-
-
-
-// ***** End BMS_CAN1_Tools.c **************************************************
+///##############################################################################
+//
+// FILE:	BMS_CAN1_Tools.c
+//
+// TITLE:	CAN 1 
+//			CAN_Tx_NLG5_CTL_618
+//			check_and_save_NLG5_ST
+//
+//
+//##############################################################################
+//
+//==============================================================================
+// Change History:
+//==============================================================================
+// Datum:   | Name | Version:| Change / Cause:                            | No
+//------------------------------------------------------------------------------
+//          |      |         |                                            | 002
+//------------------------------------------------------------------------------
+//          |      |         |                                            | 001
+//------------------------------------------------------------------------------
+// 31.07.13 |  VR  |   1.0   | New Build                                  | 000
+//==============================================================================
+//==============================================================================
+// Comment Change / Cause:
+//==============================================================================
+// Change: 003                                                           // 003
+//----------------------
+//                                                       
+//
+//==============================================================================
+// Change: 002                                                           // 002
+//----------------------
+//                                           
+//
+//==============================================================================
+// Change: 001                                                           // 001
+//----------------------
+// 
+//
+//==============================================================================
+
+#include "BMS_Master.h"
+
+
+//quick and dirty loesung
+//extern CAN_MAILBOX CAN_Tx0_RCT_INVERTER;
+//extern CAN_MAILBOX CAN_Tx1_RCT_INVERTER; 
+//extern CAN_MAILBOX CAN_Rx_RCT_INVERTER;
+
+// ***** CAN_Tx_NLG5_CTL ********************************************************
+uint16_t CAN_Tx_NLG5_CTL_618( void )
+{
+	uint8_t  	Data[7];
+	uint16_t   	ReturnResult = CAN_OK;
+
+
+	Data[0]  = (uint8_t)(0x80);										// CAN enable
+	Data[1]  = (uint8_t)((NLG5_MAINS_CURRENT >> 8) & 0xFF);			// Mains Current Maximum
+	Data[2]  = (uint8_t)(NLG5_MAINS_CURRENT & 0xFF);				
+	Data[3]  = (uint8_t)((NLG5_OUTPUT_VOLTAGE >> 8) & 0xFF);			// Output Voltage Command
+	Data[4]  = (uint8_t)(NLG5_OUTPUT_VOLTAGE & 0xFF);				
+	Data[5]  = (uint8_t)((NLG5_OUTPUT_CURRENT >> 8) & 0xFF);			// Output Current Command
+	Data[6]  = (uint8_t)(NLG5_OUTPUT_CURRENT & 0xFF);				
+		
+	//ReturnResult = CAN_Write( &CAN_TxMB_NLG5_CTL_618, &Data[0] );
+
+	return ReturnResult;
+}
+
+int16_t CAN1_tx_Data_to_Inverter(uint64_t timestamp,BMS_CAN1_INVERTER_TX* data) {
+	int16_t   	ReturnResult = CAN_OK;
+	//uint8_t		test[8]= {0,0,0,0,0,0,0,0};
+	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.maxBatteryChargeCurrent),Global_1msCounter);
+	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.maxBatteryChargeVoltage),Global_1msCounter);
+	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.maxBatteryDischargeCurrent),Global_1msCounter);
+	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.minBatteryDischargeVoltage),Global_1msCounter);
+	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryCurrent),Global_1msCounter);
+	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryVoltage),Global_1msCounter);
+	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batterySOCtarget),Global_1msCounter);
+	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batterySOC),Global_1msCounter);
+	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryCapacity),Global_1msCounter);
+	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryTemperature),Global_1msCounter);
+	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batterySOH),Global_1msCounter);
+	ReturnResult +=CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryStatus),Global_1msCounter);
+	//ReturnResult =CAN_Write(&CAN_Tx0_RCT_INVERTER,test);
+	return ReturnResult;
+}
+
+uint32_t delay_CAN1_ms(uint64_t timestamp,uint32_t delay_ms) {
+	while(timestamp + delay_ms >Global_1msCounter) {
+		// do nothing
+	}
+	return Global_1msCounter;
+}
+
+int16_t CAN1_request_float_value(uint64_t timestamp,float* value,uint32_t requestId) {
+	static BMS_CAN1_INVERTER_REQUEST request_telegram;
+	static BMS_CAN1_INVERTER_FLOAT_t received_telegram;	
+	int16_t   	ReturnResult = CAN_OK;
+	request_telegram.valueId=CAN1_TX_REQUESTED_VALUE_ID_ID ;
+	request_telegram.requestId=requestId;
+	ReturnResult =CAN_Write(&CAN_Tx1_RCT_INVERTER, (uint8_t*)&request_telegram);
+	if(ReturnResult != CAN_OK) {
+		return CAN_ERROR;
+	}
+	// wait 2ms for response
+	while(timestamp + CAN1_TX_TIMEOUT >= Global_1msCounter) {
+		if(CHECKBIT( CAN_1.IFRL.R, 2 )) {
+			// answer received
+			ReturnResult = CAN_Read(&CAN_Rx_RCT_INVERTER, (uint8_t*)&received_telegram);
+			*value=received_telegram.value;
+			return CAN_OK;
+		}
+	return CAN_ERROR;	
+	}
+}
+
+int16_t CAN1_send_request_telegram(uint32_t requestId) {
+	static BMS_CAN1_INVERTER_REQUEST request_telegram;
+	int16_t   	ReturnResult = CAN_OK;
+	request_telegram.valueId=CAN1_TX_REQUESTED_VALUE_ID_ID ;
+	request_telegram.requestId=requestId;
+	
+	shuffle_lsb_msb_can1((uint8_t*)&(request_telegram.valueId));
+	shuffle_lsb_msb_can1((uint8_t*)&(request_telegram.requestId));
+	ReturnResult =CAN_Write(&CAN_Tx1_RCT_INVERTER, (uint8_t*)&request_telegram);
+	return ReturnResult;
+}
+
+uint16_t CAN1_wait_for_response(float* value) {
+	static BMS_CAN1_INVERTER_FLOAT_t received_telegram;	
+	int16_t   	ReturnResult = CAN_OK;
+	if(CHECKBIT( CAN_1.IFRL.R, 2 )) {
+		// answer received
+		ReturnResult = CAN_Read(&CAN_Rx_RCT_INVERTER, (uint8_t*)&received_telegram);
+		shuffle_lsb_msb_can1((uint8_t*)&(received_telegram.value));
+		*value=received_telegram.value;
+		return TRUE;
+	}
+	return FALSE;
+}
+
+
+
+// ***** check_and_save_NLG5_ST ************************************************
+void check_and_save_NLG5_ST( CAN_MAILBOX *p_MBox )
+{
+	uint8_t		Data[8];											// Receive Dummy
+	NLG5_ST_t	gNLG5_ST;
+	
+	
+	if( CAN_Read(p_MBox, &Data[0] ) != CAN_ERROR )
+	{
+		gNLG5_ST.NLG5_STB1.R = ( uint8_t )Data[0];
+		gNLG5_ST.NLG5_STB2.R = ( uint8_t )Data[1];
+		gNLG5_ST.NLG5_STB3.R = ( uint8_t )Data[2];
+		gNLG5_ST.NLG5_STB4   =            Data[3];
+	}
+}
+
+
+
+// ***** End BMS_CAN1_Tools.c **************************************************

+ 2029 - 2029
BMS Master/Sources/BMS_Master.c

@@ -1,2029 +1,2029 @@
-//##############################################################################
-//
-// FILE:	BMS_Master.c
-//
-// TITLE:	Functions of BMS_Master
-//            void		BMS_Init_BSD	( void );
-//            void		BMS_Init_BSE	( void );
-//            void		SwitchRelais	( uint8_t, uint8_t );
-//            void		SetBalancer		( void );
-//	          uint16_t	BMS_Do			( void );
-//
-//
-//##############################################################################
-
-//==============================================================================
-// Historie:
-//==============================================================================
-// Datum:   | Name | Version:| Aenderungsgrund:                          | rev.:
-//------------------------------------------------------------------------------
-//          |  SB  | 2.1    |  Implementaion of Balancing and SoC Estimator                                         | 003   
-//------------------------------------------------------------------------------
-//          |  SB  |  2.0   | Adaptation for RCT	                                           | 002   
-//------------------------------------------------------------------------------
-// 01.07.13 |  VR  |   1.1   | Rearrange Code for IAA Bus                | 001 
-//------------------------------------------------------------------------------
-// 20.04.10 |  TM  |   1.0   | Start Code for Master Test                | 000
-//==============================================================================
-
-#include "BMS_Master.h"
-
-
-
-// ***** Global Data ***********************************************************
-extern uint32_t 	Global_1msCounter; 
-extern BSE_t		gBSE;
-extern BSD_t		gBSD;
-
-
-
-
-
-
-// ***** SwitchRelais **********************************************************
-void SwitchRelais( uint8_t Relais, uint8_t OnOff )
-{
-	if( Relais == LS_RELAIS )
-	{
-		if(OnOff)
-			SET_OUTPIN( PIN_REGNR_RELAIS_SLAVE );
-		else
-			CLEAR_OUTPIN( PIN_REGNR_RELAIS_SLAVE);
-	}
-	
-	if( Relais == HS_RELAIS)
-	{
-		if(OnOff) {
-			SET_OUTPIN( PIN_REGNR_RELAIS_PLUS );
-			SET_OUTPIN(PIN_REGNR_LED3);
-		}
-		else{
-			CLEAR_OUTPIN( PIN_REGNR_RELAIS_PLUS );
-			CLEAR_OUTPIN(PIN_REGNR_LED3);
-		}
-	}
-	
-	if( Relais == PRE_CHARGE_RELAIS )
-	{
-		if(OnOff)
-			SET_OUTPIN( PIN_REGNR_RELAIS_PRECHA );
-		else
-			CLEAR_OUTPIN( PIN_REGNR_RELAIS_PRECHA );
-	}
-	if( Relais ==PWR_SUPPLY ) {
-		if(OnOff)
-			SET_OUTPIN( PIN_REGNR_PWR_SUPPLY );
-		else
-			CLEAR_OUTPIN( PIN_REGNR_PWR_SUPPLY );
-	}
-
-}
-
-
-
-
-
-
-
-
-
-uint16_t init_master_CAN0_fsm(MASTER_CAN0_STRUCT_t* s,BMS_SLAVE_CONFIGURATION_t* cellConfig,BMS_UI_CONFIGURATION_t* uiConfig) {
-	uint8_t slaveNr;
-	uint8_t i;
-	uint16_t stateActive;
-	//go thought all connected Slaves
-	for(slaveNr=0;slaveNr<CAN0_MAX_NR_OF_SLAVES-1;slaveNr++) {
-			
-			// set slave Type
-			s->Slave[slaveNr].SlaveType=cellConfig[slaveNr].type;
-			s->Slave[slaveNr].TxMailbox_ptr=MB_Container[slaveNr];
-			s->Slave[slaveNr].TxTelegram_ptr=&TelegramTxContainer[slaveNr];
-			s->Slave[slaveNr].SlaveConnectionState=cellConfig[slaveNr].connectionSate;
-			
-			// set initial Voltage and Temp value to 0xffff = not initialzied
-			
-			for(i=0;i<MAX_SLAVE_CELLS;i++) {
-				s->Slave[slaveNr].CellVoltage[i]=0xffff;
-				s->Slave[slaveNr].CellTemp[i]=-51;
-				s->Slave[slaveNr].CellConnectionState[i]=cellConfig[slaveNr].cellConnectionState[i];
-				s->Slave[slaveNr].TempSensConnectionState[i]=cellConfig[slaveNr].tempSensConnectionState[i];
-			}
-			s->Slave[slaveNr].HeatSinkTemp=-51;
-			
-			// set slave alive cnt to 0xff fot not initialized
-			for(i=0;i<CAN0_NR_OF_TELEGRAMS;i++) {
-				s->Slave[slaveNr].SlaveAliveCnt[i]=0xff;
-			}
-			
-			// set slave Status to 0xff for Not initialized
-			s->Slave[slaveNr].SlaveMode=0xff;
-			// no Errors
-			s->Slave[slaveNr].SlaveError =0 ;
-			
-			// first State Running mode
-			s->Slave[slaveNr].Set_Mode = BMS_SLAVE_RUN ;
-			// No Balancing
-			s->Slave[slaveNr].Balance_Cell_0_7=0;
-			s->Slave[slaveNr].Balance_Cell_8_15=0;
-			s->Slave[slaveNr].Balance_Cell_16_23=0;
-			
-			// set Slave Error to 0
-			s->Slave[slaveNr].SlaveCanCommuniationError.FailedComCnt=0;
-			s->Slave[slaveNr].SlaveCanCommuniationError.SlaveErrorCounterRegister=0;
-			s->Slave[slaveNr].SlaveCanCommuniationError.SlaveErrorStateRegister=0;
-			s->Slave[slaveNr].SlaveCanCommuniationError.WrongAliveCnt=0;
-			
-			s->Slave[slaveNr].MasterAliveCnt=0;
-			s->Slave[slaveNr].maxCellTemp=0;
-			s->Slave[slaveNr].minCellTemp=0;			
-		}
-	
-	// init UI
-	
-	s->Slave[15].SlaveType=uiConfig->type;
-	s->Slave[15].TxMailbox_ptr=MB_Container[15];
-	s->Slave[15].TxTelegram_ptr=&TelegramTxContainer[15];
-	s->Slave[15].SlaveConnectionState=uiConfig->connectionSate;
-	
-	s->Slave[15].SlaveMode=0xff;
-	// no Errors
-	s->Slave[15].SlaveError =0 ;
-	
-	// first State Running mode
-	s->Slave[15].Set_Mode = BMS_SLAVE_RUN ;
-
-	
-	// set Slave Error to 0
-	s->Slave[15].SlaveCanCommuniationError.FailedComCnt=0;
-	s->Slave[15].SlaveCanCommuniationError.SlaveErrorCounterRegister=0;
-	s->Slave[15].SlaveCanCommuniationError.SlaveErrorStateRegister=0;
-	s->Slave[15].SlaveCanCommuniationError.WrongAliveCnt=0;
-	
-		
-	// set State to INIT
-	s->FsmState=INIT;
-	s->slaveSelect=0;
-	s->transmission_pending=FALSE;
-	s->cycleCounter=0;
-	s->cycleTimestamp=0;
-	s->StateOfCharge=40*60*60*1000; // 40Ah in mAs
-	s->allValuesInitialized = FALSE;
-	s->startCan1Comm=FALSE;
-	s->balancerState=BMS_BALANCE_INIT;
-	
-
-	s->SoC_initialized=FALSE;
-	s->SoC_outside=0;
-	s->maxHeatSinkTemp=0;
-	s->NrOfSlaves= get_nr_of_connected_slaves(s);
-	
-	s->CAN1_fsmStruct.fsmState=CAN1_FSM_INIT;
-	s->CAN1_fsmStruct.highPrioMsgNr=0;
-	s->CAN1_fsmStruct.lowPrioMsgNr=0;
-	s->CAN1_fsmStruct.requestTelegramNr=0;
-	s->CAN1_fsmStruct.timeoutCyclesCnt=0;
-	s->CAN1_fsmStruct.receivedTelegrams=0;
-	s->CAN1_fsmStruct.fastRequestFsmRunning=FALSE;
-	s->CAN1_fsmStruct.slowRequestFsmRunning=FALSE;
-	s->CAN1_fsmStruct.fastRxState=CAN1_FAST_RX_FSM_REQUEST_BATTERY_CURRENT;
-	s->CAN1_fsmStruct.nrOfRecCurrentSamples=0;
-	
-	s->FsmErrorState=ERROR_INIT;
-	//s->ErrorStack.ErrorNr=0;
-	//s->RunMode=RUN_MODE_INIT;
-	s->ErrorFlags=0;
-	// celar Error Buffers
-	ErrorStackClearBuffer(s); 
-	
-	// set Operation fsms to idle
-	s->RunMode.OperationMode=OP_MODE_INIT;
-	s->RunMode.ErrorState1fsm=ES1_FSM_INIT;
-	s->RunMode.ErrorState2fsm=ES2_FSM_INIT;
-	s->RunMode.ErrorState3fsm=ES3_FSM_INIT;
-	// init master temp sensor
-	s->masterTemp=18;
-	s->MasterTempSensState=BMS_MASTER_TEMP_SENSOR_INITIATE_MEASUREMENT;
-	s->inverterState.state=RCT_INV_INACTIVE;
-	s->inverterState.inverterCanOnline=FALSE;
-	s->inverterState.inverterIsCharging=FALSE;
-	s->inverterState.startupPwr=0;
-	
-	// assign impossible values to be able to check if values have been initialized
-	s->inverter.rxStruct.expectedInputPower=-1;
-	s->inverter.rxStruct.DCinputA_power=-1;
-	s->inverter.rxStruct.DCinputB_power=-1;
-	
-	BMS_Clear_Error_init_recovery_struct(s);//clear recovery struct
-	s->ErrorBuffer.ES2_New_Error=0;
-	s->relayState.HS_closed=0;
-	s->relayState.LS_closed=0;
-	s->relayState.PRECHARGE_closed=0;
-	s->relayState.reseved=0;
-	
-	s->reset_test_timestamp=0;
-
-	BMS_RCT_init_fsm(s);
-	initUIFifo(s);
-}
-	
-
-
-void set_slave_cell_connection_state(MASTER_CAN0_STRUCT_t* s,uint8_t slaveNr,CELL_STATE_t* cell_state){
-	uint8_t i;
-	for(i=0;i<MAX_SLAVE_CELLS;i++) {
-		s->Slave[slaveNr].CellConnectionState[i]=cell_state[i];
-	}
-}
-
-void set_slave_temp_connection_state(MASTER_CAN0_STRUCT_t* s,uint8_t slaveNr,TEMP_SENSOR_STATE_t* temp_state){
-	uint8_t i;
-	for(i=0;i<MAX_SLAVE_CELLS;i++) {
-		s->Slave[slaveNr].TempSensConnectionState[i]=temp_state[i];
-	}
-}
-
-uint8_t check_slave_data(MASTER_CAN0_STRUCT_t* s,
-		BMS_CAN0_SLAVE_t* Slave,
-		BMS_CAN0_SLAVE_t* tempSlave,
-		int8_t overTemp_charge,
-		int8_t overTemp_discharge,
-		int8_t underTemp_charge,
-		int8_t underTemp_discharge,
-		uint16_t overVoltage,uint16_t underVoltage) {
-	uint8_t i;
-	uint8_t error_status=BMS_SLAVE_DATA_OK;
-	uint16_t current=s->UI_Board.Ibatt*10;
-	
-	// Check Slave Mode
-	if(tempSlave->SlaveMode==BMS_SLAVE_RUN) {
-		// everything OK
-		
-		
-		//check Slave Alive Counter
-		
-		//if Failed communication counter is grater than 0  the communication
-		//attempt last Cycle failed and the alive counters are out of sync
-		if(tempSlave->SlaveCanCommuniationError.FailedComCnt>0) {
-			//
-			for(i=0;i<CAN0_NR_OF_TELEGRAMS;i++) {
-				Slave->SlaveAliveCnt[i]=tempSlave->SlaveAliveCnt[i];
-			}
-			tempSlave->SlaveCanCommuniationError.FailedComCnt=0;
-		}
-		//compare all Slave Alive Counter
-		else{
-			for(i=0;i<CAN0_NR_OF_TELEGRAMS;i++) {
-				if(	(tempSlave->SlaveAliveCnt[i] == Slave->SlaveAliveCnt[i] + 1) ||
-					(Slave->SlaveAliveCnt[i] ==0x7 && tempSlave->SlaveAliveCnt[i] ==0) ) {
-					// Slave Alive Counter == OK
-					Slave->SlaveAliveCnt[i]=tempSlave->SlaveAliveCnt[i];
-					Slave->SlaveCanCommuniationError.WrongAliveCnt=0;
-				}
-				else {
-					// slave Alive Counter didn't change or made bigger steps
-				
-					Slave->SlaveCanCommuniationError.WrongAliveCnt++;
-					if(Slave->SlaveCanCommuniationError.WrongAliveCnt>=CAN0_MAX_NR_OF_FAILED_COM) {
-						error_status|=BMS_SLAVE_DATA_ERROR_ALIVE_TIMEOUT;
-						// set CAN ERROR
-						ErrorStackPushMasterError(s,BMS_ERROR_STACK_SLAVE_CAN_ERROR,BMS_ERROR_CLASS_1);
-						return error_status;
-					}
-					for(i=0;i<CAN0_NR_OF_TELEGRAMS;i++) {
-						Slave->SlaveAliveCnt[i]=tempSlave->SlaveAliveCnt[i];
-					}
-					error_status |=BMS_SALVE_DATA_ERROR_ALIVE_CNT;
-					return error_status;
-
-				}
-			}
-		}
-		
-		// check voltages
-		// discard uninitialized values 0xff and Bypassed cells
-		for(i=0;i<MAX_SLAVE_CELLS;i++){
-			if(tempSlave->CellConnectionState[i]==CELL_BYPASSED) {
-				// no cell == no voltage 
-				tempSlave->CellVoltage[i]=0;
-			}
-			else if(tempSlave->CellConnectionState[i]==CELL_CONNECTED && tempSlave->CellVoltage[i]>= 0xfff8 ) {
-				// not initialized cells
-				//TODO decide upon signed unsigned representation
-				// use old value
-				tempSlave->CellVoltage[i]= Slave->CellVoltage[i];
-				
-			}
-			if( (tempSlave->CellVoltage[i] >= overVoltage || tempSlave->CellVoltage[i] <= underVoltage) 
-				&& tempSlave->CellConnectionState[i]==CELL_CONNECTED) {
-				//copy Slave to record current Errors
-				*Slave=*tempSlave;
-				error_status |=BMS_SLAVE_DATA_ERROR_VOLTAGE_LIMIT;
-				
-				// Write Error Stack
-				if(tempSlave->CellVoltage[i] >= overVoltage ) {
-					
-					ErrorStackPushSlaveError(s,s->slaveSelect,BMS_ERROR_STACK_SLAVE_OVER_VOLTAGE,i,BMS_ERROR_CLASS_3);
-					error_status |=BMS_SLAVE_DATA_ERROR_OVER_VOLTAGE;
-				}
-				else {
-					
-					ErrorStackPushSlaveError(s,s->slaveSelect,BMS_ERROR_STACK_SLAVE_UNDER_VOLTAGE,i,BMS_ERROR_CLASS_3);
-					error_status |=BMS_SLAVE_DATA_ERROR_UNDER_VOLTAGE;
-				}
-				
-				return error_status;
-			}
-			
-		}
-		
-		if(tempSlave->HeatSinkTemp >= BMS_ERROR_THRESHOLD_T_HEATSINK_MAX || tempSlave->HeatSinkTemp <= BMS_ERROR_THRESHOLD_T_HEATSINK_MIN){
-			//copy Slave to record current Errors
-			*Slave=*tempSlave;
-			error_status |=BMS_SLAVE_DATA_ERROR_HEAT_SINK_LIMIT;
-			// Write Error Stack
-			if(tempSlave->HeatSinkTemp >= BMS_ERROR_THRESHOLD_T_HEATSINK_MAX  ) {
-				// Has to be defined
-				
-			}
-			else {
-				// has to be defined
-			}
-			return error_status;
-		}
-		
-		//check cell temperatures		
-		for(i=0;i<MAX_SLAVE_CELLS;i++){
-			
-			if (tempSlave->CellTemp[i] > -40) {
-				//toDo: QUICKFIX FOR INITIALIZED SENSORS
-				
-				if(current < -100 ) {
-					// battery is charged
-					if( (tempSlave->CellTemp[i] >= overTemp_charge || tempSlave->CellTemp[i] <= underTemp_charge) 
-						&& tempSlave->TempSensConnectionState[i] ==TEMP_SENSOR_CONNECTED) {
-						//copy Slave to record current Errors
-						*Slave=*tempSlave;
-						error_status |=BMS_SLAVE_DATA_ERROR_TEMP_LIMIT;
-						
-						// Write Error Stack
-						if(tempSlave->CellTemp[i] >= overTemp_charge  ) {
-							ErrorStackPushSlaveError(s,s->slaveSelect,BMS_ERROR_STACK_SLAVE_OVER_TEMP_CHARGE,i,BMS_ERROR_CLASS_3);
-							
-						}
-						else {
-							ErrorStackPushSlaveError(s,s->slaveSelect,BMS_ERROR_STACK_SLAVE_UNDER_TEMP_CHARGE,i,BMS_ERROR_CLASS_3);
-						}
-						return error_status;
-					}	
-				}
-				else {
-					// battery is discharged
-					if( (tempSlave->CellTemp[i] >= overTemp_discharge || tempSlave->CellTemp[i] <= underTemp_discharge) 
-						&& tempSlave->TempSensConnectionState[i] ==TEMP_SENSOR_CONNECTED) {
-						//copy Slave to record current Errors
-						*Slave=*tempSlave;
-						error_status |=BMS_SLAVE_DATA_ERROR_TEMP_LIMIT;
-						
-						// Write Error Stack
-						if(tempSlave->CellTemp[i] >= overTemp_discharge  ) {
-							ErrorStackPushSlaveError(s,s->slaveSelect,BMS_ERROR_STACK_SLAVE_OVER_TEMP_DISCHARGE,i,BMS_ERROR_CLASS_3);
-							
-						}
-						else {
-							ErrorStackPushSlaveError(s,s->slaveSelect,BMS_ERROR_STACK_SLAVE_UNDER_TEMP_DISCHARGE,i,BMS_ERROR_CLASS_3);
-						}
-						return error_status;
-					}						
-				}
-			}
-		}
-		
-
-	
-		*Slave=*tempSlave;
-		return error_status; //everything should be ok
-	}
-}
-
-uint8_t check_UI_data(BMS_CAN0_SLAVE_t* Slave, BMS_CAN0_SLAVE_t* tempSlave,BMS_CAN0_UI_t* ui,BMS_CAN0_UI_t* tempUI) {
-	// todo Check Alive Cnt
-	// Check Over current etc
-	uint8_t i=0;
-	
-	if(tempUI->Ibatt > 50) {
-		i++;
-	}
-	
-	ui->Ubatt=tempUI->Ubatt;
-	ui->Ibatt=tempUI->Ibatt;
-	ui->Checksum=tempUI->Checksum;
-	return BMS_SLAVE_DATA_OK;
-}
-
-/**
- * @brief calculate Voltage of Slave Board By adding cell voltages
- */
-uint32_t calc_block_voltage(BMS_CAN0_SLAVE_t* Slave) {
-	uint32_t blockVoltage=0;
-	uint8_t i=0;
-	for(i=0;i<MAX_SLAVE_CELLS;i++) {
-		if(Slave->CellConnectionState[i]==CELL_CONNECTED) {
-			blockVoltage += Slave->CellVoltage[i];
-		}
-	}
-	return blockVoltage;
-}
-
-/**
- * @brief calculate min and Max Voltage of Block
- */
-uint32_t calc_min_max_voltage_slave(BMS_CAN0_SLAVE_t* Slave) {
-	uint16_t minV=Slave->CellVoltage[0];
-	uint16_t maxV=Slave->CellVoltage[0];
-	uint8_t i=0;
-	for(i=0;i<MAX_SLAVE_CELLS;i++) {
-		if(Slave->CellConnectionState[i]==CELL_CONNECTED) {
-			if(minV >= Slave->CellVoltage[i]) {
-				minV = Slave->CellVoltage[i];	
-			}
-			if(maxV <= Slave->CellVoltage[i]) {
-				maxV = Slave->CellVoltage[i];	
-			}			
-		}
-
-	}
-	Slave->minCellVoltage=minV;
-	Slave->maxCellVoltage=maxV;
-	return TRUE;
-}
-
-/**
- * @brief calculate min and Max Voltage of System
- */
-uint32_t calc_min_max_voltage_system(MASTER_CAN0_STRUCT_t* s) {
-	uint8_t slave_nr=0;
-	uint16_t minV=BMS_SLAVE_MAX_CELL_VOLTAGE;
-	uint16_t maxV=BMS_SLAVE_MIN_CELL_VOLTAGE;
-	BMS_CAN0_SLAVE_t* Slave;
-	for(slave_nr=0;slave_nr<CAN0_MAX_NR_OF_SLAVES -1 ;slave_nr++) {
-		if(s->Slave[slave_nr].SlaveConnectionState != NOT_CONNECTED ) {
-			//slave is connected
-			Slave=&(s->Slave[slave_nr]);
-			if(Slave->maxCellVoltage >=maxV ) {
-				maxV = Slave->maxCellVoltage;
-			}
-			if(Slave->minCellVoltage <= minV) {
-				minV = Slave->minCellVoltage;
-			}
-		}
-	}
-	s->minCellVoltage=minV;
-	s->maxCellVoltage=maxV;
-	return TRUE;
-}
-
-/*
- * set balancing register for cell_nr 
- */
-uint32_t balance_cell(BMS_CAN0_SLAVE_t* Slave,uint8_t cell_nr) {
-	if( cell_nr <8) {
-		Slave->Balance_Cell_0_7|= (1<<cell_nr);
-		return TRUE;
-	}
-	else if(cell_nr <16) {
-		Slave->Balance_Cell_8_15|=(1<<(cell_nr-8));
-		return TRUE;
-	}
-	else {
-		Slave->Balance_Cell_16_23|=(1<<(cell_nr-16));
-		return TRUE;		
-	}
-	
-	return FALSE;
-}
-
-/**
- * go though all slaves, destinguish slaves to balance and set Balancearray
- */
-uint32_t set_balancer(MASTER_CAN0_STRUCT_t* s) {
-	uint8_t slave_nr=0;
-	uint8_t cell_nr=0;
-	BMS_CAN0_SLAVE_t* Slave;
-	
-	for(slave_nr=0;slave_nr < CAN0_MAX_NR_OF_SLAVES -1 ;slave_nr++) {	// -1 because slave 15 is UI
-		if(s->Slave[slave_nr].SlaveConnectionState != NOT_CONNECTED) {
-			// slave is connected
-			Slave=&(s->Slave[slave_nr]);
-			
-			
-			if(Slave->maxCellVoltage - s->minCellVoltage > SLAVE_BALANCE_MIN_DELTA_U_MV) {
-				// blancing neccessay
-				for(cell_nr=0;cell_nr <MAX_SLAVE_CELLS;cell_nr++) {
-					if(Slave->CellConnectionState[cell_nr]==CELL_CONNECTED) {
-						// cell is connected
-						if(Slave->CellVoltage[cell_nr] - s->minCellVoltage > SLAVE_BALANCE_MIN_DELTA_U_MV) {
-							// cell has to be balanced
-							balance_cell(Slave,cell_nr);
-						}
-					}
-				}
-			}
-			else {
-				// no need to balance				
-			}
-
-		}
-		
-	}
-	
-}
-
-/**
- * set all balance registers to off
- */
-uint32_t set_balancer_off(MASTER_CAN0_STRUCT_t* s) {
-	uint8_t slave_nr=0;
-	BMS_CAN0_SLAVE_t* Slave;
-	for(slave_nr=0;slave_nr < CAN0_MAX_NR_OF_SLAVES -1 ;slave_nr++) {
-		Slave=&(s->Slave[slave_nr]);
-		Slave->Balance_Cell_0_7=0;
-		Slave->Balance_Cell_16_23=0;
-		Slave->Balance_Cell_8_15=0;		
-	}
-	return TRUE;
-}
-
-
-/**
- * @brief set min and Max Cell Temperature
- *  */
-
-uint32_t set_block_min_max_temp(BMS_CAN0_SLAVE_t* Slave){
-	uint8_t	i;
-	int8_t maxTemp=25;
-	int8_t minTemp=25;
-	for(i=0;i<MAX_SLAVE_CELLS;i++) {
-		if(Slave->TempSensConnectionState[i]==TEMP_SENSOR_CONNECTED){
-			if(Slave->CellTemp[i] > maxTemp) {
-				maxTemp=Slave->CellTemp[i];
-			}
-			if(Slave->CellTemp[i] < minTemp) {
-				minTemp=Slave->CellTemp[i];
-			}
-		}
-	}
-	Slave->maxCellTemp=maxTemp;
-	Slave->minCellTemp=minTemp;
-}
-
-/**
- * @brief set min and Max Cell Temperature of System
- *  */
-
-uint32_t set_system_min_max_temp(MASTER_CAN0_STRUCT_t* s){
-	uint8_t	i;
-	int8_t maxTemp=25;
-	int8_t minTemp=25;
-	BMS_CAN0_SLAVE_t* Slave;
-	
-	for(i=0;i<CAN0_MAX_NR_OF_SLAVES;i++) {
-		if(s->Slave[i].SlaveConnectionState!=NOT_CONNECTED && s->Slave[i].SlaveType == SLAVE) {
-			Slave=&(s->Slave[i]);
-			if(Slave->maxCellTemp > maxTemp) {
-				maxTemp=Slave->maxCellTemp;
-			}
-			if(Slave->minCellTemp < minTemp) {
-				minTemp=Slave->minCellTemp;
-			}
-		}
-	}
-	s->maxCellTemp=maxTemp;
-	s->minCellTemp=minTemp;
-}
-
-uint32_t set_system_min_max_heatsink_temp(MASTER_CAN0_STRUCT_t* s) {
-	uint8_t i;
-	int8_t maxTemp=25;
-	int8_t minTemp=25;
-	BMS_CAN0_SLAVE_t* Slave;
-	
-	for(i=0;i<CAN0_MAX_NR_OF_SLAVES;i++) {
-		if(s->Slave[i].SlaveConnectionState!=NOT_CONNECTED &&s->Slave[i].SlaveType == SLAVE) {
-			Slave=&(s->Slave[i]);
-			if(Slave->HeatSinkTemp > maxTemp) {
-				maxTemp=Slave->HeatSinkTemp;
-			}
-			if(Slave->HeatSinkTemp < minTemp) {
-				minTemp=Slave->HeatSinkTemp;
-			}
-		}
-	}
-	s->maxHeatSinkTemp=maxTemp;
-	s->minHeatSinkTemp=minTemp;
-	
-	return 0;
-}
-
-/**
- * @brief calculate Voltage of System by adding block voltages
- */
-uint32_t calc_system_voltage(MASTER_CAN0_STRUCT_t* s) {
-	uint32_t systemVoltage=0;
-	uint8_t i=0;
-	for(i=0;i<CAN0_MAX_NR_OF_SLAVES;i++) {
-		if(s->Slave[i].SlaveConnectionState!=NOT_CONNECTED && s->Slave[i].SlaveType == SLAVE ) {
-			systemVoltage += s->Slave[i].BlockVoltage;
-		}
-	}
-	return systemVoltage;
-}
-
-/**
- * @bief calculate SOC by simple coulomb counting
- */
-void calc_system_SoC(MASTER_CAN0_STRUCT_t* s) {
-	s->StateOfCharge = s->StateOfCharge - s->UI_Board.Ibatt*10 *200; // t=200ms ibatt in 10mA steps
-}
-
-/**
- * @brief convert inverter data into correct data types
- */
-void refresh_inverter_tx_data(MASTER_CAN0_STRUCT_t* s) {
-	BMS_CAN1_INVERTER_TX* inv=&(s->inverter.txStruct);
-	inv->Values.batteryCapacity.value=36.0;
-	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batteryCapacity.value));
-	inv->Values.batteryCurrent.value=( (float)(s->UI_Board.Ibatt) )/100 ;
-	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batteryCurrent.value));
-	inv->Values.batterySOC.value=s->SoC_estimator.SoC_percentage_smooth;
-	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batterySOC.value));
-	inv->Values.batterySOCtarget.value=(float)-1.0;
-	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batterySOCtarget.value));
-	inv->Values.batterySOH.value=(float)1.0;
-	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batterySOH.value));
-	inv->Values.batteryStatus.byte6=0;
-	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batteryStatus.byte6));
-	inv->Values.batteryTemperature.value=(float)s->maxCellTemp;
-	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batteryTemperature.value));
-	inv->Values.batteryVoltage.value=( (float)(s->systemVoltage)) /1000.0;
-	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batteryVoltage.value));
-	inv->Values.maxBatteryChargeCurrent.value=s->SoC_estimator.MaxBatteryChargeCurrent;
-	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.maxBatteryChargeCurrent.value));
-	inv->Values.maxBatteryChargeVoltage.value=s->startupConfig.maxBatteryVoltage;
-	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.maxBatteryChargeVoltage.value));
-	inv->Values.maxBatteryDischargeCurrent.value=s->SoC_estimator.MaxBatteryDischargeCurrent;
-	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.maxBatteryDischargeCurrent.value));
-	inv->Values.minBatteryDischargeVoltage.value=s->startupConfig.minBatteryVoltage;
-	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.minBatteryDischargeVoltage.value));
-	
-	if(s->relayState.HS_closed == TRUE && s->relayState.LS_closed == TRUE && s->relayState.PRECHARGE_closed == TRUE) {
-		inv->Values.batteryModeExtra.value = 0;
-		
-	}
-	else {
-		inv->Values.batteryModeExtra.value = 1;
-		shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batteryModeExtra.value));
-	}
-	//inv->Values.batteryMode.value=(uint32_t)(s->RunMode);
-	//shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batteryMode.value));
-}
-
-void shuffle_lsb_msb_can1(uint8_t* value) {
-	uint8_t tempValue[4];
-	tempValue[3]=value[0];
-	tempValue[2]=value[1];
-	tempValue[1]=value[2];
-	tempValue[0]=value[3];
-	
-	value[0]=tempValue[0];
-	value[1]=tempValue[1];
-	value[2]=tempValue[2];
-	value[3]=tempValue[3];
-}
-
-
-uint8_t check_if_all_values_are_initialized(MASTER_CAN0_STRUCT_t* s) {
-	uint8_t slaveNr;
-	uint8_t cellNr;
-	for(slaveNr=0;slaveNr<CAN0_MAX_NR_OF_SLAVES-1;slaveNr++){
-		if(s->Slave[slaveNr].SlaveConnectionState != NOT_CONNECTED) {
-			for(cellNr=0;cellNr<MAX_SLAVE_CELLS;cellNr++) {
-				if(s->Slave[slaveNr].CellConnectionState[cellNr]==CELL_CONNECTED) {
-					if(s->Slave[slaveNr].CellVoltage[cellNr] == 0xffff) {
-						return FALSE;
-					}
-				}
-				if(s->Slave[slaveNr].TempSensConnectionState[cellNr] == TEMP_SENSOR_CONNECTED) {
-					if(s->Slave[slaveNr].CellTemp[cellNr] == -1) {
-						return FALSE;
-					}
-				}
-			}
-		}
-		
-	}
-	return TRUE;
-}
-
-/**
- * @brief Handles communication with Slave-Boards over CAN0 interface
- * @param	s pointer to state variable
- * @param	time	current timestamp in ms
- * 
- * Master_CAN0_fsm is a finite state machine which handles the commuinication between Master and Slave boards.
- * It requests Data from the Slaves by sending an Request telegram, and saves the received data in the
- * provided MASTER_CAN0_STRUCT. It records CAN BUS Errors and hands these information to the Master_CAN0_ERROR_fsm. 
- */	
-uint16_t Master_CAN0_fsm(MASTER_CAN0_STRUCT_t* s,uint32_t time) {
-	CAN_CONFIG *config;
-	int8_t can_state=CAN_OK;
-	uint8_t data_state=0;
-	uint8_t ui_state=FALSE;
-	switch(s->FsmState) {
-		case INIT:
-			s->slaveSelect=0;
-			s->cycleTimestamp=time;
-			s->FsmState=CHECK_IF_SLAVE_ACTIVE;
-			s->cycleCounter++;
-			return TRUE;
-		break;
-		case CHECK_IF_SLAVE_ACTIVE:
-			// transmitt data to Inverter
-				if(s->SoC_initialized==TRUE && s->allValuesInitialized ==TRUE) {
-					//Master_CAN1_Inverter_fsm( s,&(s->CAN1_fsmStruct)) ;
-					Master_CAN1_select_comm_mode ( s,&(s->CAN1_fsmStruct)) ;
-				}
-				// Update Master temp sensor
-				readMasterTempSensorFsm(s);
-			s->timestamp=Global_1msCounter;
-			if(s->Slave[s->slaveSelect].SlaveConnectionState == NOT_CONNECTED) {
-				s->FsmState=WAIT_FOR_NEXT_SLAVE_TIMESLOT;
-				s->slaveSelect++;		// ignore and go to next slave
-				if(s->slaveSelect>=CAN0_MAX_NR_OF_SLAVES) {
-					s->slaveSelect=0;
-					s->FsmState=WAIT_FOR_NEXT_COMMUNICATION_CYCLE;
-				}
-				return TRUE;
-			}
-			else{
-				s->Slave[s->slaveSelect].SlaveTelegramsRecFlag=0;	// no Telegrams recoredet yet
-				s->FsmState=SEND_REQUEST_TELEGRAM;
-				
-				return TRUE;
-			}
-		break;	
-		case SEND_REQUEST_TELEGRAM:
-			s->transmission_pending=TRUE;
-			CAN0_tx_send_request_telegram(&(s->Slave[s->slaveSelect]),s->Slave[s->slaveSelect].MasterAliveCnt);
-			s->Slave[s->slaveSelect].MasterAliveCnt++;
-			if(s->Slave[s->slaveSelect].MasterAliveCnt >=CAN0_NR_OF_TELEGRAMS) {
-				s->Slave[s->slaveSelect].MasterAliveCnt=0;
-			}
-			
-			if(s->Slave[s->slaveSelect].SlaveType==SLAVE) {
-				s->tempSlave=s->Slave[s->slaveSelect];
-			}
-			else {
-				s->tempSlave=s->Slave[s->slaveSelect];
-				s->temp_UI_Board=s->UI_Board;
-			}
-			s->FsmState=WAIT_FOR_SLAVE_RESPONSE;
-			return TRUE;
-		break;
-		case WAIT_FOR_SLAVE_RESPONSE:
-			config= s->tempSlave.TxMailbox_ptr->p_CAN_Config;
-			//can_state=CAN_Check_error_Register(config);
-			if(s->tempSlave.SlaveType==SLAVE) {
-				if(s->tempSlave.SlaveConnectionState == CONNECTED) {
-					// real slave with real Sensors
-					CAN0_check_if_slave_rec(&(s->tempSlave));
-				}
-				else if(s->tempSlave.SlaveConnectionState == DEBUG_DATA_SIMULATED) {
-					// real slave with simulated Sensors
-					CAN0_DEBUG_data_check_if_slave_rec((&s->tempSlave),&(gDUMMY_data_struct.Slave[s->slaveSelect]) );
-				}
-				else{
-					// simulated Slave
-					CAN0_DEBUG_slave_check_if_slave_rec((&s->tempSlave),&(gDUMMY_data_struct.Slave[s->slaveSelect]) );
-				}
-				
-				//all Telegrams received
-				if(s->tempSlave.SlaveTelegramsRecFlag==CAN0_ALL_TELEGRAMS_REC ) {
-					//s->slaveSelect++;				
-					if(can_state == CAN_OK) {
-						// all telegrams received => reset error counter
-						if(s->slaveSelect == 3) {
-							s->FsmState= CHECK_CAN_DATA;
-						}
-						s->Slave[s->slaveSelect].SlaveCanCommuniationError.FailedComCnt=0;
-						s->FsmState= CHECK_CAN_DATA;
-						return TRUE;
-					}
-					else {
-						s->FsmState =HANDLE_CAN_ERROR;
-						return TRUE;
-					}
-				}
-
-				//timeout
-				else if(s->timestamp + CAN0_TIMEOUT_MS <=Global_1msCounter) {
-					s->FsmState =HANDLE_CAN_ERROR;
-					return TRUE;
-				}
-				// wait
-				else {
-					s->FsmState =WAIT_FOR_SLAVE_RESPONSE;
-					return TRUE;				
-				}
-			}
-			else {
-				
-				
-				if(s->tempSlave.SlaveConnectionState == CONNECTED) {
-					// real UI with real Sensors
-					ui_state=CAN0_check_if_UI_Board_rec( &(s->tempSlave) ,&(s->temp_UI_Board));
-				}
-				else if(s->tempSlave.SlaveConnectionState == DEBUG_DATA_SIMULATED) {
-					// real UI with simulated Sensors
-					ui_state=CAN0_DEBUG_data_check_if_UI_Board_rec(&(s->tempSlave),
-							&(gDUMMY_data_struct.Slave[s->slaveSelect]),
-							&(s->temp_UI_Board),
-							&(gDUMMY_data_struct.UI_Board));
-				}
-				else{
-					// simulated UI
-					ui_state=CAN0_DEBUG_slave_check_if_UI_Board_rec(&(s->tempSlave),
-							&(gDUMMY_data_struct.Slave[s->slaveSelect]),
-							&(s->temp_UI_Board),
-							&(gDUMMY_data_struct.UI_Board));
-				}
-				
-				if(ui_state==TRUE) {
-					//s->slaveSelect++;
-					if(can_state==CAN_OK) {
-						s->FsmState= CHECK_CAN_DATA;
-						return TRUE;
-					}
-					else {
-						s->FsmState =HANDLE_CAN_ERROR;
-						return TRUE;
-					}
-					//return TRUE;					
-				}
-				//timeout
-				else if(s->timestamp + CAN0_TIMEOUT_MS <=time) {
-					s->FsmState =HANDLE_CAN_ERROR;
-					return TRUE;
-				}
-				// wait
-				else {
-					s->FsmState =WAIT_FOR_SLAVE_RESPONSE;
-					return TRUE;				
-				}				
-			}
-		break;
-		case CHECK_CAN_DATA:
-				// check if rx data is correct
-			
-			if(s->tempSlave.SlaveType ==SLAVE ) {
-				
-				s->ErrorFlags=check_slave_data(s,&(s->Slave[s->slaveSelect]),
-						&(s->tempSlave),
-						BMS_SLAVE_MAX_TEMP,
-						BMS_ERROR_THRESHOLD_T_DISCHARGE_MAX,
-						BMS_SLAVE_MIN_TEMP,
-						BMS_ERROR_THRESHOLD_T_DISCHARGE_MIN,
-						BMS_SLAVE_MAX_CELL_VOLTAGE,
-						BMS_SLAVE_MIN_CELL_VOLTAGE);
-
-				if(s->ErrorFlags & BMS_SLAVE_DATA_ERROR_ALIVE_TIMEOUT) {
-					s->FsmState =SHUT_DOWN_BMS;
-					return TRUE;
-				}
-				
-				if(s->ErrorFlags & BMS_SLAVE_DATA_ERROR_OVER_VOLTAGE) {
-					s->FsmState =SHUT_DOWN_BMS;
-					return TRUE;
-				}		
-				if(s->ErrorFlags & BMS_SLAVE_DATA_ERROR_UNDER_VOLTAGE) {
-					s->FsmState =SHUT_DOWN_BMS;
-					return TRUE;
-				}	
-				if((s->ErrorFlags & BMS_SLAVE_DATA_ERROR_TEMP_LIMIT) && (s->allValuesInitialized == TRUE)) {
-					s->FsmState =SHUT_DOWN_BMS;
-					return TRUE;
-				}
-				if(s->ErrorFlags & BMS_SLAVE_DATA_ERROR_HEAT_SINK_LIMIT) {
-					s->FsmState =SHUT_DOWN_BMS;
-					return TRUE;
-				}
-				if(s->ErrorFlags & BMS_SLAVE_DATA_ERROR_BOARD_ELECTRONIC) {
-					s->FsmState =SHUT_DOWN_BMS;
-					return TRUE;
-				}
-				else {
-					// everything ok
-					
-				}
-				
-				
-				
-			
-				
-			}
-			else {
-				data_state=check_UI_data(&(s->Slave[s->slaveSelect]),
-						&(s->tempSlave),
-						&(s->UI_Board),
-						&(s->temp_UI_Board));	
-				
-				if(s->allValuesInitialized==FALSE) {
-					s->allValuesInitialized=check_if_all_values_are_initialized(s);
-				}
-				
-
-				
-				// Check for "Soft" Errors and set Error states
-				
-
-				
-				
-			}
-			s->transmission_pending=FALSE;
-			
-			s->FsmState= DO_CALCULATIONS;
-			return TRUE;
-		break;
-		case DO_CALCULATIONS:
-			// calculate SoC SoH ?
-			if(s->Slave[s->slaveSelect].SlaveType==SLAVE) {
-				// calculate Slave Voltage
-				s->Slave[s->slaveSelect].BlockVoltage=calc_block_voltage(&(s->Slave[s->slaveSelect]));
-				// set min max Temp
-				set_block_min_max_temp(&(s->Slave[s->slaveSelect]));
-				// set min max Voltage
-				calc_min_max_voltage_slave(&(s->Slave[s->slaveSelect]));
-				
-				s->slaveSelect++;
-				s->FsmState=WAIT_FOR_NEXT_SLAVE_TIMESLOT;
-				return TRUE;
-			}
-			else {
-				
-				
-				
-				// UI-Platine
-				// calc SoC
-				s->systemVoltage=calc_system_voltage(s);
-				calc_min_max_voltage_system(s);
-				set_system_min_max_temp(s);
-				// update UI FIFO
-				popUIFiFo(s); 
-				
-				BMS_Set_Error_Check_voltage_inconsitency(s);
-				
-				// check if System voltage is too high
-				if(s->allValuesInitialized ==TRUE) {
-					// Check Umin 1 Umin2 Umin3
-					BMS_Set_Error_check_Voltage_level_min(s);
-					// Check Umax 1 and Umax 2
-					BMS_Set_Error_check_Voltage_level_max(s) ;
-					BMS_Set_Error_check_System_voltage_level_max(s);
-					
-					// check if CHECK Imax 
-					BMS_Set_Error_Check_derating(s); 
-					
-					
-					// make balancing decisions
-					Master_Balancer_fsm(s);
-				}
-				// if in Winter MOde get SoC from FRAM
-//				if(s->SoC_initialized==TRUE && s->allValuesInitialized ==FALSE && s->RunMode== RUN_MODE_WINTER) {
-//					bms_SoC_init_estimator_FRAM(&(s->SoC_estimator), s->maxCellVoltage);
-//				}
-				// calculate SoC of higest and Lowest Cell
-				if(s->SoC_initialized==FALSE && s->allValuesInitialized ==TRUE) {
-					set_system_min_max_heatsink_temp(s);
-					//set initial SoC
-					if(s->startupConfig.state.Bit.SOC_Initialized) {
-						// get initial SOC From FRAM
-						 bms_SoC_init_estimator_FRAM(&(s->SoC_estimator), s->maxCellVoltage);
-					}
-					else {
-						bms_SoC_init_estimator(&(s->SoC_estimator), s->maxCellVoltage) ;
-					}
-					initSoCFifo(s);
-					s->SoC_initialized=TRUE;
-					s->FsmState=RUNNING_MODE_FSM;
-				}
-				else if(s->SoC_initialized==TRUE && s->allValuesInitialized ==TRUE) {
-					set_system_min_max_heatsink_temp(s);
-					
-					// calc SoC 
-					
-					while(s->SoC_estimator.state != BMS_SOC_READY) {
-						bms_SoC_running_fsm( &(s->SoC_estimator),s->UI_Board.Ibatt*10 ,s->maxCellVoltage,s->minCellVoltage,s->minCellTemp,s->maxCellTemp); 
-					}	
-					s->SoC_estimator.state = BMS_SOC_IDLE   ;		
-					
-					// if soc is at 100% set SoC initialized Flag
-					if(s->SoC_estimator.SoC_percentage_smooth > 0.9999) {
-						s->startupConfig.state.Bit.SOC_Initialized=1;
-						write_fram_set_startup_state(s);
-					}
-					// write SoC to FRAM
-					else if(s->startupConfig.state.Bit.SOC_Initialized==1) {
-						write_fram_set_SoC(s->SoC_estimator.SoC_percentage_smooth);
-					}
-					s->slaveSelect=0;
-					
-					// transmitt data to Inverter
-					if(s->SoC_initialized==TRUE && s->allValuesInitialized ==TRUE) {
-						refresh_inverter_tx_data(s);
-						//Master_CAN1_Inverter_fsm( s,&(s->CAN1_fsmStruct)) ;
-					}
-					// set running Mode
-					
-					// update inverter state
-					BMS_RCT_Inverter_fsm (s);
-					s->FsmState=RUNNING_MODE_FSM;
-					return TRUE;
-				}
-				else {
-					// nothing happend yet
-					s->FsmState=RUNNING_MODE_FSM;
-					return TRUE;
-				}
-	
-			}
-			return TRUE;
-		break;
-		case RUNNING_MODE_FSM:
-			// set running Mode
-			RunningModeFSM(s) ;
-			s->FsmState=WAIT_FOR_NEXT_COMMUNICATION_CYCLE;
-			return TRUE;
-		break;
-		case HANDLE_CAN_ERROR:
-			// delete interrupt flags
-			CAN0_clear_all_interrupt_flags();
-				// handle CAN Errors
-			config= s->tempSlave.TxMailbox_ptr->p_CAN_Config;
-			//can_state=CAN_Check_error_Register(config);			
-			// all telegrams received, can telegrams disturbed
-			if(s->tempSlave.SlaveTelegramsRecFlag==CAN0_ALL_TELEGRAMS_REC ) {
-				// Telegram values could be disturbed => reject all received Data
-				// Don't use newly received data => ignore tempSlave
-				s->Slave[s->slaveSelect].SlaveCanCommuniationError.FailedComCnt++;
-				if(s->Slave[s->slaveSelect].SlaveCanCommuniationError.FailedComCnt >=CAN0_MAX_NR_OF_FAILED_COM) {
-					s->FsmState=SHUT_DOWN_BMS;
-					
-					//write Error
-					ErrorStackPushSlaveError(s,s->slaveSelect,BMS_ERROR_STACK_SLAVE_CAN_ERROR,0,BMS_ERROR_CLASS_2);
-					return TRUE;
-				}
-				s->FsmState=DO_CALCULATIONS;
-				return TRUE;
-				
-			}
-			// telegrams missing, CAN Channel Ok
-			else{
-				if(can_state == CAN_OK) {
-					// CAN BUS OK, Slave is not reacting
-					// Don't use newly received data
-					s->Slave[s->slaveSelect].SlaveCanCommuniationError.FailedComCnt++;
-					if(s->Slave[s->slaveSelect].SlaveCanCommuniationError.FailedComCnt >=CAN0_MAX_NR_OF_FAILED_COM) {
-						//write Error
-						ErrorStackPushSlaveError(s,s->slaveSelect,BMS_ERROR_STACK_SLAVE_CAN_ERROR,0,BMS_ERROR_CLASS_2);
-						s->FsmState=SHUT_DOWN_BMS;
-						s->reset_test_timestamp=Global_1msCounter;
-						return TRUE;
-					}
-					s->FsmState=DO_CALCULATIONS;
-					return TRUE;				
-				}
-				else{
-					// CAN BUS ERROR, telegrams not coming thought
-					// Don't use newly received data
-					s->Slave[s->slaveSelect].SlaveCanCommuniationError.FailedComCnt++;
-					if(s->Slave[s->slaveSelect].SlaveCanCommuniationError.FailedComCnt >=CAN0_MAX_NR_OF_FAILED_COM) {
-						//write Error
-						ErrorStackPushSlaveError(s,s->slaveSelect,BMS_ERROR_STACK_SLAVE_CAN_ERROR,0,BMS_ERROR_CLASS_2);
-						s->reset_test_timestamp=Global_1msCounter;
-						s->FsmState=SHUT_DOWN_BMS;
-						return TRUE;
-					}
-					s->FsmState=DO_CALCULATIONS;
-					return TRUE;
-				}
-			}
-
-			return TRUE;
-		break;
-		case WAIT_FOR_NEXT_SLAVE_TIMESLOT:
-			// next timesolt ready
-			
-			if(s->timestamp +CAN0_RASTER_MS <= time) {
-				s->FsmState= CHECK_IF_SLAVE_ACTIVE;
-				return TRUE;
-				}
-			//wait
-			else{
-				s->FsmState=WAIT_FOR_NEXT_SLAVE_TIMESLOT;
-				return TRUE;
-			}
-		break;
-		case SEND_RECEIVE_INVERTER_DATA:
-			// send data to inverter and Wait for response
-			//CAN1_tx_Data_to_Inverter(time,&(s->inverter.txStruct));
-			//request DC INPUT VOLTAGE
-			//CAN1_request_float_value(Global_1msCounter,&(s->inverter.rxStruct.DCinputA_power),CAN1_RX_DC_INPUT_A_VOLTAGE);
-			s->startCan1Comm=TRUE;
-			s->FsmState=WAIT_FOR_NEXT_COMMUNICATION_CYCLE;
-			return TRUE;	
-		break;	
-		case WAIT_FOR_NEXT_COMMUNICATION_CYCLE:
-			if(s->cycleTimestamp +CAN0_COMM_CYCLE_MS <= time) {
-				s->FsmState= INIT;
-				return TRUE;
-				}
-			else {
-				s->FsmState=WAIT_FOR_NEXT_COMMUNICATION_CYCLE;
-				return TRUE;
-			}
-			return TRUE; 	
-		break;
-		case SHUT_DOWN_BMS:
-				// Something went horribly wrong, turn off system
-			SwitchRelais( LS_RELAIS, 0);
-			SwitchRelais( PRE_CHARGE_RELAIS, 0);
-			SwitchRelais( HS_RELAIS, 0);
-			s->relayState.HS_closed=FALSE;
-			s->relayState.LS_closed=FALSE;
-			s->relayState.PRECHARGE_closed=FALSE;
-			CLEAR_OUTPIN(PIN_REGNR_LED4);	// set LED4 to 0 to indicate that an Error has occured 
-			
-			//write_fram_word(BMS_STARTUP_ERROR_MODE_3,3,BMS_STARTUP_MODE_ADDR);
-			// go to Error	Mode
-			
-			// continue communication cycles
-			s->FsmState=DO_CALCULATIONS;
-			
-			return TRUE;
-		break;
-		default:
-			return FALSE;
-		break;
-	}
-	return FALSE;
-}
-	
-
-
-
-uint16_t init_master_operation_fsm(BMS_MASTER_OPERATION_t* opFsm) {
-	opFsm->FsmState=MASTER_OPERATION_INIT;
-	opFsm->timestamp=0;
-
-	return TRUE;
-}
-
-
-
-
-uint16_t Master_CAN1_fsm_init(MASTER_CAN1_STRUCT_t* can1Fsm) {
-	can1Fsm->delay =3;
-	can1Fsm->fsmState=CAN1_INIT;
-	can1Fsm->txMsgNr=0;
-	return TRUE;
-}
-
-/*
- * 
- */
-uint32_t Master_CAN1_select_comm_mode (MASTER_CAN0_STRUCT_t* s,MASTER_CAN1_INVERTER_STRUCT_t* fsmStruct) {
-	if(fsmStruct->slowRequestFsmRunning == TRUE) {
-		// slow requests are running => wait till requests are complete
-		Master_CAN1_Inverter_fsm(s,fsmStruct);
-		// set fast request running flag for faast request asap
-		fsmStruct->fastRequestFsmRunning=TRUE;
-		return TRUE;
-	}
-	else if(s->Slave[s->slaveSelect].SlaveType== UI || fsmStruct->fastRequestFsmRunning==TRUE) {
-		// commuincation with UI is about to begin or fast request flag is set
-		// this means 250ms tick is reached => initiate fast request if possible
-		Master_CAN1_Fast_request_fsm (s,fsmStruct);
-		return TRUE;
-	}
-	else {
-		// nothing special run normal fsm
-		Master_CAN1_Inverter_fsm(s,fsmStruct);
-		return TRUE;
-	}
-}
-/*
- * handles request of battery current and battery voltage from inverter
- * which have to be sampled regulatly
- */
-uint32_t Master_CAN1_Fast_request_fsm (MASTER_CAN0_STRUCT_t* s,MASTER_CAN1_INVERTER_STRUCT_t* fsmStruct) {
-	switch(fsmStruct->fastRxState) {
-		case CAN1_FAST_RX_FSM_REQUEST_BATTERY_CURRENT:
-			// request battery current from inverter
-			fsmStruct->nrOfRecCurrentSamples++;
-			CAN1_send_request_telegram(CAN1_RX_BATTERY_CURRENT);
-			fsmStruct->fastRequestFsmRunning=TRUE;
-			fsmStruct->fastRxState=CAN1_FAST_RX_FSM_REQUEST_BATTERY_VOLTAGE;
-			return TRUE;
-		break;	
-		case CAN1_FAST_RX_FSM_REQUEST_BATTERY_VOLTAGE:
-			// readout battery current and request battery voltage
-			if(CAN1_wait_for_response(&(s->inverter.rxStruct.batteryCurrent)) == TRUE ) {
-				// battery current received
-				pushInverterCurrentFIFO(s);
-				// compare UI Current and Inverter Current
-				if(fsmStruct->nrOfRecCurrentSamples > UI_CURRENT_FIFO_SIZE) {
-					// BMS_Set_Error_Check_current_consitency(s); //compare current of UI with Inverter
-				}
-			}
-			else {
-				// no response in 10ms => timeout
-				// go to normal communication fsm
-				fsmStruct->fastRxState = CAN1_FAST_RX_FSM_REQUEST_BATTERY_CURRENT;
-				fsmStruct->fastRequestFsmRunning=FALSE;
-				return TRUE;
-			}
-			// request battery voltage
-			CAN1_send_request_telegram(CAN1_RX_BATTERY_VOLTAGE);
-			fsmStruct->fastRxState =CAN1_FAST_RX_FSM_REQUEST_COMPLETE;
-			return TRUE;
-		break;
-		case CAN1_FAST_RX_FSM_REQUEST_COMPLETE:
-			// readout voltage
-			if(CAN1_wait_for_response(&(s->inverter.rxStruct.batteryVoltage)) == TRUE ) {
-				// battery voltage received
-			}
-			else {
-				// no response in 10ms => timeout
-				// go to normal communication fsm
-				fsmStruct->fastRxState = CAN1_FAST_RX_FSM_REQUEST_BATTERY_CURRENT;
-				fsmStruct->fastRequestFsmRunning=FALSE;
-				return TRUE;
-			}		
-			// fast requests done
-			fsmStruct->fastRxState = CAN1_FAST_RX_FSM_REQUEST_BATTERY_CURRENT;
-			fsmStruct->fastRequestFsmRunning=FALSE;	
-			return TRUE;
-		break;
-	}
-}
-
-
-
-uint32_t Master_CAN1_Inverter_fsm(MASTER_CAN0_STRUCT_t* s,MASTER_CAN1_INVERTER_STRUCT_t* fsmStruct) {
-	BMS_CAN1_INVERTER_TX* data = &(s->inverter.txStruct);
-	BMS_CAN1_INVERTER_CELL_DATA_t txPkg;
-	float* rx_ptr=&(s->inverter.rxStruct.expectedInputPower); 	// points to rx_address to sotre inverter value
-	uint8_t eightBitBuff[8]= {0,0,0,0,0,0,0,0} ;
-	switch(fsmStruct->fsmState) {
-		case CAN1_FSM_INIT:
-			// reset Message counters
-			fsmStruct->highPrioMsgNr=0;
-			fsmStruct->lowPrioMsgNr=0;
-			fsmStruct->requestTelegramNr=0;
-			fsmStruct->timeoutCyclesCnt=0;
-
-			
-			// check if all Values are initialized 
-			// if yes start transmitting
-			if(s->allValuesInitialized == TRUE) {
-				fsmStruct->fsmState=CAN1_FSM_SEND_HIGH_PRIO_DATA;
-				return TRUE;
-			}
-			// not all values are initialized
-			//=> stay in INIT state
-			return TRUE;
-		break;
-		case CAN1_FSM_SEND_HIGH_PRIO_DATA:
-			// rx process complete
-			fsmStruct->slowRequestFsmRunning=FALSE;
-			
-			// transmit high priority data, which is
-			// maximum charge Current
-			// maximum Charge Voltage
-			// maximum Discharge Current
-			// minimum Discharge Voltage
-			// battery Current
-			// battery Voltage
-			// Battery SoC
-			// Battery Capacity
-			// Battery Temperature
-			// Battery SoH
-			// Battery Status
-			// Battery SoC Target
-			
-			if(fsmStruct->highPrioMsgNr == 0) {
-				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.maxBatteryChargeCurrent),Global_1msCounter);
-			}
-			else if(fsmStruct->highPrioMsgNr == 1) {
-				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.maxBatteryChargeVoltage),Global_1msCounter);
-			}
-			else if(fsmStruct->highPrioMsgNr == 2) {
-				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.maxBatteryDischargeCurrent),Global_1msCounter);
-			}
-			else if(fsmStruct->highPrioMsgNr == 3) {
-				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.minBatteryDischargeVoltage),Global_1msCounter);
-			}
-			else if(fsmStruct->highPrioMsgNr == 4) {
-				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryCurrent),Global_1msCounter);
-			}
-			else if(fsmStruct->highPrioMsgNr == 5) {
-				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryVoltage),Global_1msCounter);
-			}
-			else if(fsmStruct->highPrioMsgNr == 7) {
-				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batterySOC),Global_1msCounter);
-			}
-			else if(fsmStruct->highPrioMsgNr == 8) {
-				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryCapacity),Global_1msCounter);
-			}
-			else if(fsmStruct->highPrioMsgNr == 9) {
-				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryTemperature),Global_1msCounter);
-			}
-			else if(fsmStruct->highPrioMsgNr == 10) {
-				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batterySOH),Global_1msCounter);
-			}
-			else if(fsmStruct->highPrioMsgNr == 11) {
-				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batterySOCtarget),Global_1msCounter);
-			}
-			else if(fsmStruct->highPrioMsgNr == 12) {
-				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryMode),Global_1msCounter);
-			}
-			else if(fsmStruct->highPrioMsgNr == 13) {
-				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryModeExtra),Global_1msCounter);
-			}
-			
-			// increment high prio msg cnt
-			fsmStruct->highPrioMsgNr++ ;
-			
-			// if all high prio msg are transmitted start transmitting low prio msg
-			if(fsmStruct->highPrioMsgNr > 13) {
-				fsmStruct->highPrioMsgNr=0;
-				// reset error cnt to start with error 1 again
-				fsmStruct->transmitErrorNrEs1=0;
-				fsmStruct->transmitErrorNrEs2=0;
-				fsmStruct->transmitErrorNrEs3=0;
-				fsmStruct->fsmState=CAN1_FSM_SEND_ES_1;
-				return TRUE;
-			}
-			else {
-				// continue Transmitting high Prio Msg
-				fsmStruct->fsmState=CAN1_FSM_SEND_HIGH_PRIO_DATA;
-				return TRUE;
-			}
-		break;
-		case CAN1_FSM_SEND_ES_1:
-			// send Error Calls 1 Errors
-			
-			if( !ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_1) && !ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_2) && ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_3) ) {
-				// no Error has occured Transmitt everything ok
-				CLEAR_OUTPIN(PIN_REGNR_LED4);
-				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryStatus),Global_1msCounter);
-				fsmStruct->fsmState=CAN1_FSM_SEND_LOW_PRIO_DATA;
-				return TRUE;
-			}
-			
-			else if(ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_3) && fsmStruct->transmitErrorNrEs3 < BMS_ERROR_ERROR_STACK_SIZE) {
-				// transmitt ES 3 Errors
-				// check if Error is active
-				SET_OUTPIN(PIN_REGNR_LED4);
-				while(s->ErrorBuffer.ES3_Error[fsmStruct->transmitErrorNrEs3].Master.active == 0){
-					// Error no ,longer Active go to next entry
-					fsmStruct->transmitErrorNrEs3++;
-					if(fsmStruct->transmitErrorNrEs3 >=BMS_ERROR_ERROR_STACK_SIZE) {
-						
-						return TRUE;
-					}
-				}
-				ErrorStackGenerateStatusPkg(eightBitBuff,(uint8_t*)&(s->ErrorBuffer.ES3_Error[fsmStruct->transmitErrorNrEs3]));
-				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, eightBitBuff,Global_1msCounter);
-				fsmStruct->transmitErrorNrEs3++;
-				return TRUE;
-			}
-			
-			else if(ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_2) && fsmStruct->transmitErrorNrEs2 < BMS_ERROR_ERROR_STACK_SIZE) {
-				// transmitt ES 2 Errors
-				// check if Error is active
-				SET_OUTPIN(PIN_REGNR_LED4);
-				while(s->ErrorBuffer.ES2_Error[fsmStruct->transmitErrorNrEs2].Master.active == 0){
-					// Error no ,longer Active go to next entry
-					fsmStruct->transmitErrorNrEs2++;
-					if(fsmStruct->transmitErrorNrEs2 >=BMS_ERROR_ERROR_STACK_SIZE) {
-						
-						return TRUE;
-					}
-				}
-				ErrorStackGenerateStatusPkg(eightBitBuff,(uint8_t*)&(s->ErrorBuffer.ES2_Error[fsmStruct->transmitErrorNrEs2]));
-				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, eightBitBuff,Global_1msCounter);
-				fsmStruct->transmitErrorNrEs2++;
-				return TRUE;
-			}
-			else if(ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_1) && fsmStruct->transmitErrorNrEs1 < BMS_ERROR_ERROR_STACK_SIZE) {
-				// transmitt ES 1 Errors
-				// check if Error is active
-				SET_OUTPIN(PIN_REGNR_LED4);
-				while(s->ErrorBuffer.ES1_Error[fsmStruct->transmitErrorNrEs1].Master.active == 0){
-					// Error no ,longer Active go to next entry
-					fsmStruct->transmitErrorNrEs1++;
-					if(fsmStruct->transmitErrorNrEs1 >=BMS_ERROR_ERROR_STACK_SIZE) {
-						
-						return TRUE;
-					}					
-				}
-				ErrorStackGenerateStatusPkg(eightBitBuff,(uint8_t*)&(s->ErrorBuffer.ES1_Error[fsmStruct->transmitErrorNrEs1]));
-				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, eightBitBuff,Global_1msCounter);
-				fsmStruct->transmitErrorNrEs1++;
-				return TRUE;
-			}
-			else {
-				fsmStruct->fsmState=CAN1_FSM_SEND_LOW_PRIO_DATA;
-				return TRUE;
-			}
-		break;
-		case CAN1_FSM_SEND_LOW_PRIO_DATA:
-			// send low Priority data which is
-			// Cell temperature and Cell Voltages
-			generateCellInfoPkg(s, fsmStruct->lowPrioMsgNr,&txPkg);
-			CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(txPkg),Global_1msCounter);
-			fsmStruct->lowPrioMsgNr++ ;
-			if(fsmStruct->lowPrioMsgNr >= (s->NrOfSlaves)*MAX_SLAVE_CELLS) {
-				// start with cell nr 0 again
-				fsmStruct->lowPrioMsgNr=0;
-				fsmStruct->fsmState=CAN1_FSM_SEND_REQUEST_DATA;
-				fsmStruct->requestTelegramNr=0;
-				return TRUE;
-			}
-			fsmStruct->fsmState=CAN1_FSM_SEND_LOW_PRIO_DATA;
-			return TRUE;	
-		break;
-		case CAN1_FSM_SEND_REQUEST_DATA:
-			// request data from RCT Inverter
-			// Set flag so request process cant be interrupted 
-			fsmStruct->slowRequestFsmRunning=TRUE;
-			if(fsmStruct->requestTelegramNr==0) {
-				CAN1_send_request_telegram(CAN1_RX_TOTAL_DC_PWR);
-				fsmStruct->fsmState= CAN1_FSM_WAIT_FOR_RESPONSE;
-				return TRUE;
-			}
-			else if(fsmStruct->requestTelegramNr==1) {
-				CAN1_send_request_telegram(CAN1_RX_DC_INPUT_A_POWER);
-				fsmStruct->fsmState= CAN1_FSM_WAIT_FOR_RESPONSE;
-				return TRUE;				
-			}
-			else if(fsmStruct->requestTelegramNr==2) {
-				CAN1_send_request_telegram(CAN1_RX_DC_INPUT_B_POWER);
-				fsmStruct->fsmState= CAN1_FSM_WAIT_FOR_RESPONSE;
-				return TRUE;						
-			}
-			else if(fsmStruct->requestTelegramNr==3) {
-				CAN1_send_request_telegram(CAN1_RX_DC_INPUT_A_POWER);
-				fsmStruct->fsmState= CAN1_FSM_WAIT_FOR_RESPONSE;
-				return TRUE;						
-			}
-			else if(fsmStruct->requestTelegramNr==4) {
-				CAN1_send_request_telegram(CAN1_RX_DC_INPUT_B_POWER);
-				fsmStruct->fsmState= CAN1_FSM_WAIT_FOR_RESPONSE;
-				return TRUE;						
-			}
-			else {
-				// you should not be here
-				fsmStruct->fsmState=CAN1_FSM_SEND_HIGH_PRIO_DATA;
-				return TRUE;
-			}
-		break;	
-		case CAN1_FSM_WAIT_FOR_RESPONSE:
-			// to be updateted for more values
-			if(fsmStruct->requestTelegramNr==0) {
-				rx_ptr=&(s->inverter.rxStruct.expectedInputPower);
-			}
-			else if(fsmStruct->requestTelegramNr==1) {
-				rx_ptr=&(s->inverter.rxStruct.DCinputA_power);
-			}
-			else if(fsmStruct->requestTelegramNr==2)  {
-				rx_ptr=&(s->inverter.rxStruct.DCinputB_power);
-			}
-			else if(fsmStruct->requestTelegramNr==3)  {
-				// not valid anymore
-				rx_ptr=&(s->inverter.rxStruct.DCinputA_power);
-			}
-			else {
-				// not valid anymore
-				rx_ptr=&(s->inverter.rxStruct.DCinputB_power);
-			}
-			if(CAN1_wait_for_response(rx_ptr) == TRUE ) {	
-				fsmStruct->requestTelegramNr++;
-				fsmStruct->receivedTelegrams++;
-				if(fsmStruct->requestTelegramNr >=CAN1_NR_OF_REQUEST_TELEGRAMS) {
-					fsmStruct->fsmState=CAN1_FSM_SEND_HIGH_PRIO_DATA;
-					fsmStruct->timeoutCyclesCnt=0;
-					s->inverterState.inverterCanOnline= TRUE;
-					return TRUE;
-				}
-				else {
-					fsmStruct->fsmState=CAN1_FSM_SEND_REQUEST_DATA;
-					fsmStruct->timeoutCyclesCnt=0;
-					s->inverterState.inverterCanOnline= TRUE;
-					return TRUE;				
-				}
-			}
-			else{
-				fsmStruct->timeoutCyclesCnt++;
-			}
-			
-			if(fsmStruct->timeoutCyclesCnt >5) {
-				// timeout
-				fsmStruct->receivedTelegrams=0;
-				//fsmStruct->timeoutCyclesCnt=0;
-				
-				// set Error
-				BMS_Set_Error_CAN1_Timeout(s) ;
-				// set inverter fsm to can out 
-				s->inverterState.inverterCanOnline= FALSE;
-				fsmStruct->fsmState=CAN1_FSM_SEND_HIGH_PRIO_DATA;
-				return TRUE;
-			}
-				// wait another 10ms for response
-			return TRUE;
-		break;
-		default :
-			// you should not be here	
-			return FALSE;
-		break;
-			
-	}
-}
-
-/*
- * @brief generate a pkg with value ID (32bit) Cell Index (8-bit) voltage (16 bit) temperature (8-bit)
- */
-uint32_t generateCellInfoPkg(MASTER_CAN0_STRUCT_t* s, uint8_t cellIndex,BMS_CAN1_INVERTER_CELL_DATA_t* txPkg) {
-	// collect information
-	int8_t cellTemp;
-	uint16_t cellVoltage;
-	uint8_t SlaveNr;
-	uint8_t cellNr;
-	uint8_t payload[4];
-	
-	
-	uint32_t valueId=CAN1_TX_CELL_STATUS;
-	
-	// shuffle Bits for correct Order
-	shuffle_lsb_msb_can1((uint8_t*)&valueId);
-	
-	SlaveNr = cellIndex/ (MAX_SLAVE_CELLS); // Slave Nr 0...14
-	cellNr = cellIndex - SlaveNr * MAX_SLAVE_CELLS ;// cellNr 0... 24
-	
-	cellVoltage = s->Slave[SlaveNr].CellVoltage[cellNr];
-	
-	if(s->Slave[SlaveNr].TempSensConnectionState[cellNr] == TEMP_SENSOR_CONNECTED) {
-		cellTemp = s->Slave[SlaveNr].CellTemp[cellNr] ;
-	}
-	else {
-		// if temp sensor not connected transmit -51 deg
-		cellTemp = -51 ;
-	}
-	payload[0]=cellIndex;
-	payload[1]= cellVoltage >> 8;
-	payload[2]= cellVoltage & 0xFF;
-	payload[3]= (uint8_t)cellTemp;
-	
-	shuffle_lsb_msb_can1((uint8_t*)&(payload[0]));
-	
-	txPkg->valueId=valueId;
-	txPkg->payload= (payload[0] << 24) + (payload[1] << 16) + (payload[2] << 8) + payload[3] ;
-}
-
-
-uint32_t Master_Balancer_fsm(MASTER_CAN0_STRUCT_t* s) {
-	switch(s->balancerState) {
-		case BMS_BALANCE_INIT:
-				if(s->allValuesInitialized== TRUE && (s->maxCellVoltage >=BMS_SLAVE_MAX_BALANCE_VOLTAGE)) {
-					// cellvoltage of system too high => no Balancing
-					s->balancerState=BMS_BALANCE_OFF;
-				}
-				else if(s->SoC_estimator.SoC_percentage_smooth <= BMS_SLAVE_MIN_BALANCE_SOC) {
-					// SoC under 80% do not balance
-					s->balancerState=BMS_BALANCE_OFF;
-				}
-				else if(s->maxHeatSinkTemp >= BMS_SLAVE_MAX_BALANCE_HEATSINK_TEMP) {
-					// Heatsink too hot => do not balance
-					s->balancerState=BMS_BALANCE_OFF;
-				}
-				else if(s->allValuesInitialized== TRUE && (s->UI_Board.Ibatt > BMS_SLAVE_BATTERY_CHARGE_THERESOLD) ) {
-					// battery discharging => no Balancing
-					s->balancerState=BMS_BALANCE_OFF;
-				}
-				else if(s->allValuesInitialized== TRUE && (s->UI_Board.Ibatt < BMS_SLAVE_BATTERY_CHARGE_THERESOLD)) {
-					// ready for balancing
-					s->balancerState=BMS_BALANCE_GET_VOLTAGE;
-				}
-
-				else {
-					// do nothing
-				}
-			
-			return TRUE;
-		break;
-		case BMS_BALANCE_GET_VOLTAGE:
-				// decide Which cells to balance
-				if(s->UI_Board.Ibatt < BMS_SLAVE_BATTERY_CHARGE_THERESOLD) {
-					set_balancer(s);
-					s->balancerState=BMS_BALANCE_BALANCE_CELLS;
-				}
-				else {
-					set_balancer_off(s) ;
-					s->balancerState=BMS_BALANCE_OFF;
-				}
-			return TRUE;
-		break;
-		case BMS_BALANCE_BALANCE_CELLS:
-			// turn off balancing to obtain uneffected cell voltages	
-			if(s->UI_Board.Ibatt < BMS_SLAVE_BATTERY_CHARGE_THERESOLD) {
-				set_balancer_off(s) ;
-				s->balancerState=BMS_BALANCE_COOL;
-			}
-			else {
-				set_balancer_off(s) ;
-				s->balancerState=BMS_BALANCE_OFF;
-			}
-			return TRUE;
-		break;
-		case BMS_BALANCE_COOL:
-			// uneffected cell voltages are now available
-			if(s->UI_Board.Ibatt < BMS_SLAVE_BATTERY_CHARGE_THERESOLD) {
-				s->balancerState=BMS_BALANCE_INIT;
-			}
-			else {
-				set_balancer_off(s) ;
-				s->balancerState=BMS_BALANCE_OFF;
-			}			
-			return TRUE;
-		break;
-		case BMS_BALANCE_OFF:
-				set_balancer_off(s) ;
-			if(s->UI_Board.Ibatt < BMS_SLAVE_BATTERY_CHARGE_THERESOLD) {
-				s->balancerState=BMS_BALANCE_INIT;
-			}	
-			s->balancerState=BMS_BALANCE_INIT;
-			return TRUE;
-		break;	
-		
-			
-	
-	}
-	
-}
-
-uint8_t get_nr_of_connected_slaves(MASTER_CAN0_STRUCT_t* s){
-	uint8_t i=0;
-	uint8_t nr=0;
-	for(i=0;i<CAN0_MAX_NR_OF_SLAVES-1;i++) {
-		if(s->Slave[i].SlaveConnectionState== CONNECTED) {
-			nr++;
-		}
-	}
-	return nr;
-}
-
-uint32_t RunningModeFSM(MASTER_CAN0_STRUCT_t* s){
-
-	
-	// check for active Error States
-	if(ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_3) || s->RunMode.ErrorState3fsm != ES3_FSM_INIT) {
-		// handle Error Class 3
-		BMS_Master_ES3_fsm(s);
-		return TRUE;
-	}
-	else if(ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_2) || s->RunMode.ErrorState2fsm != ES2_FSM_INIT) {
-		// handle Error Class 2
-		BMS_Master_ES2_fsm(s);
-		return TRUE;
-	}
-	else if(ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_1) || s->RunMode.ErrorState1fsm != ES1_FSM_INIT) {
-		// handle Error Class 1
-		BMS_Master_ES1_fsm(s);
-		return TRUE;
-	}
-	
-	else {
-		// normal operation
-		OPModeFSM( s );
-	return TRUE;
-	}
-
-}
-
-uint32_t OPModeFSM(MASTER_CAN0_STRUCT_t* s){
-	float SoC=s->SoC_estimator.SoC_percentage_smooth;
-	switch(s->RunMode.OperationMode) {
-		case OP_MODE_INIT:
-			// just jump to checkup startup conditions
-			s->RunMode.OperationMode=OP_MODE_CHECK_STARTUP_CONDITIONS;
-			
-			CLEAR_OUTPIN(PIN_REGNR_LED4);
-			return TRUE;
-		break;
-		case OP_MODE_CHECK_STARTUP_CONDITIONS:
-			if(s->allValuesInitialized==TRUE) {
-				// all values initalized and no error occured
-				// => Startup conditions apply => start startup
-				s->RunMode.OperationModeTimestamp=Global_1msCounter;
-				s->RunMode.OperationMode=OP_MODE_SET_PRECHARGE_RELAY;
-				s->RunMode.onCounter=0;
-				return TRUE;
-			}
-			else {
-				// wait till all values are initialiezd
-				s->RunMode.OperationMode=OP_MODE_CHECK_STARTUP_CONDITIONS;
-				return TRUE;
-			}
-		break;
-		case OP_MODE_SET_PRECHARGE_RELAY:
-			// set Low Side and Precharge Relais
-			s->relayState.LS_closed=TRUE;
-			s->relayState.PRECHARGE_closed=TRUE;
-			SwitchRelais( LS_RELAIS, 1);
-			SwitchRelais( PRE_CHARGE_RELAIS, 1);			
-			if(s->RunMode.OperationModeTimestamp + 3000 <= Global_1msCounter) {
-				s->RunMode.OperationMode=OP_MODE_SET_MAIN_RELAY;
-				return TRUE;
-			}
-			else {
-				s->RunMode.OperationMode= OP_MODE_SET_PRECHARGE_RELAY;
-				return TRUE;
-			}
-		break;
-		case OP_MODE_SET_MAIN_RELAY:
-			// Switch Highside relais
-			SwitchRelais( HS_RELAIS, 1);
-			s->relayState.HS_closed=TRUE;
-			s->RunMode.OperationMode=OP_MODE_NORMAL;
-			return TRUE;
-		break;
-		case OP_MODE_NORMAL:
-			// do nothing until SoC becomes low
-			s->RunMode.onCounter++;
-			if ( SoC < BMS_SOC_LOW_MARK) {
-				s->RunMode.OperationMode=OP_MODE_SOC_LOW;
-				return TRUE;
-			}
-			else {
-				s->RunMode.OperationMode=OP_MODE_NORMAL;
-				return TRUE;
-			}				
-			return TRUE;
-		break;
-		case OP_MODE_SOC_LOW:
-			s->RunMode.onCounter++;
-			// do nothing until SoC becomes high again
-			if ( SoC > BMS_SOC_LOW_MARK) {
-				s->RunMode.OperationMode=OP_MODE_NORMAL;
-				return TRUE;
-			}
-			else {
-				s->RunMode.OperationMode=OP_MODE_SOC_LOW;
-				return TRUE;
-			}	
-		break;	
-		default:
-			// something went horribly wrong
-			return FALSE;
-		break;
-	}
-	
-}
-/*
- * @brief Statemachine which handles Class 1 Errors
- */
-
-uint32_t BMS_Master_ES1_fsm(MASTER_CAN0_STRUCT_t* s){
-	switch (s->RunMode.ErrorState1fsm) {
-		case ES1_FSM_INIT:
-			s->RunMode.ErrorState1fsm=ES1_FSM_CHECK_IF_ERROR_VALID;
-			return TRUE;
-		break;
-		case ES1_FSM_CHECK_IF_ERROR_VALID:
-			// Try to clear Error
-			BMS_Clear_Error_Buffer(s,BMS_ERROR_CLASS_1);
-
-			
-			if(ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_1)) {
-				// Error still active
-				// Don't do anything
-				
-			}
-			else {
-				// No Error
-				s->RunMode.ErrorState1fsm=ES1_FSM_ERROR_REVOKED;
-			}
-			return TRUE;
-		break;
-		case ES1_FSM_ERROR_REVOKED:
-			// No More Errors apply startup system again
-			s->RunMode.OperationMode=OP_MODE_INIT;
-			// set Fsm Back to INIT
-			s->RunMode.ErrorState1fsm=ES1_FSM_INIT;
-			return TRUE;
-		break;
-	}
-}
-
-uint32_t BMS_Master_ES2_fsm(MASTER_CAN0_STRUCT_t* s){
-	switch(s->RunMode.ErrorState2fsm) {
-		case ES2_FSM_INIT:
-			// save time for Timeout timer
-			s->RunMode.ErrorState2Timestamp=Global_1msCounter;
-			if(s->ErrorBuffer.ES2_New_Error==FALSE) {
-				// System had power cycle, Try to fix Error
-				s->RunMode.ErrorState2fsm=ES2_FSM_CHECK_IF_ERROR_VALID;
-			}
-			else {
-				// no restart => wait timeout then kill system
-				s->RunMode.ErrorState2fsm=ES2_FSM_WAIT_FOR_SHUTDOWN;
-			}
-			return TRUE;
-		break;
-		case ES2_FSM_CHECK_IF_ERROR_VALID:
-			// Try to clear Error
-			BMS_Clear_Error_Buffer(s,BMS_ERROR_CLASS_2);
-			if(!ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_2)) {
-				// all Errors cleared
-				s->RunMode.ErrorState2fsm=ES2_FSM_ERROR_REVOKED;
-			}
-			else if(s->RunMode.ErrorState2Timestamp + BMS_ERROR_FSM_ES2_TIMEOUT < Global_1msCounter ) {
-				// Timeout shutdown system
-				s->RunMode.ErrorState2fsm=ES2_FSM_SYSTEM_SHUTDOWN;
-			}
-			else{
-				// do nothing an wait for timeout or error to be cleared
-			}
-			return TRUE;
-		break;
-		case ES2_FSM_WAIT_FOR_SHUTDOWN:
-			// wait timeout
-			if(s->RunMode.ErrorState2Timestamp + BMS_ERROR_FSM_ES2_TIMEOUT < Global_1msCounter ) {
-				// timeout
-				s->RunMode.ErrorState2fsm=ES2_FSM_SYSTEM_SHUTDOWN;
-				return TRUE;
-			}
-			else {
-				// wait and do nothing
-				return TRUE;
-			}
-			return TRUE;
-		break;
-		case ES2_FSM_ERROR_REVOKED:
-			// no more Errors in the system => Start normal Operation again
-			s->RunMode.ErrorState2fsm=ES2_FSM_INIT;
-			s->RunMode.OperationMode=OP_MODE_INIT;
-			return TRUE;
-		break;
-		case ES2_FSM_SYSTEM_SHUTDOWN:
-			// Turn off power Supply
-			SwitchRelais( PWR_SUPPLY, 1);
-			// now System should be dead
-			while (1) {
-				// loop for ever
-				SwitchRelais( PWR_SUPPLY, 1);
-			}
-			
-			break;
-		return TRUE;
-	}
-}
-
-/*
- * @brief handle error class 3
- * Todo System repair tool not implemented yet
- */
-uint32_t BMS_Master_ES3_fsm(MASTER_CAN0_STRUCT_t* s) {
-	switch(s->RunMode.ErrorState3fsm){
-		case ES3_FSM_INIT:
-			// save timestamp for timeout
-			s->RunMode.ErrorState3Timestamp=Global_1msCounter;
-			s->RunMode.ErrorState3fsm=ES3_FSM_CONNECT_TO_SERVICE_TOOL;
-			return TRUE;
-		break;
-		case ES3_FSM_CONNECT_TO_SERVICE_TOOL:
-			// not fully implemented yet
-			// just shut down system after timeout
-			if(s->RunMode.ErrorState3Timestamp + BMS_ERROR_FSM_ES3_TIMEOUT < Global_1msCounter ) {
-				// Shut down System
-				s->RunMode.ErrorState3fsm=ES3_FSM_SYSTEM_SHUTDOWN;
-			}
-			else {
-				// wait
-			}
-			return TRUE;
-		break;
-		case ES3_FSM_SYSTEM_SHUTDOWN:
-			// Turn off power Supply
-			SwitchRelais( PWR_SUPPLY, 1);
-			// now System should be dead
-			while (1) {
-				// loop for ever
-				SwitchRelais( PWR_SUPPLY, 1);
-			}
-			return TRUE;
-		break;
-			
-	
-	}
-}
-
-/*
- * @brief check if connected Inverter has enough power to charge battery and recover from Wintermode 
- */
-
-int32_t checkIfInverterHasPower(MASTER_CAN0_STRUCT_t* s) {
-	if((s->inverter.rxStruct.expectedInputPower) > BMS_WINTER_MODE_RECOVER_PWR) {
-		return TRUE;
-	}
-	else {
-		return FALSE;
-	}
-}
-
-/*
- * @brief read Temp sensor on master Board
- */
-uint32_t readMasterTempSensorFsm(MASTER_CAN0_STRUCT_t* s) {
-	switch(s->MasterTempSensState) {
-		case BMS_MASTER_TEMP_SENSOR_INITIATE_MEASUREMENT:
-			//  trigger measurement
-			if(TempMess_triggerRead() == 0) {
-				// measurement triggered got to next state
-				s->MasterTempSensState=BMS_MASTER_TEMP_SENSOR_UPDATE_MEASUREMENT;
-			}
-			return TRUE;
-		break;
-		case BMS_MASTER_TEMP_SENSOR_UPDATE_MEASUREMENT:
-			TempMess_update();
-			if(TempMess_poll_Value(&(s->masterTemp)) == 0) {
-				// readout succesfull go back to triggering measurement
-				s->MasterTempSensState=BMS_MASTER_TEMP_SENSOR_INITIATE_MEASUREMENT;
-			}
-			return TRUE;
-		break;
-	}
-}
-
-/*
- * @brief clear fifos 
- */
-
-uint32_t initUIFifo(MASTER_CAN0_STRUCT_t* s) {
-	uint8_t i;
-	for(i=0;i<UI_VOLTAGE_FIFO_SIZE;i++) {
-		s->UI_Board.UbattFiFo[i]=0;
-		s->UI_Board.SystemVoltageFiFo[i]=0;
-	}
-	for(i=0;i<UI_CURRENT_FIFO_SIZE;i++) {
-		s->UI_Board.IbattFiFo[i]=0;
-		s->UI_Board.Ibatt_Inverter_FIFO[i]=0;
-	}
-	return TRUE;
-}
-
-uint32_t popUIFiFo(MASTER_CAN0_STRUCT_t* s) {
-	uint8_t i;
-	
-	for(i=UI_VOLTAGE_FIFO_SIZE-1;i>0;i--) {
-		s->UI_Board.UbattFiFo[i]=s->UI_Board.UbattFiFo[i-1];
-	}
-	s->UI_Board.UbattFiFo[0]=s->UI_Board.Ubatt;
-	
-	for(i=UI_VOLTAGE_FIFO_SIZE-1;i>0;i--) {
-		s->UI_Board.SystemVoltageFiFo[i]=s->UI_Board.SystemVoltageFiFo[i-1];
-	}
-	s->UI_Board.SystemVoltageFiFo[0]=(s->systemVoltage);
-	
-	for(i=UI_CURRENT_FIFO_SIZE-1;i>0;i--) {
-		s->UI_Board.IbattFiFo[i]=s->UI_Board.IbattFiFo[i-1];
-	}
-	s->UI_Board.IbattFiFo[0]=s->UI_Board.Ibatt;
-}
-
-uint32_t pushInverterCurrentFIFO(MASTER_CAN0_STRUCT_t* s) {
-	uint8_t i;
-	for(i=UI_CURRENT_FIFO_SIZE-1;i>0;i--) {
-		s->UI_Board.Ibatt_Inverter_FIFO[i]=s->UI_Board.Ibatt_Inverter_FIFO[i-1];
-	}
-	s->UI_Board.Ibatt_Inverter_FIFO[0]=s->inverter.rxStruct.batteryCurrent;
-	
-//	if(s->inverter.rxStruct.batteryCurrent > 100 ||  s->inverter.rxStruct.batteryCurrent < -100) {
-//		// fake value
-//		i++ ; // break here
-//	}
-	return TRUE;
-}
-
-
-// *** End BMS_Master.c ******************************************************
+//##############################################################################
+//
+// FILE:	BMS_Master.c
+//
+// TITLE:	Functions of BMS_Master
+//            void		BMS_Init_BSD	( void );
+//            void		BMS_Init_BSE	( void );
+//            void		SwitchRelais	( uint8_t, uint8_t );
+//            void		SetBalancer		( void );
+//	          uint16_t	BMS_Do			( void );
+//
+//
+//##############################################################################
+
+//==============================================================================
+// Historie:
+//==============================================================================
+// Datum:   | Name | Version:| Aenderungsgrund:                          | rev.:
+//------------------------------------------------------------------------------
+//          |  SB  | 2.1    |  Implementaion of Balancing and SoC Estimator                                         | 003   
+//------------------------------------------------------------------------------
+//          |  SB  |  2.0   | Adaptation for RCT	                                           | 002   
+//------------------------------------------------------------------------------
+// 01.07.13 |  VR  |   1.1   | Rearrange Code for IAA Bus                | 001 
+//------------------------------------------------------------------------------
+// 20.04.10 |  TM  |   1.0   | Start Code for Master Test                | 000
+//==============================================================================
+
+#include "BMS_Master.h"
+
+
+
+// ***** Global Data ***********************************************************
+extern uint64_t 	Global_1msCounter; 
+extern BSE_t		gBSE;
+extern BSD_t		gBSD;
+
+
+
+
+
+
+// ***** SwitchRelais **********************************************************
+void SwitchRelais( uint8_t Relais, uint8_t OnOff )
+{
+	if( Relais == LS_RELAIS )
+	{
+		if(OnOff)
+			SET_OUTPIN( PIN_REGNR_RELAIS_SLAVE );
+		else
+			CLEAR_OUTPIN( PIN_REGNR_RELAIS_SLAVE);
+	}
+	
+	if( Relais == HS_RELAIS)
+	{
+		if(OnOff) {
+			SET_OUTPIN( PIN_REGNR_RELAIS_PLUS );
+			SET_OUTPIN(PIN_REGNR_LED3);
+		}
+		else{
+			CLEAR_OUTPIN( PIN_REGNR_RELAIS_PLUS );
+			CLEAR_OUTPIN(PIN_REGNR_LED3);
+		}
+	}
+	
+	if( Relais == PRE_CHARGE_RELAIS )
+	{
+		if(OnOff)
+			SET_OUTPIN( PIN_REGNR_RELAIS_PRECHA );
+		else
+			CLEAR_OUTPIN( PIN_REGNR_RELAIS_PRECHA );
+	}
+	if( Relais ==PWR_SUPPLY ) {
+		if(OnOff)
+			SET_OUTPIN( PIN_REGNR_PWR_SUPPLY );
+		else
+			CLEAR_OUTPIN( PIN_REGNR_PWR_SUPPLY );
+	}
+
+}
+
+
+
+
+
+
+
+
+
+uint16_t init_master_CAN0_fsm(MASTER_CAN0_STRUCT_t* s,BMS_SLAVE_CONFIGURATION_t* cellConfig,BMS_UI_CONFIGURATION_t* uiConfig) {
+	uint8_t slaveNr;
+	uint8_t i;
+	uint16_t stateActive;
+	//go thought all connected Slaves
+	for(slaveNr=0;slaveNr<CAN0_MAX_NR_OF_SLAVES-1;slaveNr++) {
+			
+			// set slave Type
+			s->Slave[slaveNr].SlaveType=cellConfig[slaveNr].type;
+			s->Slave[slaveNr].TxMailbox_ptr=MB_Container[slaveNr];
+			s->Slave[slaveNr].TxTelegram_ptr=&TelegramTxContainer[slaveNr];
+			s->Slave[slaveNr].SlaveConnectionState=cellConfig[slaveNr].connectionSate;
+			
+			// set initial Voltage and Temp value to 0xffff = not initialzied
+			
+			for(i=0;i<MAX_SLAVE_CELLS;i++) {
+				s->Slave[slaveNr].CellVoltage[i]=0xffff;
+				s->Slave[slaveNr].CellTemp[i]=-51;
+				s->Slave[slaveNr].CellConnectionState[i]=cellConfig[slaveNr].cellConnectionState[i];
+				s->Slave[slaveNr].TempSensConnectionState[i]=cellConfig[slaveNr].tempSensConnectionState[i];
+			}
+			s->Slave[slaveNr].HeatSinkTemp=-51;
+			
+			// set slave alive cnt to 0xff fot not initialized
+			for(i=0;i<CAN0_NR_OF_TELEGRAMS;i++) {
+				s->Slave[slaveNr].SlaveAliveCnt[i]=0xff;
+			}
+			
+			// set slave Status to 0xff for Not initialized
+			s->Slave[slaveNr].SlaveMode=0xff;
+			// no Errors
+			s->Slave[slaveNr].SlaveError =0 ;
+			
+			// first State Running mode
+			s->Slave[slaveNr].Set_Mode = BMS_SLAVE_RUN ;
+			// No Balancing
+			s->Slave[slaveNr].Balance_Cell_0_7=0;
+			s->Slave[slaveNr].Balance_Cell_8_15=0;
+			s->Slave[slaveNr].Balance_Cell_16_23=0;
+			
+			// set Slave Error to 0
+			s->Slave[slaveNr].SlaveCanCommuniationError.FailedComCnt=0;
+			s->Slave[slaveNr].SlaveCanCommuniationError.SlaveErrorCounterRegister=0;
+			s->Slave[slaveNr].SlaveCanCommuniationError.SlaveErrorStateRegister=0;
+			s->Slave[slaveNr].SlaveCanCommuniationError.WrongAliveCnt=0;
+			
+			s->Slave[slaveNr].MasterAliveCnt=0;
+			s->Slave[slaveNr].maxCellTemp=0;
+			s->Slave[slaveNr].minCellTemp=0;			
+		}
+	
+	// init UI
+	
+	s->Slave[15].SlaveType=uiConfig->type;
+	s->Slave[15].TxMailbox_ptr=MB_Container[15];
+	s->Slave[15].TxTelegram_ptr=&TelegramTxContainer[15];
+	s->Slave[15].SlaveConnectionState=uiConfig->connectionSate;
+	
+	s->Slave[15].SlaveMode=0xff;
+	// no Errors
+	s->Slave[15].SlaveError =0 ;
+	
+	// first State Running mode
+	s->Slave[15].Set_Mode = BMS_SLAVE_RUN ;
+
+	
+	// set Slave Error to 0
+	s->Slave[15].SlaveCanCommuniationError.FailedComCnt=0;
+	s->Slave[15].SlaveCanCommuniationError.SlaveErrorCounterRegister=0;
+	s->Slave[15].SlaveCanCommuniationError.SlaveErrorStateRegister=0;
+	s->Slave[15].SlaveCanCommuniationError.WrongAliveCnt=0;
+	
+		
+	// set State to INIT
+	s->FsmState=INIT;
+	s->slaveSelect=0;
+	s->transmission_pending=FALSE;
+	s->cycleCounter=0;
+	s->cycleTimestamp=0;
+	s->StateOfCharge=40*60*60*1000; // 40Ah in mAs
+	s->allValuesInitialized = FALSE;
+	s->startCan1Comm=FALSE;
+	s->balancerState=BMS_BALANCE_INIT;
+	
+
+	s->SoC_initialized=FALSE;
+	s->SoC_outside=0;
+	s->maxHeatSinkTemp=0;
+	s->NrOfSlaves= get_nr_of_connected_slaves(s);
+	
+	s->CAN1_fsmStruct.fsmState=CAN1_FSM_INIT;
+	s->CAN1_fsmStruct.highPrioMsgNr=0;
+	s->CAN1_fsmStruct.lowPrioMsgNr=0;
+	s->CAN1_fsmStruct.requestTelegramNr=0;
+	s->CAN1_fsmStruct.timeoutCyclesCnt=0;
+	s->CAN1_fsmStruct.receivedTelegrams=0;
+	s->CAN1_fsmStruct.fastRequestFsmRunning=FALSE;
+	s->CAN1_fsmStruct.slowRequestFsmRunning=FALSE;
+	s->CAN1_fsmStruct.fastRxState=CAN1_FAST_RX_FSM_REQUEST_BATTERY_CURRENT;
+	s->CAN1_fsmStruct.nrOfRecCurrentSamples=0;
+	
+	s->FsmErrorState=ERROR_INIT;
+	//s->ErrorStack.ErrorNr=0;
+	//s->RunMode=RUN_MODE_INIT;
+	s->ErrorFlags=0;
+	// celar Error Buffers
+	ErrorStackClearBuffer(s); 
+	
+	// set Operation fsms to idle
+	s->RunMode.OperationMode=OP_MODE_INIT;
+	s->RunMode.ErrorState1fsm=ES1_FSM_INIT;
+	s->RunMode.ErrorState2fsm=ES2_FSM_INIT;
+	s->RunMode.ErrorState3fsm=ES3_FSM_INIT;
+	// init master temp sensor
+	s->masterTemp=18;
+	s->MasterTempSensState=BMS_MASTER_TEMP_SENSOR_INITIATE_MEASUREMENT;
+	s->inverterState.state=RCT_INV_INACTIVE;
+	s->inverterState.inverterCanOnline=FALSE;
+	s->inverterState.inverterIsCharging=FALSE;
+	s->inverterState.startupPwr=0;
+	
+	// assign impossible values to be able to check if values have been initialized
+	s->inverter.rxStruct.expectedInputPower=-1;
+	s->inverter.rxStruct.DCinputA_power=-1;
+	s->inverter.rxStruct.DCinputB_power=-1;
+	
+	BMS_Clear_Error_init_recovery_struct(s);//clear recovery struct
+	s->ErrorBuffer.ES2_New_Error=0;
+	s->relayState.HS_closed=0;
+	s->relayState.LS_closed=0;
+	s->relayState.PRECHARGE_closed=0;
+	s->relayState.reseved=0;
+	
+	s->reset_test_timestamp=0;
+
+	BMS_RCT_init_fsm(s);
+	initUIFifo(s);
+}
+	
+
+
+void set_slave_cell_connection_state(MASTER_CAN0_STRUCT_t* s,uint8_t slaveNr,CELL_STATE_t* cell_state){
+	uint8_t i;
+	for(i=0;i<MAX_SLAVE_CELLS;i++) {
+		s->Slave[slaveNr].CellConnectionState[i]=cell_state[i];
+	}
+}
+
+void set_slave_temp_connection_state(MASTER_CAN0_STRUCT_t* s,uint8_t slaveNr,TEMP_SENSOR_STATE_t* temp_state){
+	uint8_t i;
+	for(i=0;i<MAX_SLAVE_CELLS;i++) {
+		s->Slave[slaveNr].TempSensConnectionState[i]=temp_state[i];
+	}
+}
+
+uint8_t check_slave_data(MASTER_CAN0_STRUCT_t* s,
+		BMS_CAN0_SLAVE_t* Slave,
+		BMS_CAN0_SLAVE_t* tempSlave,
+		int8_t overTemp_charge,
+		int8_t overTemp_discharge,
+		int8_t underTemp_charge,
+		int8_t underTemp_discharge,
+		uint16_t overVoltage,uint16_t underVoltage) {
+	uint8_t i;
+	uint8_t error_status=BMS_SLAVE_DATA_OK;
+	uint16_t current=s->UI_Board.Ibatt*10;
+	
+	// Check Slave Mode
+	if(tempSlave->SlaveMode==BMS_SLAVE_RUN) {
+		// everything OK
+		
+		
+		//check Slave Alive Counter
+		
+		//if Failed communication counter is grater than 0  the communication
+		//attempt last Cycle failed and the alive counters are out of sync
+		if(tempSlave->SlaveCanCommuniationError.FailedComCnt>0) {
+			//
+			for(i=0;i<CAN0_NR_OF_TELEGRAMS;i++) {
+				Slave->SlaveAliveCnt[i]=tempSlave->SlaveAliveCnt[i];
+			}
+			tempSlave->SlaveCanCommuniationError.FailedComCnt=0;
+		}
+		//compare all Slave Alive Counter
+		else{
+			for(i=0;i<CAN0_NR_OF_TELEGRAMS;i++) {
+				if(	(tempSlave->SlaveAliveCnt[i] == Slave->SlaveAliveCnt[i] + 1) ||
+					(Slave->SlaveAliveCnt[i] ==0x7 && tempSlave->SlaveAliveCnt[i] ==0) ) {
+					// Slave Alive Counter == OK
+					Slave->SlaveAliveCnt[i]=tempSlave->SlaveAliveCnt[i];
+					Slave->SlaveCanCommuniationError.WrongAliveCnt=0;
+				}
+				else {
+					// slave Alive Counter didn't change or made bigger steps
+				
+					Slave->SlaveCanCommuniationError.WrongAliveCnt++;
+					if(Slave->SlaveCanCommuniationError.WrongAliveCnt>=CAN0_MAX_NR_OF_FAILED_COM) {
+						error_status|=BMS_SLAVE_DATA_ERROR_ALIVE_TIMEOUT;
+						// set CAN ERROR
+						ErrorStackPushMasterError(s,BMS_ERROR_STACK_SLAVE_CAN_ERROR,BMS_ERROR_CLASS_1);
+						return error_status;
+					}
+					for(i=0;i<CAN0_NR_OF_TELEGRAMS;i++) {
+						Slave->SlaveAliveCnt[i]=tempSlave->SlaveAliveCnt[i];
+					}
+					error_status |=BMS_SALVE_DATA_ERROR_ALIVE_CNT;
+					return error_status;
+
+				}
+			}
+		}
+		
+		// check voltages
+		// discard uninitialized values 0xff and Bypassed cells
+		for(i=0;i<MAX_SLAVE_CELLS;i++){
+			if(tempSlave->CellConnectionState[i]==CELL_BYPASSED) {
+				// no cell == no voltage 
+				tempSlave->CellVoltage[i]=0;
+			}
+			else if(tempSlave->CellConnectionState[i]==CELL_CONNECTED && tempSlave->CellVoltage[i]>= 0xfff8 ) {
+				// not initialized cells
+				//TODO decide upon signed unsigned representation
+				// use old value
+				tempSlave->CellVoltage[i]= Slave->CellVoltage[i];
+				
+			}
+			if( (tempSlave->CellVoltage[i] >= overVoltage || tempSlave->CellVoltage[i] <= underVoltage) 
+				&& tempSlave->CellConnectionState[i]==CELL_CONNECTED) {
+				//copy Slave to record current Errors
+				*Slave=*tempSlave;
+				error_status |=BMS_SLAVE_DATA_ERROR_VOLTAGE_LIMIT;
+				
+				// Write Error Stack
+				if(tempSlave->CellVoltage[i] >= overVoltage ) {
+					
+					ErrorStackPushSlaveError(s,s->slaveSelect,BMS_ERROR_STACK_SLAVE_OVER_VOLTAGE,i,BMS_ERROR_CLASS_3);
+					error_status |=BMS_SLAVE_DATA_ERROR_OVER_VOLTAGE;
+				}
+				else {
+					
+					ErrorStackPushSlaveError(s,s->slaveSelect,BMS_ERROR_STACK_SLAVE_UNDER_VOLTAGE,i,BMS_ERROR_CLASS_3);
+					error_status |=BMS_SLAVE_DATA_ERROR_UNDER_VOLTAGE;
+				}
+				
+				return error_status;
+			}
+			
+		}
+		
+		if(tempSlave->HeatSinkTemp >= BMS_ERROR_THRESHOLD_T_HEATSINK_MAX || tempSlave->HeatSinkTemp <= BMS_ERROR_THRESHOLD_T_HEATSINK_MIN){
+			//copy Slave to record current Errors
+			*Slave=*tempSlave;
+			error_status |=BMS_SLAVE_DATA_ERROR_HEAT_SINK_LIMIT;
+			// Write Error Stack
+			if(tempSlave->HeatSinkTemp >= BMS_ERROR_THRESHOLD_T_HEATSINK_MAX  ) {
+				// Has to be defined
+				
+			}
+			else {
+				// has to be defined
+			}
+			return error_status;
+		}
+		
+		//check cell temperatures		
+		for(i=0;i<MAX_SLAVE_CELLS;i++){
+			
+			if (tempSlave->CellTemp[i] > -40) {
+				//toDo: QUICKFIX FOR INITIALIZED SENSORS
+				
+				if(current < -100 ) {
+					// battery is charged
+					if( (tempSlave->CellTemp[i] >= overTemp_charge || tempSlave->CellTemp[i] <= underTemp_charge) 
+						&& tempSlave->TempSensConnectionState[i] ==TEMP_SENSOR_CONNECTED) {
+						//copy Slave to record current Errors
+						*Slave=*tempSlave;
+						error_status |=BMS_SLAVE_DATA_ERROR_TEMP_LIMIT;
+						
+						// Write Error Stack
+						if(tempSlave->CellTemp[i] >= overTemp_charge  ) {
+							ErrorStackPushSlaveError(s,s->slaveSelect,BMS_ERROR_STACK_SLAVE_OVER_TEMP_CHARGE,i,BMS_ERROR_CLASS_3);
+							
+						}
+						else {
+							ErrorStackPushSlaveError(s,s->slaveSelect,BMS_ERROR_STACK_SLAVE_UNDER_TEMP_CHARGE,i,BMS_ERROR_CLASS_3);
+						}
+						return error_status;
+					}	
+				}
+				else {
+					// battery is discharged
+					if( (tempSlave->CellTemp[i] >= overTemp_discharge || tempSlave->CellTemp[i] <= underTemp_discharge) 
+						&& tempSlave->TempSensConnectionState[i] ==TEMP_SENSOR_CONNECTED) {
+						//copy Slave to record current Errors
+						*Slave=*tempSlave;
+						error_status |=BMS_SLAVE_DATA_ERROR_TEMP_LIMIT;
+						
+						// Write Error Stack
+						if(tempSlave->CellTemp[i] >= overTemp_discharge  ) {
+							ErrorStackPushSlaveError(s,s->slaveSelect,BMS_ERROR_STACK_SLAVE_OVER_TEMP_DISCHARGE,i,BMS_ERROR_CLASS_3);
+							
+						}
+						else {
+							ErrorStackPushSlaveError(s,s->slaveSelect,BMS_ERROR_STACK_SLAVE_UNDER_TEMP_DISCHARGE,i,BMS_ERROR_CLASS_3);
+						}
+						return error_status;
+					}						
+				}
+			}
+		}
+		
+
+	
+		*Slave=*tempSlave;
+		return error_status; //everything should be ok
+	}
+}
+
+uint8_t check_UI_data(BMS_CAN0_SLAVE_t* Slave, BMS_CAN0_SLAVE_t* tempSlave,BMS_CAN0_UI_t* ui,BMS_CAN0_UI_t* tempUI) {
+	// todo Check Alive Cnt
+	// Check Over current etc
+	uint8_t i=0;
+	
+	if(tempUI->Ibatt > 50) {
+		i++;
+	}
+	
+	ui->Ubatt=tempUI->Ubatt;
+	ui->Ibatt=tempUI->Ibatt;
+	ui->Checksum=tempUI->Checksum;
+	return BMS_SLAVE_DATA_OK;
+}
+
+/**
+ * @brief calculate Voltage of Slave Board By adding cell voltages
+ */
+uint32_t calc_block_voltage(BMS_CAN0_SLAVE_t* Slave) {
+	uint32_t blockVoltage=0;
+	uint8_t i=0;
+	for(i=0;i<MAX_SLAVE_CELLS;i++) {
+		if(Slave->CellConnectionState[i]==CELL_CONNECTED) {
+			blockVoltage += Slave->CellVoltage[i];
+		}
+	}
+	return blockVoltage;
+}
+
+/**
+ * @brief calculate min and Max Voltage of Block
+ */
+uint32_t calc_min_max_voltage_slave(BMS_CAN0_SLAVE_t* Slave) {
+	uint16_t minV=Slave->CellVoltage[0];
+	uint16_t maxV=Slave->CellVoltage[0];
+	uint8_t i=0;
+	for(i=0;i<MAX_SLAVE_CELLS;i++) {
+		if(Slave->CellConnectionState[i]==CELL_CONNECTED) {
+			if(minV >= Slave->CellVoltage[i]) {
+				minV = Slave->CellVoltage[i];	
+			}
+			if(maxV <= Slave->CellVoltage[i]) {
+				maxV = Slave->CellVoltage[i];	
+			}			
+		}
+
+	}
+	Slave->minCellVoltage=minV;
+	Slave->maxCellVoltage=maxV;
+	return TRUE;
+}
+
+/**
+ * @brief calculate min and Max Voltage of System
+ */
+uint32_t calc_min_max_voltage_system(MASTER_CAN0_STRUCT_t* s) {
+	uint8_t slave_nr=0;
+	uint16_t minV=BMS_SLAVE_MAX_CELL_VOLTAGE;
+	uint16_t maxV=BMS_SLAVE_MIN_CELL_VOLTAGE;
+	BMS_CAN0_SLAVE_t* Slave;
+	for(slave_nr=0;slave_nr<CAN0_MAX_NR_OF_SLAVES -1 ;slave_nr++) {
+		if(s->Slave[slave_nr].SlaveConnectionState != NOT_CONNECTED ) {
+			//slave is connected
+			Slave=&(s->Slave[slave_nr]);
+			if(Slave->maxCellVoltage >=maxV ) {
+				maxV = Slave->maxCellVoltage;
+			}
+			if(Slave->minCellVoltage <= minV) {
+				minV = Slave->minCellVoltage;
+			}
+		}
+	}
+	s->minCellVoltage=minV;
+	s->maxCellVoltage=maxV;
+	return TRUE;
+}
+
+/*
+ * set balancing register for cell_nr 
+ */
+uint32_t balance_cell(BMS_CAN0_SLAVE_t* Slave,uint8_t cell_nr) {
+	if( cell_nr <8) {
+		Slave->Balance_Cell_0_7|= (1<<cell_nr);
+		return TRUE;
+	}
+	else if(cell_nr <16) {
+		Slave->Balance_Cell_8_15|=(1<<(cell_nr-8));
+		return TRUE;
+	}
+	else {
+		Slave->Balance_Cell_16_23|=(1<<(cell_nr-16));
+		return TRUE;		
+	}
+	
+	return FALSE;
+}
+
+/**
+ * go though all slaves, destinguish slaves to balance and set Balancearray
+ */
+uint32_t set_balancer(MASTER_CAN0_STRUCT_t* s) {
+	uint8_t slave_nr=0;
+	uint8_t cell_nr=0;
+	BMS_CAN0_SLAVE_t* Slave;
+	
+	for(slave_nr=0;slave_nr < CAN0_MAX_NR_OF_SLAVES -1 ;slave_nr++) {	// -1 because slave 15 is UI
+		if(s->Slave[slave_nr].SlaveConnectionState != NOT_CONNECTED) {
+			// slave is connected
+			Slave=&(s->Slave[slave_nr]);
+			
+			
+			if(Slave->maxCellVoltage - s->minCellVoltage > SLAVE_BALANCE_MIN_DELTA_U_MV) {
+				// blancing neccessay
+				for(cell_nr=0;cell_nr <MAX_SLAVE_CELLS;cell_nr++) {
+					if(Slave->CellConnectionState[cell_nr]==CELL_CONNECTED) {
+						// cell is connected
+						if(Slave->CellVoltage[cell_nr] - s->minCellVoltage > SLAVE_BALANCE_MIN_DELTA_U_MV) {
+							// cell has to be balanced
+							balance_cell(Slave,cell_nr);
+						}
+					}
+				}
+			}
+			else {
+				// no need to balance				
+			}
+
+		}
+		
+	}
+	
+}
+
+/**
+ * set all balance registers to off
+ */
+uint32_t set_balancer_off(MASTER_CAN0_STRUCT_t* s) {
+	uint8_t slave_nr=0;
+	BMS_CAN0_SLAVE_t* Slave;
+	for(slave_nr=0;slave_nr < CAN0_MAX_NR_OF_SLAVES -1 ;slave_nr++) {
+		Slave=&(s->Slave[slave_nr]);
+		Slave->Balance_Cell_0_7=0;
+		Slave->Balance_Cell_16_23=0;
+		Slave->Balance_Cell_8_15=0;		
+	}
+	return TRUE;
+}
+
+
+/**
+ * @brief set min and Max Cell Temperature
+ *  */
+
+uint32_t set_block_min_max_temp(BMS_CAN0_SLAVE_t* Slave){
+	uint8_t	i;
+	int8_t maxTemp=25;
+	int8_t minTemp=25;
+	for(i=0;i<MAX_SLAVE_CELLS;i++) {
+		if(Slave->TempSensConnectionState[i]==TEMP_SENSOR_CONNECTED){
+			if(Slave->CellTemp[i] > maxTemp) {
+				maxTemp=Slave->CellTemp[i];
+			}
+			if(Slave->CellTemp[i] < minTemp) {
+				minTemp=Slave->CellTemp[i];
+			}
+		}
+	}
+	Slave->maxCellTemp=maxTemp;
+	Slave->minCellTemp=minTemp;
+}
+
+/**
+ * @brief set min and Max Cell Temperature of System
+ *  */
+
+uint32_t set_system_min_max_temp(MASTER_CAN0_STRUCT_t* s){
+	uint8_t	i;
+	int8_t maxTemp=25;
+	int8_t minTemp=25;
+	BMS_CAN0_SLAVE_t* Slave;
+	
+	for(i=0;i<CAN0_MAX_NR_OF_SLAVES;i++) {
+		if(s->Slave[i].SlaveConnectionState!=NOT_CONNECTED && s->Slave[i].SlaveType == SLAVE) {
+			Slave=&(s->Slave[i]);
+			if(Slave->maxCellTemp > maxTemp) {
+				maxTemp=Slave->maxCellTemp;
+			}
+			if(Slave->minCellTemp < minTemp) {
+				minTemp=Slave->minCellTemp;
+			}
+		}
+	}
+	s->maxCellTemp=maxTemp;
+	s->minCellTemp=minTemp;
+}
+
+uint32_t set_system_min_max_heatsink_temp(MASTER_CAN0_STRUCT_t* s) {
+	uint8_t i;
+	int8_t maxTemp=25;
+	int8_t minTemp=25;
+	BMS_CAN0_SLAVE_t* Slave;
+	
+	for(i=0;i<CAN0_MAX_NR_OF_SLAVES;i++) {
+		if(s->Slave[i].SlaveConnectionState!=NOT_CONNECTED &&s->Slave[i].SlaveType == SLAVE) {
+			Slave=&(s->Slave[i]);
+			if(Slave->HeatSinkTemp > maxTemp) {
+				maxTemp=Slave->HeatSinkTemp;
+			}
+			if(Slave->HeatSinkTemp < minTemp) {
+				minTemp=Slave->HeatSinkTemp;
+			}
+		}
+	}
+	s->maxHeatSinkTemp=maxTemp;
+	s->minHeatSinkTemp=minTemp;
+	
+	return 0;
+}
+
+/**
+ * @brief calculate Voltage of System by adding block voltages
+ */
+uint32_t calc_system_voltage(MASTER_CAN0_STRUCT_t* s) {
+	uint32_t systemVoltage=0;
+	uint8_t i=0;
+	for(i=0;i<CAN0_MAX_NR_OF_SLAVES;i++) {
+		if(s->Slave[i].SlaveConnectionState!=NOT_CONNECTED && s->Slave[i].SlaveType == SLAVE ) {
+			systemVoltage += s->Slave[i].BlockVoltage;
+		}
+	}
+	return systemVoltage;
+}
+
+/**
+ * @bief calculate SOC by simple coulomb counting
+ */
+void calc_system_SoC(MASTER_CAN0_STRUCT_t* s) {
+	s->StateOfCharge = s->StateOfCharge - s->UI_Board.Ibatt*10 *200; // t=200ms ibatt in 10mA steps
+}
+
+/**
+ * @brief convert inverter data into correct data types
+ */
+void refresh_inverter_tx_data(MASTER_CAN0_STRUCT_t* s) {
+	BMS_CAN1_INVERTER_TX* inv=&(s->inverter.txStruct);
+	inv->Values.batteryCapacity.value=36.0;
+	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batteryCapacity.value));
+	inv->Values.batteryCurrent.value=( (float)(s->UI_Board.Ibatt) )/100 ;
+	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batteryCurrent.value));
+	inv->Values.batterySOC.value=s->SoC_estimator.SoC_percentage_smooth;
+	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batterySOC.value));
+	inv->Values.batterySOCtarget.value=(float)-1.0;
+	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batterySOCtarget.value));
+	inv->Values.batterySOH.value=(float)1.0;
+	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batterySOH.value));
+	inv->Values.batteryStatus.byte6=0;
+	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batteryStatus.byte6));
+	inv->Values.batteryTemperature.value=(float)s->maxCellTemp;
+	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batteryTemperature.value));
+	inv->Values.batteryVoltage.value=( (float)(s->systemVoltage)) /1000.0;
+	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batteryVoltage.value));
+	inv->Values.maxBatteryChargeCurrent.value=s->SoC_estimator.MaxBatteryChargeCurrent;
+	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.maxBatteryChargeCurrent.value));
+	inv->Values.maxBatteryChargeVoltage.value=s->startupConfig.maxBatteryVoltage;
+	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.maxBatteryChargeVoltage.value));
+	inv->Values.maxBatteryDischargeCurrent.value=s->SoC_estimator.MaxBatteryDischargeCurrent;
+	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.maxBatteryDischargeCurrent.value));
+	inv->Values.minBatteryDischargeVoltage.value=s->startupConfig.minBatteryVoltage;
+	shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.minBatteryDischargeVoltage.value));
+	
+	if(s->relayState.HS_closed == TRUE && s->relayState.LS_closed == TRUE && s->relayState.PRECHARGE_closed == TRUE) {
+		inv->Values.batteryModeExtra.value = 0;
+		
+	}
+	else {
+		inv->Values.batteryModeExtra.value = 1;
+		shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batteryModeExtra.value));
+	}
+	//inv->Values.batteryMode.value=(uint32_t)(s->RunMode);
+	//shuffle_lsb_msb_can1((uint8_t*)&(inv->Values.batteryMode.value));
+}
+
+void shuffle_lsb_msb_can1(uint8_t* value) {
+	uint8_t tempValue[4];
+	tempValue[3]=value[0];
+	tempValue[2]=value[1];
+	tempValue[1]=value[2];
+	tempValue[0]=value[3];
+	
+	value[0]=tempValue[0];
+	value[1]=tempValue[1];
+	value[2]=tempValue[2];
+	value[3]=tempValue[3];
+}
+
+
+uint8_t check_if_all_values_are_initialized(MASTER_CAN0_STRUCT_t* s) {
+	uint8_t slaveNr;
+	uint8_t cellNr;
+	for(slaveNr=0;slaveNr<CAN0_MAX_NR_OF_SLAVES-1;slaveNr++){
+		if(s->Slave[slaveNr].SlaveConnectionState != NOT_CONNECTED) {
+			for(cellNr=0;cellNr<MAX_SLAVE_CELLS;cellNr++) {
+				if(s->Slave[slaveNr].CellConnectionState[cellNr]==CELL_CONNECTED) {
+					if(s->Slave[slaveNr].CellVoltage[cellNr] == 0xffff) {
+						return FALSE;
+					}
+				}
+				if(s->Slave[slaveNr].TempSensConnectionState[cellNr] == TEMP_SENSOR_CONNECTED) {
+					if(s->Slave[slaveNr].CellTemp[cellNr] == -1) {
+						return FALSE;
+					}
+				}
+			}
+		}
+		
+	}
+	return TRUE;
+}
+
+/**
+ * @brief Handles communication with Slave-Boards over CAN0 interface
+ * @param	s pointer to state variable
+ * @param	time	current timestamp in ms
+ * 
+ * Master_CAN0_fsm is a finite state machine which handles the commuinication between Master and Slave boards.
+ * It requests Data from the Slaves by sending an Request telegram, and saves the received data in the
+ * provided MASTER_CAN0_STRUCT. It records CAN BUS Errors and hands these information to the Master_CAN0_ERROR_fsm. 
+ */	
+uint16_t Master_CAN0_fsm(MASTER_CAN0_STRUCT_t* s,uint32_t time) {
+	CAN_CONFIG *config;
+	int8_t can_state=CAN_OK;
+	uint8_t data_state=0;
+	uint8_t ui_state=FALSE;
+	switch(s->FsmState) {
+		case INIT:
+			s->slaveSelect=0;
+			s->cycleTimestamp=time;
+			s->FsmState=CHECK_IF_SLAVE_ACTIVE;
+			s->cycleCounter++;
+			return TRUE;
+		break;
+		case CHECK_IF_SLAVE_ACTIVE:
+			// transmitt data to Inverter
+				if(s->SoC_initialized==TRUE && s->allValuesInitialized ==TRUE) {
+					//Master_CAN1_Inverter_fsm( s,&(s->CAN1_fsmStruct)) ;
+					Master_CAN1_select_comm_mode ( s,&(s->CAN1_fsmStruct)) ;
+				}
+				// Update Master temp sensor
+				readMasterTempSensorFsm(s);
+			s->timestamp=Global_1msCounter;
+			if(s->Slave[s->slaveSelect].SlaveConnectionState == NOT_CONNECTED) {
+				s->FsmState=WAIT_FOR_NEXT_SLAVE_TIMESLOT;
+				s->slaveSelect++;		// ignore and go to next slave
+				if(s->slaveSelect>=CAN0_MAX_NR_OF_SLAVES) {
+					s->slaveSelect=0;
+					s->FsmState=WAIT_FOR_NEXT_COMMUNICATION_CYCLE;
+				}
+				return TRUE;
+			}
+			else{
+				s->Slave[s->slaveSelect].SlaveTelegramsRecFlag=0;	// no Telegrams recoredet yet
+				s->FsmState=SEND_REQUEST_TELEGRAM;
+				
+				return TRUE;
+			}
+		break;	
+		case SEND_REQUEST_TELEGRAM:
+			s->transmission_pending=TRUE;
+			CAN0_tx_send_request_telegram(&(s->Slave[s->slaveSelect]),s->Slave[s->slaveSelect].MasterAliveCnt);
+			s->Slave[s->slaveSelect].MasterAliveCnt++;
+			if(s->Slave[s->slaveSelect].MasterAliveCnt >=CAN0_NR_OF_TELEGRAMS) {
+				s->Slave[s->slaveSelect].MasterAliveCnt=0;
+			}
+			
+			if(s->Slave[s->slaveSelect].SlaveType==SLAVE) {
+				s->tempSlave=s->Slave[s->slaveSelect];
+			}
+			else {
+				s->tempSlave=s->Slave[s->slaveSelect];
+				s->temp_UI_Board=s->UI_Board;
+			}
+			s->FsmState=WAIT_FOR_SLAVE_RESPONSE;
+			return TRUE;
+		break;
+		case WAIT_FOR_SLAVE_RESPONSE:
+			config= s->tempSlave.TxMailbox_ptr->p_CAN_Config;
+			//can_state=CAN_Check_error_Register(config);
+			if(s->tempSlave.SlaveType==SLAVE) {
+				if(s->tempSlave.SlaveConnectionState == CONNECTED) {
+					// real slave with real Sensors
+					CAN0_check_if_slave_rec(&(s->tempSlave));
+				}
+				else if(s->tempSlave.SlaveConnectionState == DEBUG_DATA_SIMULATED) {
+					// real slave with simulated Sensors
+					CAN0_DEBUG_data_check_if_slave_rec((&s->tempSlave),&(gDUMMY_data_struct.Slave[s->slaveSelect]) );
+				}
+				else{
+					// simulated Slave
+					CAN0_DEBUG_slave_check_if_slave_rec((&s->tempSlave),&(gDUMMY_data_struct.Slave[s->slaveSelect]) );
+				}
+				
+				//all Telegrams received
+				if(s->tempSlave.SlaveTelegramsRecFlag==CAN0_ALL_TELEGRAMS_REC ) {
+					//s->slaveSelect++;				
+					if(can_state == CAN_OK) {
+						// all telegrams received => reset error counter
+						if(s->slaveSelect == 3) {
+							s->FsmState= CHECK_CAN_DATA;
+						}
+						s->Slave[s->slaveSelect].SlaveCanCommuniationError.FailedComCnt=0;
+						s->FsmState= CHECK_CAN_DATA;
+						return TRUE;
+					}
+					else {
+						s->FsmState =HANDLE_CAN_ERROR;
+						return TRUE;
+					}
+				}
+
+				//timeout
+				else if(s->timestamp + CAN0_TIMEOUT_MS <=Global_1msCounter) {
+					s->FsmState =HANDLE_CAN_ERROR;
+					return TRUE;
+				}
+				// wait
+				else {
+					s->FsmState =WAIT_FOR_SLAVE_RESPONSE;
+					return TRUE;				
+				}
+			}
+			else {
+				
+				
+				if(s->tempSlave.SlaveConnectionState == CONNECTED) {
+					// real UI with real Sensors
+					ui_state=CAN0_check_if_UI_Board_rec( &(s->tempSlave) ,&(s->temp_UI_Board));
+				}
+				else if(s->tempSlave.SlaveConnectionState == DEBUG_DATA_SIMULATED) {
+					// real UI with simulated Sensors
+					ui_state=CAN0_DEBUG_data_check_if_UI_Board_rec(&(s->tempSlave),
+							&(gDUMMY_data_struct.Slave[s->slaveSelect]),
+							&(s->temp_UI_Board),
+							&(gDUMMY_data_struct.UI_Board));
+				}
+				else{
+					// simulated UI
+					ui_state=CAN0_DEBUG_slave_check_if_UI_Board_rec(&(s->tempSlave),
+							&(gDUMMY_data_struct.Slave[s->slaveSelect]),
+							&(s->temp_UI_Board),
+							&(gDUMMY_data_struct.UI_Board));
+				}
+				
+				if(ui_state==TRUE) {
+					//s->slaveSelect++;
+					if(can_state==CAN_OK) {
+						s->FsmState= CHECK_CAN_DATA;
+						return TRUE;
+					}
+					else {
+						s->FsmState =HANDLE_CAN_ERROR;
+						return TRUE;
+					}
+					//return TRUE;					
+				}
+				//timeout
+				else if(s->timestamp + CAN0_TIMEOUT_MS <=time) {
+					s->FsmState =HANDLE_CAN_ERROR;
+					return TRUE;
+				}
+				// wait
+				else {
+					s->FsmState =WAIT_FOR_SLAVE_RESPONSE;
+					return TRUE;				
+				}				
+			}
+		break;
+		case CHECK_CAN_DATA:
+				// check if rx data is correct
+			
+			if(s->tempSlave.SlaveType ==SLAVE ) {
+				
+				s->ErrorFlags=check_slave_data(s,&(s->Slave[s->slaveSelect]),
+						&(s->tempSlave),
+						BMS_SLAVE_MAX_TEMP,
+						BMS_ERROR_THRESHOLD_T_DISCHARGE_MAX,
+						BMS_SLAVE_MIN_TEMP,
+						BMS_ERROR_THRESHOLD_T_DISCHARGE_MIN,
+						BMS_SLAVE_MAX_CELL_VOLTAGE,
+						BMS_SLAVE_MIN_CELL_VOLTAGE);
+
+				if(s->ErrorFlags & BMS_SLAVE_DATA_ERROR_ALIVE_TIMEOUT) {
+					s->FsmState =SHUT_DOWN_BMS;
+					return TRUE;
+				}
+				
+				if(s->ErrorFlags & BMS_SLAVE_DATA_ERROR_OVER_VOLTAGE) {
+					s->FsmState =SHUT_DOWN_BMS;
+					return TRUE;
+				}		
+				if(s->ErrorFlags & BMS_SLAVE_DATA_ERROR_UNDER_VOLTAGE) {
+					s->FsmState =SHUT_DOWN_BMS;
+					return TRUE;
+				}	
+				if((s->ErrorFlags & BMS_SLAVE_DATA_ERROR_TEMP_LIMIT) && (s->allValuesInitialized == TRUE)) {
+					s->FsmState =SHUT_DOWN_BMS;
+					return TRUE;
+				}
+				if(s->ErrorFlags & BMS_SLAVE_DATA_ERROR_HEAT_SINK_LIMIT) {
+					s->FsmState =SHUT_DOWN_BMS;
+					return TRUE;
+				}
+				if(s->ErrorFlags & BMS_SLAVE_DATA_ERROR_BOARD_ELECTRONIC) {
+					s->FsmState =SHUT_DOWN_BMS;
+					return TRUE;
+				}
+				else {
+					// everything ok
+					
+				}
+				
+				
+				
+			
+				
+			}
+			else {
+				data_state=check_UI_data(&(s->Slave[s->slaveSelect]),
+						&(s->tempSlave),
+						&(s->UI_Board),
+						&(s->temp_UI_Board));	
+				
+				if(s->allValuesInitialized==FALSE) {
+					s->allValuesInitialized=check_if_all_values_are_initialized(s);
+				}
+				
+
+				
+				// Check for "Soft" Errors and set Error states
+				
+
+				
+				
+			}
+			s->transmission_pending=FALSE;
+			
+			s->FsmState= DO_CALCULATIONS;
+			return TRUE;
+		break;
+		case DO_CALCULATIONS:
+			// calculate SoC SoH ?
+			if(s->Slave[s->slaveSelect].SlaveType==SLAVE) {
+				// calculate Slave Voltage
+				s->Slave[s->slaveSelect].BlockVoltage=calc_block_voltage(&(s->Slave[s->slaveSelect]));
+				// set min max Temp
+				set_block_min_max_temp(&(s->Slave[s->slaveSelect]));
+				// set min max Voltage
+				calc_min_max_voltage_slave(&(s->Slave[s->slaveSelect]));
+				
+				s->slaveSelect++;
+				s->FsmState=WAIT_FOR_NEXT_SLAVE_TIMESLOT;
+				return TRUE;
+			}
+			else {
+				
+				
+				
+				// UI-Platine
+				// calc SoC
+				s->systemVoltage=calc_system_voltage(s);
+				calc_min_max_voltage_system(s);
+				set_system_min_max_temp(s);
+				// update UI FIFO
+				popUIFiFo(s); 
+				
+				BMS_Set_Error_Check_voltage_inconsitency(s);
+				
+				// check if System voltage is too high
+				if(s->allValuesInitialized ==TRUE) {
+					// Check Umin 1 Umin2 Umin3
+					BMS_Set_Error_check_Voltage_level_min(s);
+					// Check Umax 1 and Umax 2
+					BMS_Set_Error_check_Voltage_level_max(s) ;
+					BMS_Set_Error_check_System_voltage_level_max(s);
+					
+					// check if CHECK Imax 
+					BMS_Set_Error_Check_derating(s); 
+					
+					
+					// make balancing decisions
+					Master_Balancer_fsm(s);
+				}
+				// if in Winter MOde get SoC from FRAM
+//				if(s->SoC_initialized==TRUE && s->allValuesInitialized ==FALSE && s->RunMode== RUN_MODE_WINTER) {
+//					bms_SoC_init_estimator_FRAM(&(s->SoC_estimator), s->maxCellVoltage);
+//				}
+				// calculate SoC of higest and Lowest Cell
+				if(s->SoC_initialized==FALSE && s->allValuesInitialized ==TRUE) {
+					set_system_min_max_heatsink_temp(s);
+					//set initial SoC
+					if(s->startupConfig.state.Bit.SOC_Initialized) {
+						// get initial SOC From FRAM
+						 bms_SoC_init_estimator_FRAM(&(s->SoC_estimator), s->maxCellVoltage);
+					}
+					else {
+						bms_SoC_init_estimator(&(s->SoC_estimator), s->maxCellVoltage) ;
+					}
+					initSoCFifo(s);
+					s->SoC_initialized=TRUE;
+					s->FsmState=RUNNING_MODE_FSM;
+				}
+				else if(s->SoC_initialized==TRUE && s->allValuesInitialized ==TRUE) {
+					set_system_min_max_heatsink_temp(s);
+					
+					// calc SoC 
+					
+					while(s->SoC_estimator.state != BMS_SOC_READY) {
+						bms_SoC_running_fsm( &(s->SoC_estimator),s->UI_Board.Ibatt*10 ,s->maxCellVoltage,s->minCellVoltage,s->minCellTemp,s->maxCellTemp); 
+					}	
+					s->SoC_estimator.state = BMS_SOC_IDLE   ;		
+					
+					// if soc is at 100% set SoC initialized Flag
+					if(s->SoC_estimator.SoC_percentage_smooth > 0.9999) {
+						s->startupConfig.state.Bit.SOC_Initialized=1;
+						write_fram_set_startup_state(s);
+					}
+					// write SoC to FRAM
+					else if(s->startupConfig.state.Bit.SOC_Initialized==1) {
+						write_fram_set_SoC(s->SoC_estimator.SoC_percentage_smooth);
+					}
+					s->slaveSelect=0;
+					
+					// transmitt data to Inverter
+					if(s->SoC_initialized==TRUE && s->allValuesInitialized ==TRUE) {
+						refresh_inverter_tx_data(s);
+						//Master_CAN1_Inverter_fsm( s,&(s->CAN1_fsmStruct)) ;
+					}
+					// set running Mode
+					
+					// update inverter state
+					BMS_RCT_Inverter_fsm (s);
+					s->FsmState=RUNNING_MODE_FSM;
+					return TRUE;
+				}
+				else {
+					// nothing happend yet
+					s->FsmState=RUNNING_MODE_FSM;
+					return TRUE;
+				}
+	
+			}
+			return TRUE;
+		break;
+		case RUNNING_MODE_FSM:
+			// set running Mode
+			RunningModeFSM(s) ;
+			s->FsmState=WAIT_FOR_NEXT_COMMUNICATION_CYCLE;
+			return TRUE;
+		break;
+		case HANDLE_CAN_ERROR:
+			// delete interrupt flags
+			CAN0_clear_all_interrupt_flags();
+				// handle CAN Errors
+			config= s->tempSlave.TxMailbox_ptr->p_CAN_Config;
+			//can_state=CAN_Check_error_Register(config);			
+			// all telegrams received, can telegrams disturbed
+			if(s->tempSlave.SlaveTelegramsRecFlag==CAN0_ALL_TELEGRAMS_REC ) {
+				// Telegram values could be disturbed => reject all received Data
+				// Don't use newly received data => ignore tempSlave
+				s->Slave[s->slaveSelect].SlaveCanCommuniationError.FailedComCnt++;
+				if(s->Slave[s->slaveSelect].SlaveCanCommuniationError.FailedComCnt >=CAN0_MAX_NR_OF_FAILED_COM) {
+					s->FsmState=SHUT_DOWN_BMS;
+					
+					//write Error
+					ErrorStackPushSlaveError(s,s->slaveSelect,BMS_ERROR_STACK_SLAVE_CAN_ERROR,0,BMS_ERROR_CLASS_2);
+					return TRUE;
+				}
+				s->FsmState=DO_CALCULATIONS;
+				return TRUE;
+				
+			}
+			// telegrams missing, CAN Channel Ok
+			else{
+				if(can_state == CAN_OK) {
+					// CAN BUS OK, Slave is not reacting
+					// Don't use newly received data
+					s->Slave[s->slaveSelect].SlaveCanCommuniationError.FailedComCnt++;
+					if(s->Slave[s->slaveSelect].SlaveCanCommuniationError.FailedComCnt >=CAN0_MAX_NR_OF_FAILED_COM) {
+						//write Error
+						ErrorStackPushSlaveError(s,s->slaveSelect,BMS_ERROR_STACK_SLAVE_CAN_ERROR,0,BMS_ERROR_CLASS_2);
+						s->FsmState=SHUT_DOWN_BMS;
+						s->reset_test_timestamp=Global_1msCounter;
+						return TRUE;
+					}
+					s->FsmState=DO_CALCULATIONS;
+					return TRUE;				
+				}
+				else{
+					// CAN BUS ERROR, telegrams not coming thought
+					// Don't use newly received data
+					s->Slave[s->slaveSelect].SlaveCanCommuniationError.FailedComCnt++;
+					if(s->Slave[s->slaveSelect].SlaveCanCommuniationError.FailedComCnt >=CAN0_MAX_NR_OF_FAILED_COM) {
+						//write Error
+						ErrorStackPushSlaveError(s,s->slaveSelect,BMS_ERROR_STACK_SLAVE_CAN_ERROR,0,BMS_ERROR_CLASS_2);
+						s->reset_test_timestamp=Global_1msCounter;
+						s->FsmState=SHUT_DOWN_BMS;
+						return TRUE;
+					}
+					s->FsmState=DO_CALCULATIONS;
+					return TRUE;
+				}
+			}
+
+			return TRUE;
+		break;
+		case WAIT_FOR_NEXT_SLAVE_TIMESLOT:
+			// next timesolt ready
+			
+			if(s->timestamp +CAN0_RASTER_MS <= time) {
+				s->FsmState= CHECK_IF_SLAVE_ACTIVE;
+				return TRUE;
+				}
+			//wait
+			else{
+				s->FsmState=WAIT_FOR_NEXT_SLAVE_TIMESLOT;
+				return TRUE;
+			}
+		break;
+		case SEND_RECEIVE_INVERTER_DATA:
+			// send data to inverter and Wait for response
+			//CAN1_tx_Data_to_Inverter(time,&(s->inverter.txStruct));
+			//request DC INPUT VOLTAGE
+			//CAN1_request_float_value(Global_1msCounter,&(s->inverter.rxStruct.DCinputA_power),CAN1_RX_DC_INPUT_A_VOLTAGE);
+			s->startCan1Comm=TRUE;
+			s->FsmState=WAIT_FOR_NEXT_COMMUNICATION_CYCLE;
+			return TRUE;	
+		break;	
+		case WAIT_FOR_NEXT_COMMUNICATION_CYCLE:
+			if(s->cycleTimestamp +CAN0_COMM_CYCLE_MS <= time) {
+				s->FsmState= INIT;
+				return TRUE;
+				}
+			else {
+				s->FsmState=WAIT_FOR_NEXT_COMMUNICATION_CYCLE;
+				return TRUE;
+			}
+			return TRUE; 	
+		break;
+		case SHUT_DOWN_BMS:
+				// Something went horribly wrong, turn off system
+			SwitchRelais( LS_RELAIS, 0);
+			SwitchRelais( PRE_CHARGE_RELAIS, 0);
+			SwitchRelais( HS_RELAIS, 0);
+			s->relayState.HS_closed=FALSE;
+			s->relayState.LS_closed=FALSE;
+			s->relayState.PRECHARGE_closed=FALSE;
+			CLEAR_OUTPIN(PIN_REGNR_LED4);	// set LED4 to 0 to indicate that an Error has occured 
+			
+			//write_fram_word(BMS_STARTUP_ERROR_MODE_3,3,BMS_STARTUP_MODE_ADDR);
+			// go to Error	Mode
+			
+			// continue communication cycles
+			s->FsmState=DO_CALCULATIONS;
+			
+			return TRUE;
+		break;
+		default:
+			return FALSE;
+		break;
+	}
+	return FALSE;
+}
+	
+
+
+
+uint16_t init_master_operation_fsm(BMS_MASTER_OPERATION_t* opFsm) {
+	opFsm->FsmState=MASTER_OPERATION_INIT;
+	opFsm->timestamp=0;
+
+	return TRUE;
+}
+
+
+
+
+uint16_t Master_CAN1_fsm_init(MASTER_CAN1_STRUCT_t* can1Fsm) {
+	can1Fsm->delay =3;
+	can1Fsm->fsmState=CAN1_INIT;
+	can1Fsm->txMsgNr=0;
+	return TRUE;
+}
+
+/*
+ * 
+ */
+uint32_t Master_CAN1_select_comm_mode (MASTER_CAN0_STRUCT_t* s,MASTER_CAN1_INVERTER_STRUCT_t* fsmStruct) {
+	if(fsmStruct->slowRequestFsmRunning == TRUE) {
+		// slow requests are running => wait till requests are complete
+		Master_CAN1_Inverter_fsm(s,fsmStruct);
+		// set fast request running flag for faast request asap
+		fsmStruct->fastRequestFsmRunning=TRUE;
+		return TRUE;
+	}
+	else if(s->Slave[s->slaveSelect].SlaveType== UI || fsmStruct->fastRequestFsmRunning==TRUE) {
+		// commuincation with UI is about to begin or fast request flag is set
+		// this means 250ms tick is reached => initiate fast request if possible
+		Master_CAN1_Fast_request_fsm (s,fsmStruct);
+		return TRUE;
+	}
+	else {
+		// nothing special run normal fsm
+		Master_CAN1_Inverter_fsm(s,fsmStruct);
+		return TRUE;
+	}
+}
+/*
+ * handles request of battery current and battery voltage from inverter
+ * which have to be sampled regulatly
+ */
+uint32_t Master_CAN1_Fast_request_fsm (MASTER_CAN0_STRUCT_t* s,MASTER_CAN1_INVERTER_STRUCT_t* fsmStruct) {
+	switch(fsmStruct->fastRxState) {
+		case CAN1_FAST_RX_FSM_REQUEST_BATTERY_CURRENT:
+			// request battery current from inverter
+			fsmStruct->nrOfRecCurrentSamples++;
+			CAN1_send_request_telegram(CAN1_RX_BATTERY_CURRENT);
+			fsmStruct->fastRequestFsmRunning=TRUE;
+			fsmStruct->fastRxState=CAN1_FAST_RX_FSM_REQUEST_BATTERY_VOLTAGE;
+			return TRUE;
+		break;	
+		case CAN1_FAST_RX_FSM_REQUEST_BATTERY_VOLTAGE:
+			// readout battery current and request battery voltage
+			if(CAN1_wait_for_response(&(s->inverter.rxStruct.batteryCurrent)) == TRUE ) {
+				// battery current received
+				pushInverterCurrentFIFO(s);
+				// compare UI Current and Inverter Current
+				if(fsmStruct->nrOfRecCurrentSamples > UI_CURRENT_FIFO_SIZE) {
+					// BMS_Set_Error_Check_current_consitency(s); //compare current of UI with Inverter
+				}
+			}
+			else {
+				// no response in 10ms => timeout
+				// go to normal communication fsm
+				fsmStruct->fastRxState = CAN1_FAST_RX_FSM_REQUEST_BATTERY_CURRENT;
+				fsmStruct->fastRequestFsmRunning=FALSE;
+				return TRUE;
+			}
+			// request battery voltage
+			CAN1_send_request_telegram(CAN1_RX_BATTERY_VOLTAGE);
+			fsmStruct->fastRxState =CAN1_FAST_RX_FSM_REQUEST_COMPLETE;
+			return TRUE;
+		break;
+		case CAN1_FAST_RX_FSM_REQUEST_COMPLETE:
+			// readout voltage
+			if(CAN1_wait_for_response(&(s->inverter.rxStruct.batteryVoltage)) == TRUE ) {
+				// battery voltage received
+			}
+			else {
+				// no response in 10ms => timeout
+				// go to normal communication fsm
+				fsmStruct->fastRxState = CAN1_FAST_RX_FSM_REQUEST_BATTERY_CURRENT;
+				fsmStruct->fastRequestFsmRunning=FALSE;
+				return TRUE;
+			}		
+			// fast requests done
+			fsmStruct->fastRxState = CAN1_FAST_RX_FSM_REQUEST_BATTERY_CURRENT;
+			fsmStruct->fastRequestFsmRunning=FALSE;	
+			return TRUE;
+		break;
+	}
+}
+
+
+
+uint32_t Master_CAN1_Inverter_fsm(MASTER_CAN0_STRUCT_t* s,MASTER_CAN1_INVERTER_STRUCT_t* fsmStruct) {
+	BMS_CAN1_INVERTER_TX* data = &(s->inverter.txStruct);
+	BMS_CAN1_INVERTER_CELL_DATA_t txPkg;
+	float* rx_ptr=&(s->inverter.rxStruct.expectedInputPower); 	// points to rx_address to sotre inverter value
+	uint8_t eightBitBuff[8]= {0,0,0,0,0,0,0,0} ;
+	switch(fsmStruct->fsmState) {
+		case CAN1_FSM_INIT:
+			// reset Message counters
+			fsmStruct->highPrioMsgNr=0;
+			fsmStruct->lowPrioMsgNr=0;
+			fsmStruct->requestTelegramNr=0;
+			fsmStruct->timeoutCyclesCnt=0;
+
+			
+			// check if all Values are initialized 
+			// if yes start transmitting
+			if(s->allValuesInitialized == TRUE) {
+				fsmStruct->fsmState=CAN1_FSM_SEND_HIGH_PRIO_DATA;
+				return TRUE;
+			}
+			// not all values are initialized
+			//=> stay in INIT state
+			return TRUE;
+		break;
+		case CAN1_FSM_SEND_HIGH_PRIO_DATA:
+			// rx process complete
+			fsmStruct->slowRequestFsmRunning=FALSE;
+			
+			// transmit high priority data, which is
+			// maximum charge Current
+			// maximum Charge Voltage
+			// maximum Discharge Current
+			// minimum Discharge Voltage
+			// battery Current
+			// battery Voltage
+			// Battery SoC
+			// Battery Capacity
+			// Battery Temperature
+			// Battery SoH
+			// Battery Status
+			// Battery SoC Target
+			
+			if(fsmStruct->highPrioMsgNr == 0) {
+				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.maxBatteryChargeCurrent),Global_1msCounter);
+			}
+			else if(fsmStruct->highPrioMsgNr == 1) {
+				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.maxBatteryChargeVoltage),Global_1msCounter);
+			}
+			else if(fsmStruct->highPrioMsgNr == 2) {
+				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.maxBatteryDischargeCurrent),Global_1msCounter);
+			}
+			else if(fsmStruct->highPrioMsgNr == 3) {
+				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.minBatteryDischargeVoltage),Global_1msCounter);
+			}
+			else if(fsmStruct->highPrioMsgNr == 4) {
+				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryCurrent),Global_1msCounter);
+			}
+			else if(fsmStruct->highPrioMsgNr == 5) {
+				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryVoltage),Global_1msCounter);
+			}
+			else if(fsmStruct->highPrioMsgNr == 7) {
+				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batterySOC),Global_1msCounter);
+			}
+			else if(fsmStruct->highPrioMsgNr == 8) {
+				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryCapacity),Global_1msCounter);
+			}
+			else if(fsmStruct->highPrioMsgNr == 9) {
+				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryTemperature),Global_1msCounter);
+			}
+			else if(fsmStruct->highPrioMsgNr == 10) {
+				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batterySOH),Global_1msCounter);
+			}
+			else if(fsmStruct->highPrioMsgNr == 11) {
+				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batterySOCtarget),Global_1msCounter);
+			}
+			else if(fsmStruct->highPrioMsgNr == 12) {
+				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryMode),Global_1msCounter);
+			}
+			else if(fsmStruct->highPrioMsgNr == 13) {
+				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryModeExtra),Global_1msCounter);
+			}
+			
+			// increment high prio msg cnt
+			fsmStruct->highPrioMsgNr++ ;
+			
+			// if all high prio msg are transmitted start transmitting low prio msg
+			if(fsmStruct->highPrioMsgNr > 13) {
+				fsmStruct->highPrioMsgNr=0;
+				// reset error cnt to start with error 1 again
+				fsmStruct->transmitErrorNrEs1=0;
+				fsmStruct->transmitErrorNrEs2=0;
+				fsmStruct->transmitErrorNrEs3=0;
+				fsmStruct->fsmState=CAN1_FSM_SEND_ES_1;
+				return TRUE;
+			}
+			else {
+				// continue Transmitting high Prio Msg
+				fsmStruct->fsmState=CAN1_FSM_SEND_HIGH_PRIO_DATA;
+				return TRUE;
+			}
+		break;
+		case CAN1_FSM_SEND_ES_1:
+			// send Error Calls 1 Errors
+			
+			if( !ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_1) && !ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_2) && ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_3) ) {
+				// no Error has occured Transmitt everything ok
+				CLEAR_OUTPIN(PIN_REGNR_LED4);
+				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(data->Values.batteryStatus),Global_1msCounter);
+				fsmStruct->fsmState=CAN1_FSM_SEND_LOW_PRIO_DATA;
+				return TRUE;
+			}
+			
+			else if(ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_3) && fsmStruct->transmitErrorNrEs3 < BMS_ERROR_ERROR_STACK_SIZE) {
+				// transmitt ES 3 Errors
+				// check if Error is active
+				SET_OUTPIN(PIN_REGNR_LED4);
+				while(s->ErrorBuffer.ES3_Error[fsmStruct->transmitErrorNrEs3].Master.active == 0){
+					// Error no ,longer Active go to next entry
+					fsmStruct->transmitErrorNrEs3++;
+					if(fsmStruct->transmitErrorNrEs3 >=BMS_ERROR_ERROR_STACK_SIZE) {
+						
+						return TRUE;
+					}
+				}
+				ErrorStackGenerateStatusPkg(eightBitBuff,(uint8_t*)&(s->ErrorBuffer.ES3_Error[fsmStruct->transmitErrorNrEs3]));
+				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, eightBitBuff,Global_1msCounter);
+				fsmStruct->transmitErrorNrEs3++;
+				return TRUE;
+			}
+			
+			else if(ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_2) && fsmStruct->transmitErrorNrEs2 < BMS_ERROR_ERROR_STACK_SIZE) {
+				// transmitt ES 2 Errors
+				// check if Error is active
+				SET_OUTPIN(PIN_REGNR_LED4);
+				while(s->ErrorBuffer.ES2_Error[fsmStruct->transmitErrorNrEs2].Master.active == 0){
+					// Error no ,longer Active go to next entry
+					fsmStruct->transmitErrorNrEs2++;
+					if(fsmStruct->transmitErrorNrEs2 >=BMS_ERROR_ERROR_STACK_SIZE) {
+						
+						return TRUE;
+					}
+				}
+				ErrorStackGenerateStatusPkg(eightBitBuff,(uint8_t*)&(s->ErrorBuffer.ES2_Error[fsmStruct->transmitErrorNrEs2]));
+				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, eightBitBuff,Global_1msCounter);
+				fsmStruct->transmitErrorNrEs2++;
+				return TRUE;
+			}
+			else if(ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_1) && fsmStruct->transmitErrorNrEs1 < BMS_ERROR_ERROR_STACK_SIZE) {
+				// transmitt ES 1 Errors
+				// check if Error is active
+				SET_OUTPIN(PIN_REGNR_LED4);
+				while(s->ErrorBuffer.ES1_Error[fsmStruct->transmitErrorNrEs1].Master.active == 0){
+					// Error no ,longer Active go to next entry
+					fsmStruct->transmitErrorNrEs1++;
+					if(fsmStruct->transmitErrorNrEs1 >=BMS_ERROR_ERROR_STACK_SIZE) {
+						
+						return TRUE;
+					}					
+				}
+				ErrorStackGenerateStatusPkg(eightBitBuff,(uint8_t*)&(s->ErrorBuffer.ES1_Error[fsmStruct->transmitErrorNrEs1]));
+				CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, eightBitBuff,Global_1msCounter);
+				fsmStruct->transmitErrorNrEs1++;
+				return TRUE;
+			}
+			else {
+				fsmStruct->fsmState=CAN1_FSM_SEND_LOW_PRIO_DATA;
+				return TRUE;
+			}
+		break;
+		case CAN1_FSM_SEND_LOW_PRIO_DATA:
+			// send low Priority data which is
+			// Cell temperature and Cell Voltages
+			generateCellInfoPkg(s, fsmStruct->lowPrioMsgNr,&txPkg);
+			CAN_Write_dataset(&CAN_Tx0_RCT_INVERTER, (uint8_t*)&(txPkg),Global_1msCounter);
+			fsmStruct->lowPrioMsgNr++ ;
+			if(fsmStruct->lowPrioMsgNr >= (s->NrOfSlaves)*MAX_SLAVE_CELLS) {
+				// start with cell nr 0 again
+				fsmStruct->lowPrioMsgNr=0;
+				fsmStruct->fsmState=CAN1_FSM_SEND_REQUEST_DATA;
+				fsmStruct->requestTelegramNr=0;
+				return TRUE;
+			}
+			fsmStruct->fsmState=CAN1_FSM_SEND_LOW_PRIO_DATA;
+			return TRUE;	
+		break;
+		case CAN1_FSM_SEND_REQUEST_DATA:
+			// request data from RCT Inverter
+			// Set flag so request process cant be interrupted 
+			fsmStruct->slowRequestFsmRunning=TRUE;
+			if(fsmStruct->requestTelegramNr==0) {
+				CAN1_send_request_telegram(CAN1_RX_TOTAL_DC_PWR);
+				fsmStruct->fsmState= CAN1_FSM_WAIT_FOR_RESPONSE;
+				return TRUE;
+			}
+			else if(fsmStruct->requestTelegramNr==1) {
+				CAN1_send_request_telegram(CAN1_RX_DC_INPUT_A_POWER);
+				fsmStruct->fsmState= CAN1_FSM_WAIT_FOR_RESPONSE;
+				return TRUE;				
+			}
+			else if(fsmStruct->requestTelegramNr==2) {
+				CAN1_send_request_telegram(CAN1_RX_DC_INPUT_B_POWER);
+				fsmStruct->fsmState= CAN1_FSM_WAIT_FOR_RESPONSE;
+				return TRUE;						
+			}
+			else if(fsmStruct->requestTelegramNr==3) {
+				CAN1_send_request_telegram(CAN1_RX_DC_INPUT_A_POWER);
+				fsmStruct->fsmState= CAN1_FSM_WAIT_FOR_RESPONSE;
+				return TRUE;						
+			}
+			else if(fsmStruct->requestTelegramNr==4) {
+				CAN1_send_request_telegram(CAN1_RX_DC_INPUT_B_POWER);
+				fsmStruct->fsmState= CAN1_FSM_WAIT_FOR_RESPONSE;
+				return TRUE;						
+			}
+			else {
+				// you should not be here
+				fsmStruct->fsmState=CAN1_FSM_SEND_HIGH_PRIO_DATA;
+				return TRUE;
+			}
+		break;	
+		case CAN1_FSM_WAIT_FOR_RESPONSE:
+			// to be updateted for more values
+			if(fsmStruct->requestTelegramNr==0) {
+				rx_ptr=&(s->inverter.rxStruct.expectedInputPower);
+			}
+			else if(fsmStruct->requestTelegramNr==1) {
+				rx_ptr=&(s->inverter.rxStruct.DCinputA_power);
+			}
+			else if(fsmStruct->requestTelegramNr==2)  {
+				rx_ptr=&(s->inverter.rxStruct.DCinputB_power);
+			}
+			else if(fsmStruct->requestTelegramNr==3)  {
+				// not valid anymore
+				rx_ptr=&(s->inverter.rxStruct.DCinputA_power);
+			}
+			else {
+				// not valid anymore
+				rx_ptr=&(s->inverter.rxStruct.DCinputB_power);
+			}
+			if(CAN1_wait_for_response(rx_ptr) == TRUE ) {	
+				fsmStruct->requestTelegramNr++;
+				fsmStruct->receivedTelegrams++;
+				if(fsmStruct->requestTelegramNr >=CAN1_NR_OF_REQUEST_TELEGRAMS) {
+					fsmStruct->fsmState=CAN1_FSM_SEND_HIGH_PRIO_DATA;
+					fsmStruct->timeoutCyclesCnt=0;
+					s->inverterState.inverterCanOnline= TRUE;
+					return TRUE;
+				}
+				else {
+					fsmStruct->fsmState=CAN1_FSM_SEND_REQUEST_DATA;
+					fsmStruct->timeoutCyclesCnt=0;
+					s->inverterState.inverterCanOnline= TRUE;
+					return TRUE;				
+				}
+			}
+			else{
+				fsmStruct->timeoutCyclesCnt++;
+			}
+			
+			if(fsmStruct->timeoutCyclesCnt >5) {
+				// timeout
+				fsmStruct->receivedTelegrams=0;
+				//fsmStruct->timeoutCyclesCnt=0;
+				
+				// set Error
+				BMS_Set_Error_CAN1_Timeout(s) ;
+				// set inverter fsm to can out 
+				s->inverterState.inverterCanOnline= FALSE;
+				fsmStruct->fsmState=CAN1_FSM_SEND_HIGH_PRIO_DATA;
+				return TRUE;
+			}
+				// wait another 10ms for response
+			return TRUE;
+		break;
+		default :
+			// you should not be here	
+			return FALSE;
+		break;
+			
+	}
+}
+
+/*
+ * @brief generate a pkg with value ID (32bit) Cell Index (8-bit) voltage (16 bit) temperature (8-bit)
+ */
+uint32_t generateCellInfoPkg(MASTER_CAN0_STRUCT_t* s, uint8_t cellIndex,BMS_CAN1_INVERTER_CELL_DATA_t* txPkg) {
+	// collect information
+	int8_t cellTemp;
+	uint16_t cellVoltage;
+	uint8_t SlaveNr;
+	uint8_t cellNr;
+	uint8_t payload[4];
+	
+	
+	uint32_t valueId=CAN1_TX_CELL_STATUS;
+	
+	// shuffle Bits for correct Order
+	shuffle_lsb_msb_can1((uint8_t*)&valueId);
+	
+	SlaveNr = cellIndex/ (MAX_SLAVE_CELLS); // Slave Nr 0...14
+	cellNr = cellIndex - SlaveNr * MAX_SLAVE_CELLS ;// cellNr 0... 24
+	
+	cellVoltage = s->Slave[SlaveNr].CellVoltage[cellNr];
+	
+	if(s->Slave[SlaveNr].TempSensConnectionState[cellNr] == TEMP_SENSOR_CONNECTED) {
+		cellTemp = s->Slave[SlaveNr].CellTemp[cellNr] ;
+	}
+	else {
+		// if temp sensor not connected transmit -51 deg
+		cellTemp = -51 ;
+	}
+	payload[0]=cellIndex;
+	payload[1]= cellVoltage >> 8;
+	payload[2]= cellVoltage & 0xFF;
+	payload[3]= (uint8_t)cellTemp;
+	
+	shuffle_lsb_msb_can1((uint8_t*)&(payload[0]));
+	
+	txPkg->valueId=valueId;
+	txPkg->payload= (payload[0] << 24) + (payload[1] << 16) + (payload[2] << 8) + payload[3] ;
+}
+
+
+uint32_t Master_Balancer_fsm(MASTER_CAN0_STRUCT_t* s) {
+	switch(s->balancerState) {
+		case BMS_BALANCE_INIT:
+				if(s->allValuesInitialized== TRUE && (s->maxCellVoltage >=BMS_SLAVE_MAX_BALANCE_VOLTAGE)) {
+					// cellvoltage of system too high => no Balancing
+					s->balancerState=BMS_BALANCE_OFF;
+				}
+				else if(s->SoC_estimator.SoC_percentage_smooth <= BMS_SLAVE_MIN_BALANCE_SOC) {
+					// SoC under 80% do not balance
+					s->balancerState=BMS_BALANCE_OFF;
+				}
+				else if(s->maxHeatSinkTemp >= BMS_SLAVE_MAX_BALANCE_HEATSINK_TEMP) {
+					// Heatsink too hot => do not balance
+					s->balancerState=BMS_BALANCE_OFF;
+				}
+				else if(s->allValuesInitialized== TRUE && (s->UI_Board.Ibatt > BMS_SLAVE_BATTERY_CHARGE_THERESOLD) ) {
+					// battery discharging => no Balancing
+					s->balancerState=BMS_BALANCE_OFF;
+				}
+				else if(s->allValuesInitialized== TRUE && (s->UI_Board.Ibatt < BMS_SLAVE_BATTERY_CHARGE_THERESOLD)) {
+					// ready for balancing
+					s->balancerState=BMS_BALANCE_GET_VOLTAGE;
+				}
+
+				else {
+					// do nothing
+				}
+			
+			return TRUE;
+		break;
+		case BMS_BALANCE_GET_VOLTAGE:
+				// decide Which cells to balance
+				if(s->UI_Board.Ibatt < BMS_SLAVE_BATTERY_CHARGE_THERESOLD) {
+					set_balancer(s);
+					s->balancerState=BMS_BALANCE_BALANCE_CELLS;
+				}
+				else {
+					set_balancer_off(s) ;
+					s->balancerState=BMS_BALANCE_OFF;
+				}
+			return TRUE;
+		break;
+		case BMS_BALANCE_BALANCE_CELLS:
+			// turn off balancing to obtain uneffected cell voltages	
+			if(s->UI_Board.Ibatt < BMS_SLAVE_BATTERY_CHARGE_THERESOLD) {
+				set_balancer_off(s) ;
+				s->balancerState=BMS_BALANCE_COOL;
+			}
+			else {
+				set_balancer_off(s) ;
+				s->balancerState=BMS_BALANCE_OFF;
+			}
+			return TRUE;
+		break;
+		case BMS_BALANCE_COOL:
+			// uneffected cell voltages are now available
+			if(s->UI_Board.Ibatt < BMS_SLAVE_BATTERY_CHARGE_THERESOLD) {
+				s->balancerState=BMS_BALANCE_INIT;
+			}
+			else {
+				set_balancer_off(s) ;
+				s->balancerState=BMS_BALANCE_OFF;
+			}			
+			return TRUE;
+		break;
+		case BMS_BALANCE_OFF:
+				set_balancer_off(s) ;
+			if(s->UI_Board.Ibatt < BMS_SLAVE_BATTERY_CHARGE_THERESOLD) {
+				s->balancerState=BMS_BALANCE_INIT;
+			}	
+			s->balancerState=BMS_BALANCE_INIT;
+			return TRUE;
+		break;	
+		
+			
+	
+	}
+	
+}
+
+uint8_t get_nr_of_connected_slaves(MASTER_CAN0_STRUCT_t* s){
+	uint8_t i=0;
+	uint8_t nr=0;
+	for(i=0;i<CAN0_MAX_NR_OF_SLAVES-1;i++) {
+		if(s->Slave[i].SlaveConnectionState== CONNECTED) {
+			nr++;
+		}
+	}
+	return nr;
+}
+
+uint32_t RunningModeFSM(MASTER_CAN0_STRUCT_t* s){
+
+	
+	// check for active Error States
+	if(ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_3) || s->RunMode.ErrorState3fsm != ES3_FSM_INIT) {
+		// handle Error Class 3
+		BMS_Master_ES3_fsm(s);
+		return TRUE;
+	}
+	else if(ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_2) || s->RunMode.ErrorState2fsm != ES2_FSM_INIT) {
+		// handle Error Class 2
+		BMS_Master_ES2_fsm(s);
+		return TRUE;
+	}
+	else if(ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_1) || s->RunMode.ErrorState1fsm != ES1_FSM_INIT) {
+		// handle Error Class 1
+		BMS_Master_ES1_fsm(s);
+		return TRUE;
+	}
+	
+	else {
+		// normal operation
+		OPModeFSM( s );
+	return TRUE;
+	}
+
+}
+
+uint32_t OPModeFSM(MASTER_CAN0_STRUCT_t* s){
+	float SoC=s->SoC_estimator.SoC_percentage_smooth;
+	switch(s->RunMode.OperationMode) {
+		case OP_MODE_INIT:
+			// just jump to checkup startup conditions
+			s->RunMode.OperationMode=OP_MODE_CHECK_STARTUP_CONDITIONS;
+			
+			CLEAR_OUTPIN(PIN_REGNR_LED4);
+			return TRUE;
+		break;
+		case OP_MODE_CHECK_STARTUP_CONDITIONS:
+			if(s->allValuesInitialized==TRUE) {
+				// all values initalized and no error occured
+				// => Startup conditions apply => start startup
+				s->RunMode.OperationModeTimestamp=Global_1msCounter;
+				s->RunMode.OperationMode=OP_MODE_SET_PRECHARGE_RELAY;
+				s->RunMode.onCounter=0;
+				return TRUE;
+			}
+			else {
+				// wait till all values are initialiezd
+				s->RunMode.OperationMode=OP_MODE_CHECK_STARTUP_CONDITIONS;
+				return TRUE;
+			}
+		break;
+		case OP_MODE_SET_PRECHARGE_RELAY:
+			// set Low Side and Precharge Relais
+			s->relayState.LS_closed=TRUE;
+			s->relayState.PRECHARGE_closed=TRUE;
+			SwitchRelais( LS_RELAIS, 1);
+			SwitchRelais( PRE_CHARGE_RELAIS, 1);			
+			if(s->RunMode.OperationModeTimestamp + 3000 <= Global_1msCounter) {
+				s->RunMode.OperationMode=OP_MODE_SET_MAIN_RELAY;
+				return TRUE;
+			}
+			else {
+				s->RunMode.OperationMode= OP_MODE_SET_PRECHARGE_RELAY;
+				return TRUE;
+			}
+		break;
+		case OP_MODE_SET_MAIN_RELAY:
+			// Switch Highside relais
+			SwitchRelais( HS_RELAIS, 1);
+			s->relayState.HS_closed=TRUE;
+			s->RunMode.OperationMode=OP_MODE_NORMAL;
+			return TRUE;
+		break;
+		case OP_MODE_NORMAL:
+			// do nothing until SoC becomes low
+			s->RunMode.onCounter++;
+			if ( SoC < BMS_SOC_LOW_MARK) {
+				s->RunMode.OperationMode=OP_MODE_SOC_LOW;
+				return TRUE;
+			}
+			else {
+				s->RunMode.OperationMode=OP_MODE_NORMAL;
+				return TRUE;
+			}				
+			return TRUE;
+		break;
+		case OP_MODE_SOC_LOW:
+			s->RunMode.onCounter++;
+			// do nothing until SoC becomes high again
+			if ( SoC > BMS_SOC_LOW_MARK) {
+				s->RunMode.OperationMode=OP_MODE_NORMAL;
+				return TRUE;
+			}
+			else {
+				s->RunMode.OperationMode=OP_MODE_SOC_LOW;
+				return TRUE;
+			}	
+		break;	
+		default:
+			// something went horribly wrong
+			return FALSE;
+		break;
+	}
+	
+}
+/*
+ * @brief Statemachine which handles Class 1 Errors
+ */
+
+uint32_t BMS_Master_ES1_fsm(MASTER_CAN0_STRUCT_t* s){
+	switch (s->RunMode.ErrorState1fsm) {
+		case ES1_FSM_INIT:
+			s->RunMode.ErrorState1fsm=ES1_FSM_CHECK_IF_ERROR_VALID;
+			return TRUE;
+		break;
+		case ES1_FSM_CHECK_IF_ERROR_VALID:
+			// Try to clear Error
+			BMS_Clear_Error_Buffer(s,BMS_ERROR_CLASS_1);
+
+			
+			if(ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_1)) {
+				// Error still active
+				// Don't do anything
+				
+			}
+			else {
+				// No Error
+				s->RunMode.ErrorState1fsm=ES1_FSM_ERROR_REVOKED;
+			}
+			return TRUE;
+		break;
+		case ES1_FSM_ERROR_REVOKED:
+			// No More Errors apply startup system again
+			s->RunMode.OperationMode=OP_MODE_INIT;
+			// set Fsm Back to INIT
+			s->RunMode.ErrorState1fsm=ES1_FSM_INIT;
+			return TRUE;
+		break;
+	}
+}
+
+uint32_t BMS_Master_ES2_fsm(MASTER_CAN0_STRUCT_t* s){
+	switch(s->RunMode.ErrorState2fsm) {
+		case ES2_FSM_INIT:
+			// save time for Timeout timer
+			s->RunMode.ErrorState2Timestamp=Global_1msCounter;
+			if(s->ErrorBuffer.ES2_New_Error==FALSE) {
+				// System had power cycle, Try to fix Error
+				s->RunMode.ErrorState2fsm=ES2_FSM_CHECK_IF_ERROR_VALID;
+			}
+			else {
+				// no restart => wait timeout then kill system
+				s->RunMode.ErrorState2fsm=ES2_FSM_WAIT_FOR_SHUTDOWN;
+			}
+			return TRUE;
+		break;
+		case ES2_FSM_CHECK_IF_ERROR_VALID:
+			// Try to clear Error
+			BMS_Clear_Error_Buffer(s,BMS_ERROR_CLASS_2);
+			if(!ErrorStackCheckForActiveErrors(s,BMS_ERROR_CLASS_2)) {
+				// all Errors cleared
+				s->RunMode.ErrorState2fsm=ES2_FSM_ERROR_REVOKED;
+			}
+			else if(s->RunMode.ErrorState2Timestamp + BMS_ERROR_FSM_ES2_TIMEOUT < Global_1msCounter ) {
+				// Timeout shutdown system
+				s->RunMode.ErrorState2fsm=ES2_FSM_SYSTEM_SHUTDOWN;
+			}
+			else{
+				// do nothing an wait for timeout or error to be cleared
+			}
+			return TRUE;
+		break;
+		case ES2_FSM_WAIT_FOR_SHUTDOWN:
+			// wait timeout
+			if(s->RunMode.ErrorState2Timestamp + BMS_ERROR_FSM_ES2_TIMEOUT < Global_1msCounter ) {
+				// timeout
+				s->RunMode.ErrorState2fsm=ES2_FSM_SYSTEM_SHUTDOWN;
+				return TRUE;
+			}
+			else {
+				// wait and do nothing
+				return TRUE;
+			}
+			return TRUE;
+		break;
+		case ES2_FSM_ERROR_REVOKED:
+			// no more Errors in the system => Start normal Operation again
+			s->RunMode.ErrorState2fsm=ES2_FSM_INIT;
+			s->RunMode.OperationMode=OP_MODE_INIT;
+			return TRUE;
+		break;
+		case ES2_FSM_SYSTEM_SHUTDOWN:
+			// Turn off power Supply
+			SwitchRelais( PWR_SUPPLY, 1);
+			// now System should be dead
+			while (1) {
+				// loop for ever
+				SwitchRelais( PWR_SUPPLY, 1);
+			}
+			
+			break;
+		return TRUE;
+	}
+}
+
+/*
+ * @brief handle error class 3
+ * Todo System repair tool not implemented yet
+ */
+uint32_t BMS_Master_ES3_fsm(MASTER_CAN0_STRUCT_t* s) {
+	switch(s->RunMode.ErrorState3fsm){
+		case ES3_FSM_INIT:
+			// save timestamp for timeout
+			s->RunMode.ErrorState3Timestamp=Global_1msCounter;
+			s->RunMode.ErrorState3fsm=ES3_FSM_CONNECT_TO_SERVICE_TOOL;
+			return TRUE;
+		break;
+		case ES3_FSM_CONNECT_TO_SERVICE_TOOL:
+			// not fully implemented yet
+			// just shut down system after timeout
+			if(s->RunMode.ErrorState3Timestamp + BMS_ERROR_FSM_ES3_TIMEOUT < Global_1msCounter ) {
+				// Shut down System
+				s->RunMode.ErrorState3fsm=ES3_FSM_SYSTEM_SHUTDOWN;
+			}
+			else {
+				// wait
+			}
+			return TRUE;
+		break;
+		case ES3_FSM_SYSTEM_SHUTDOWN:
+			// Turn off power Supply
+			SwitchRelais( PWR_SUPPLY, 1);
+			// now System should be dead
+			while (1) {
+				// loop for ever
+				SwitchRelais( PWR_SUPPLY, 1);
+			}
+			return TRUE;
+		break;
+			
+	
+	}
+}
+
+/*
+ * @brief check if connected Inverter has enough power to charge battery and recover from Wintermode 
+ */
+
+int32_t checkIfInverterHasPower(MASTER_CAN0_STRUCT_t* s) {
+	if((s->inverter.rxStruct.expectedInputPower) > BMS_WINTER_MODE_RECOVER_PWR) {
+		return TRUE;
+	}
+	else {
+		return FALSE;
+	}
+}
+
+/*
+ * @brief read Temp sensor on master Board
+ */
+uint32_t readMasterTempSensorFsm(MASTER_CAN0_STRUCT_t* s) {
+	switch(s->MasterTempSensState) {
+		case BMS_MASTER_TEMP_SENSOR_INITIATE_MEASUREMENT:
+			//  trigger measurement
+			if(TempMess_triggerRead() == 0) {
+				// measurement triggered got to next state
+				s->MasterTempSensState=BMS_MASTER_TEMP_SENSOR_UPDATE_MEASUREMENT;
+			}
+			return TRUE;
+		break;
+		case BMS_MASTER_TEMP_SENSOR_UPDATE_MEASUREMENT:
+			TempMess_update();
+			if(TempMess_poll_Value(&(s->masterTemp)) == 0) {
+				// readout succesfull go back to triggering measurement
+				s->MasterTempSensState=BMS_MASTER_TEMP_SENSOR_INITIATE_MEASUREMENT;
+			}
+			return TRUE;
+		break;
+	}
+}
+
+/*
+ * @brief clear fifos 
+ */
+
+uint32_t initUIFifo(MASTER_CAN0_STRUCT_t* s) {
+	uint8_t i;
+	for(i=0;i<UI_VOLTAGE_FIFO_SIZE;i++) {
+		s->UI_Board.UbattFiFo[i]=0;
+		s->UI_Board.SystemVoltageFiFo[i]=0;
+	}
+	for(i=0;i<UI_CURRENT_FIFO_SIZE;i++) {
+		s->UI_Board.IbattFiFo[i]=0;
+		s->UI_Board.Ibatt_Inverter_FIFO[i]=0;
+	}
+	return TRUE;
+}
+
+uint32_t popUIFiFo(MASTER_CAN0_STRUCT_t* s) {
+	uint8_t i;
+	
+	for(i=UI_VOLTAGE_FIFO_SIZE-1;i>0;i--) {
+		s->UI_Board.UbattFiFo[i]=s->UI_Board.UbattFiFo[i-1];
+	}
+	s->UI_Board.UbattFiFo[0]=s->UI_Board.Ubatt;
+	
+	for(i=UI_VOLTAGE_FIFO_SIZE-1;i>0;i--) {
+		s->UI_Board.SystemVoltageFiFo[i]=s->UI_Board.SystemVoltageFiFo[i-1];
+	}
+	s->UI_Board.SystemVoltageFiFo[0]=(s->systemVoltage);
+	
+	for(i=UI_CURRENT_FIFO_SIZE-1;i>0;i--) {
+		s->UI_Board.IbattFiFo[i]=s->UI_Board.IbattFiFo[i-1];
+	}
+	s->UI_Board.IbattFiFo[0]=s->UI_Board.Ibatt;
+}
+
+uint32_t pushInverterCurrentFIFO(MASTER_CAN0_STRUCT_t* s) {
+	uint8_t i;
+	for(i=UI_CURRENT_FIFO_SIZE-1;i>0;i--) {
+		s->UI_Board.Ibatt_Inverter_FIFO[i]=s->UI_Board.Ibatt_Inverter_FIFO[i-1];
+	}
+	s->UI_Board.Ibatt_Inverter_FIFO[0]=s->inverter.rxStruct.batteryCurrent;
+	
+//	if(s->inverter.rxStruct.batteryCurrent > 100 ||  s->inverter.rxStruct.batteryCurrent < -100) {
+//		// fake value
+//		i++ ; // break here
+//	}
+	return TRUE;
+}
+
+
+// *** End BMS_Master.c ******************************************************

+ 104 - 107
BMS Master/Sources/BoardPeripherals.c

@@ -1,107 +1,104 @@
-#include "BMS_Master.h"
-
-
-
-#define TEST_TIMEOUT	10000
-
-extern uint32_t Global_1msCounter; 
-static vuint32_t TimeStamp;
-
-static void init_BoardIO();
-
-static const Board_Status Board_Status_INIT = {{0},0};
-Board_Status Board_S;	//globaler BoardStatus
-
-
-
-void BoardPeriph_init()
-{
-	RelaisLEDs_init();
-//	IMess_init();
-//	IMess_URef_init();
-	TempMess_init();
-//	UartToUsb_init();
-	//init FRAM
-	Board_S = Board_Status_INIT;
-	Board_S.FRAM_Flags.B.init_ok = (FRAM_init()>=0) ? 1:0;
-}
-
-
-
-void BoardPeriph_test_init()
-{
-	TimeStamp = Global_1msCounter;
-	FRAM_trigger_Test();
-}
-
-
-
-int8_t BoardPeriph_test_update_polled()
-{
-	static uint8_t state = 0;
-	static int8_t FRAM_result = 0;
-	static uint32_t old_Global_1msCounter = 0;
-	uint8_t tick = 0;
-	int8_t result = 0;
-	
-	if (Global_1msCounter != old_Global_1msCounter) tick = 1;
-	
-	switch (state) {
-		case 0:
-			if ( RelaisLEDs_TM_update(tick) == 1 )
-				state = 1;
-			break;
-		case 1: 
-		{
-			FRAM_update(tick);
-			if (FRAM_result == 0) {
-				FRAM_result = FRAM_Test_update();
-				if (FRAM_result > 0) Board_S.FRAM_Flags.B.test_ok = 1;
-				else if (FRAM_result < 0) Board_S.FRAM_Flags.B.test_fail = 1;
-			}
-			result = FRAM_result;
-//			Board_S.test_time = Global_1msCounter - TimeStamp;
-//			if ( Board_S.test_time >= TEST_TIMEOUT ) return -100;
-			break;
-		}
-	}
-	old_Global_1msCounter = Global_1msCounter;
-	
-	return result;
-}
-
-
-
-void BoardPeriph_update_1ms()
-{
-//	IMess_update();
-//	IMess_URef_update();
-	TempMess_update();
-}
-
-
-
-void BoardPeriph_update_polled()
-{
-	static uint32_t old_Global_1msCounter = 0;
-	uint8_t tick = 0;
-	if (Global_1msCounter != old_Global_1msCounter) {
-		tick = 1;
-	}
-	
-	FRAM_update(tick);
-	CAN0_update();
-	
-	old_Global_1msCounter = Global_1msCounter;
-}
-
-
-
-/*
-void do_Testroutine()
-{
-	FRAM_do_Test();
-	ADC_do_Test();
-	IMessLEM_do_Test();
-	TempADC_do_Test();
-}*/
+#include "BMS_Master.h"
+
+
+
+#define TEST_TIMEOUT	10000
+
+extern uint64_t Global_1msCounter; 
+static vuint32_t TimeStamp;
+
+static void init_BoardIO();
+
+static const Board_Status Board_Status_INIT = {{0},0};
+Board_Status Board_S;	//globaler BoardStatus
+
+
+
+void BoardPeriph_init()
+{
+	RelaisLEDs_init();
+	TempMess_init();
+    ADC_1_init();
+    Board_S = Board_Status_INIT;
+	Board_S.FRAM_Flags.B.init_ok = (FRAM_init()>=0) ? 1:0;
+}
+
+
+
+void BoardPeriph_test_init()
+{
+	TimeStamp = Global_1msCounter;
+	FRAM_trigger_Test();
+}
+
+
+
+int8_t BoardPeriph_test_update_polled()
+{
+	static uint8_t state = 0;
+	static int8_t FRAM_result = 0;
+	static uint32_t old_Global_1msCounter = 0;
+	uint8_t tick = 0;
+	int8_t result = 0;
+	
+	if (Global_1msCounter != old_Global_1msCounter) tick = 1;
+	
+	switch (state) {
+		case 0:
+			if ( RelaisLEDs_TM_update(tick) == 1 )
+				state = 1;
+			break;
+		case 1: 
+		{
+			FRAM_update(tick);
+			if (FRAM_result == 0) {
+				FRAM_result = FRAM_Test_update();
+				if (FRAM_result > 0) Board_S.FRAM_Flags.B.test_ok = 1;
+				else if (FRAM_result < 0) Board_S.FRAM_Flags.B.test_fail = 1;
+			}
+			result = FRAM_result;
+//			Board_S.test_time = Global_1msCounter - TimeStamp;
+//			if ( Board_S.test_time >= TEST_TIMEOUT ) return -100;
+			break;
+		}
+	}
+	old_Global_1msCounter = Global_1msCounter;
+	
+	return result;
+}
+
+
+
+void BoardPeriph_update_1ms()
+{
+//	IMess_update();
+//	IMess_URef_update();
+	TempMess_update();
+}
+
+
+
+void BoardPeriph_update_polled()
+{
+	static uint32_t old_Global_1msCounter = 0;
+	uint8_t tick = 0;
+	if (Global_1msCounter != old_Global_1msCounter) {
+		tick = 1;
+	}
+	
+	FRAM_update(tick);
+	CAN0_update();
+	
+	old_Global_1msCounter = Global_1msCounter;
+}
+
+
+
+/*
+void do_Testroutine()
+{
+	FRAM_do_Test();
+	ADC_do_Test();
+	IMessLEM_do_Test();
+	TempADC_do_Test();
+}*/

+ 244 - 241
BMS Master/Sources/Device.c

@@ -1,241 +1,244 @@
-#include "BMS_Master.h"
-
-
-
-extern uint32_t __IVPR_VALUE; /* Interrupt Vector Prefix value from link file*/
-extern uint32_t IntcIsrVectorTable[];
-
-
-#define CHIPVERSION	F1
-
-
-
-void init_Device()
-{
-	//--INIT-----------------------------------------------
-	// (1) Disable Watchdog --------------------------
-	disableWatchdog(); /* Disable watchdog */
-	// -----------------------------------------------
-
-	INTC_InstallINTCInterruptHandler(&ISR_Timer_OS,59,10);	//irq(PIT0) = 59
-	INTC_InitINTCInterrupts();
-	Asm_initIrqVectors();
-    INTC.PSR[4].R = 2;		          /* Software interrupt 4 IRQ priority = 2 */
-	INTC.CPR_PRC0.B.PRI = 1;          /* Single Core: Lower INTC's current priority */
-		
-	/* (2) - Configure modes and activate all clock for all peripherals      */ 
-	initMODE();
-
-	/* (3) - Configure system clock dividers for 120Mhz Fsys                 */
-	CGM.Z0_DCR.B.DIV = 0x1;       /* Z0 clock divider to divide by 2        */
-	CGM.FLASH_DCR.B.DIV = 0x1;    /* Flash register interface /2 (default)  */
-	ECSM.MUDCR.B.RAM_WS=0x1;      /* RAM Wait states to divide by 2         */
-
-	/* (4) - Set system clock to 120MHz based on 40Mhz XTAL                  */
-	setPLL();                     /* Also enables CLKOUT On PA[0]           */     
-
-	initINTC();
-}
-
-
-
-/* ----------------------------- */
-/* Initialize Modes              */
-/* ----------------------------- */
-void initMODE()
-{            
-    ME.MER.R = 0x000025FF;          /* Enable all modes                     */
-    ME.RUNPC[0].R = 0x000000FE; 	/* Enable all peripherals in all modes  */
-    
-   /* Enable system clock for all peripherals assuming 120MHz system clock  */
-    CGM.SC_DC0.R = 0x83;          	/* Max 32MHz. Closest is 30MHz, Div+1=4 */
-    CGM.SC_DC1.R = 0x81;          	/* Max 64MHz. Closest is 60MHz, Div+1=2 */
-    CGM.SC_DC2.R = 0x81;          	/* Max 64MHz. Closest is 60MHz, Div+1=2 */
-
-    /* Re-enter DRUN mode to update the clock configuration                 */
-    ME.MCTL.R = 0x30005AF0;         /* DRUN Mode & Key                      */
-    ME.MCTL.R = 0x3000A50F;         /* DRUN Mode & Key                      */
-    while (ME.IS.B.I_MTC != 1) {}   /* Wait Until transition completed      */
-    ME.IS.B.I_MTC = 1;              /* Clear flag                           */   
-   
-    //CAN 
-    ME.RUNPC[1].R = 0x00000018; 	/* Peri. Cfg. 1 settings: only run in DRUN & RUN0 mode */
-    ME.PCTL[16].R = 0x01;           /* MPC56xxB/P/S FlexCAN0:select ME.RUNPC[1] */	
-//  ME.PCTL[17].R = 0x01;           /* MPC56xxB/S FlexCAN1:  select ME.RUNPC[1] */	
-    ME.PCTL[68].R = 0x01;           /* MPC56xxB/S SIUL:      select ME.RUNPC[1] */	
-    ME.PCTL[91].R = 0x01;           /* MPC56xxB/S RTC/API:   select ME.RUNPC[1] */	
-    ME.PCTL[92].R = 0x01;           /* MPC56xxB/S PIT_RTI:   select ME.RUNPC[1] */	
-    ME.PCTL[4].R = 0x01;           	/* MPC56xxB/S DSPI0:     select ME.RUNPC[1] */	
-    ME.PCTL[5].R = 0x01;           	/* MPC56xxB/S DSPI1:     select ME.RUNPC[1] */	
-    ME.PCTL[48].R = 0x01;           /* MPC56xxB/S LINFLEX0:  select ME.RUNPC[1] */	
-    ME.PCTL[49].R = 0x01;           /* MPC56xxB/S LINFLEX1:  select ME.RUNPC[1] */	
-}
-
-
-
-void init_Mode_and_Clock()
-{
-	//--PLL--
-	//Nur einstellen, wenn PLL nicht Sysclk
-	//F_vco = F_xtal * NDIV/(IDIF+1) = 256...512
-	//F_PLL_outclk = F_vco / 2^(ODIF+1)
-	CGM.FMPLL_CR.B.IDF= 3; /* Divide by 4 */
-	CGM.FMPLL_CR.B.ODF= 1; /* Divide by 4 */
-	CGM.FMPLL_CR.B.NDIV=48; /* Multiply 48 */
-	
-	/* Switch on external osc in DRUN mode */
-	ME.DRUN.B.FXOSC0ON=1;
-	//Set PLL to Soure in DRUN
-	ME.DRUN.B.SYSCLK=4;
-	
-	ME.MCTL.R = 0x30005AF0; /* Mode & Key */
-	ME.MCTL.R = 0x3000A50F; /* Mode & Key inverted */
-	while(ME.GS.B.S_MTRANS == 1) {} /* Wait for mode transition complete */
-	/* Error trap - if current mode is not DRUM (eg safe mode), then loop */
-	while(ME.GS.B.S_CURRENTMODE != 3) {}
-
-	/* Wait for external OSC to stabilize */
-	while(ME.GS.B.S_FXOSC != 1) {}
-
-	// wait for PLL to lock
-	while(CGM.FMPLL_CR.B.S_LOCK==0) {}
-	
-	/* Enable CLKOUT pin so clock frequency can be verified */
-	CGM.OC_EN.B.EN=1; 		/* Enable Output clock */
-	CGM.OCDS_SC.R =0x23; 	/* And seclect output as system clock / 4 */
-	SIU.PCR[0].R = 0x0A04; 	/* PA0 ALT2 function (Clkout), MAX SRC */
-}
-
-
-
-/* ----------------------------- */
-/* PLL to 120Mhz (40Mhz xtal) */
-/* ----------------------------- */
-void setPLL()
-{
-	/* Note - in example code below the flow is: */
-	/* Switch on osc, change mode and wait for osc ON */
-	/* Configure and enable PLL, change mode and wait for PLL to lock */
-	/* Set clock source as PLL, change mode and check clock is PLL */
-	/* */
-
-	/* However, do not actually have to do all 3 mode changes. Can */
-	/* switch on osc, enable PLL and Set PLL as clock source THEN do a */
-	/* single mode change. The ME module must be smart enough to look */
-	/* at which bits are set and see if it's a valid combination of */
-	/* bits. However, if there is an issue, there is no way of seeing */
-	/* what caused the problem! */
-#ifdef EVALBOARD
-	/* Switch on external osc in DRUN mode */
-	ME.DRUN.B.FXOSC0ON=1;
-#else
-	//MasterBoard
-	CGM.FXOSC_CTL.B.OSCBYP=1;
-	ME.DRUN.B.FXOSC0ON=1;
-#endif
-	/* Re-Enter DRUN mode (mode=0x3) to activate change */
-	ME.MCTL.R = 0x30005AF0; /* Mode & Key */
-	ME.MCTL.R = 0x3000A50F; /* Mode & Key inverted */
-	while(ME.GS.B.S_MTRANS == 1) {} /* Wait for mode transition complete */
-
-	/* Error trap - if current mode is not DRUM (eg in safe mode), then loop */
-	while(ME.GS.B.S_CURRENTMODE != 3) {}
-
-	/* Wait for external OSC to stabilize */
-	while(ME.GS.B.S_FXOSC != 1) {}
-
-	/* Select External OSC as the FMPLL Reference Clock Source */
-#if CHIPVERSION == F1
-	CGM.AC0_SC.B.SELCTL = 0x0;
-#elif CHIPVERSION == F0
-	CGM.AC0_SC.B.SELCTL = 0x1;
-#else
-	#error Device.c: Keine gültige Cipversion ausgewählt
-#endif
-
-	/* Configure PLL for 120MHz with 40MHz xtal */
-	/* PLL frequency = (40 * NDIV) / (IDF * ODF) */
-	/* VCO (PLL * ODF) must be between 256 and 512MHz */
-	/* */
-	/* For 120Mhz Output: */
-
-	/* ODF deliviers are 2, 4, 8, 16. /4 gives VCO of 480 (in range) */
-	/* With ODF = 2, NDIV = 12xIDF. Chose IDF =5, therefore NDIV = 60 */
-	CGM.FMPLL_CR.B.IDF=0x4; /* Divide by 5 */
-	CGM.FMPLL_CR.B.ODF=0x1; /* Divide by 4 */
-	CGM.FMPLL_CR.B.NDIV=60; /* Divide by 60 */
-	/* Enable PLL in DRUN mode. */
-	ME.DRUN.B.FMPLLON = 1;
-
-	/* Re-Enter DRUN mode (mode=0x3) to activate change */
-	ME.MCTL.R = 0x30005AF0; /* Mode & Key */
-	ME.MCTL.R = 0x3000A50F; /* Mode & Key inverted */
-
-	while(ME.GS.B.S_MTRANS == 1) {} /* Wait for mode transition complete */
-	/* Error trap - if current mode is not DRUM (eg safe mode), then loop */
-	while(ME.GS.B.S_CURRENTMODE != 3) {}
-	/* wait for PLL to lock (will not lock until re-enter DRUN mode */
-	while(CGM.FMPLL_CR.B.S_LOCK==0) {}
-	/* Finally set system clock to be PLL in DRUN mode */
-	ME.DRUN.B.SYSCLK=0x4;
-
-	/* Re-Enter DRUN mode (mode=0x3) to activate change */
-	// Application Code
-	// Getting started with the MPC564xB/C Microcontroller, Rev. 0, 12/2010
-	// 20 Freescale Semiconductor, Inc.
-	ME.MCTL.R = 0x30005AF0; /* Mode & Key */
-	ME.MCTL.R = 0x3000A50F; /* Mode & Key inverted */
-	while(ME.GS.B.S_MTRANS == 1) {} /* Wait for mode transition complete */
-
-	/* Error trap - if current mode is not DRUM (eg safe mode), then loop */
-	while(ME.GS.B.S_CURRENTMODE != 3) {}
-
-	/* Final check - ensure ME_GS reports clock as system PLL (0x4) */
-	while(ME.GS.B.S_SYSCLK != 4) {} /* fail if stuck here */
-
-	/* Enable CLKOUT pin so clock frequency can be verified */
-	CGM.OC_EN.B.EN=1; 		/* Enable Output clock */
-	CGM.OCDS_SC.R =0x23; 	/* And seclect output as system clock / 4 */
-	SIU.PCR[0].R = 0x0A04; 	/* PA0 ALT2 function (Clkout), MAX SRC */
-}
-
-
-
-void disableWatchdog()
-{
-  SWT.SR.R = 0x0000c520;     /* Write keys to clear soft lock bit */
-  SWT.SR.R = 0x0000d928; 
-  SWT.CR.R = 0x8000010A;     /* Clear watchdog enable (WEN) */
-}        
-
-
-
-void initINTC()
-{	
-  INTC.MCR.B.HVEN_PRC0 = 1;       /* 0 -> SW vector mode */
-  INTC.MCR.B.VTES_PRC0 = 0;       /* Single core: Use default vector table 4B offsets */
-  INTC.IACKR_PRC0.R = 2;    /* MPC555x: INTC ISR table base */
-  INTC.PSR[59].R = 4;           /* PIT 0 interrupt vector with priority 1 */
-  INTC.PSR[0].R = 3;		/* Software interrupt 0 IRQ priority = 2 */
-  INTC.PSR[1].R = 2;		/* Software interrupt 1 IRQ priority = 2 */
-  INTC.PSR[2].R = 1;		/* Software interrupt 2 IRQ priority = 2 */
-}
-
-
-
-void enableIrq()
-{
-  INTC.CPR_PRC0.B.PRI = 0;          /* Single Core: Lower INTC's current priority */
-  asm(" wrteei 1");	    	   /* Enable external interrupts */
-}
-
-
-
-void Asm_initIrqVectors( void )
-{
-  asm(" lis r3, __IVPR_VALUE@h");   /* IVPR value is passed from link file */
-  asm(" ori r3, r3, __IVPR_VALUE@l"); 
-  asm(" mtivpr  r3");
-  asm(" li r3, 0x40");  
-  asm(" mtivor4 r3");  							 
-}
+#include "BMS_Master.h"
+
+
+
+extern uint32_t __IVPR_VALUE; /* Interrupt Vector Prefix value from link file*/
+extern uint32_t IntcIsrVectorTable[];
+
+
+#define CHIPVERSION	F1
+
+
+
+void init_Device()
+{
+	//--INIT-----------------------------------------------
+	// (1) Disable Watchdog --------------------------
+	disableWatchdog(); /* Disable watchdog */
+	// -----------------------------------------------
+
+	INTC_InstallINTCInterruptHandler(&ISR_Timer_OS,59,10);	//irq(PIT0) = 59
+	INTC_InitINTCInterrupts();
+	Asm_initIrqVectors();
+    INTC.PSR[4].R = 2;		          /* Software interrupt 4 IRQ priority = 2 */
+	INTC.CPR_PRC0.B.PRI = 1;          /* Single Core: Lower INTC's current priority */
+		
+	/* (2) - Configure modes and activate all clock for all peripherals      */ 
+	initMODE();
+
+	/* (3) - Configure system clock dividers for 120Mhz Fsys                 */
+	CGM.Z0_DCR.B.DIV = 0x1;       /* Z0 clock divider to divide by 2        */
+	CGM.FLASH_DCR.B.DIV = 0x1;    /* Flash register interface /2 (default)  */
+	ECSM.MUDCR.B.RAM_WS=0x1;      /* RAM Wait states to divide by 2         */
+
+	/* (4) - Set system clock to 120MHz based on 40Mhz XTAL                  */
+	setPLL();                     /* Also enables CLKOUT On PA[0]           */     
+
+	initINTC();
+}
+
+
+
+/* ----------------------------- */
+/* Initialize Modes              */
+/* ----------------------------- */
+void initMODE()
+{            
+    ME.MER.R = 0x000025FF;          /* Enable all modes                     */
+    ME.RUNPC[0].R = 0x000000FE; 	/* Enable all peripherals in all modes  */
+    
+   /* Enable system clock for all peripherals assuming 120MHz system clock  */
+    CGM.SC_DC0.R = 0x83;          	/* Max 32MHz. Closest is 30MHz, Div+1=4 */
+    CGM.SC_DC1.R = 0x81;          	/* Max 64MHz. Closest is 60MHz, Div+1=2 */
+    CGM.SC_DC2.R = 0x81;          	/* Max 64MHz. Closest is 60MHz, Div+1=2 */
+
+    /* Re-enter DRUN mode to update the clock configuration                 */
+    ME.MCTL.R = 0x30005AF0;         /* DRUN Mode & Key                      */
+    ME.MCTL.R = 0x3000A50F;         /* DRUN Mode & Key                      */
+    while (ME.IS.B.I_MTC != 1) {}   /* Wait Until transition completed      */
+    ME.IS.B.I_MTC = 1;              /* Clear flag                           */   
+   
+    //CAN 
+    ME.RUNPC[1].R = 0x00000018; 	/* Peri. Cfg. 1 settings: only run in DRUN & RUN0 mode */
+    ME.PCTL[16].R = 0x01;           /* MPC56xxB/P/S FlexCAN0:select ME.RUNPC[1] */	
+//  ME.PCTL[17].R = 0x01;           /* MPC56xxB/S FlexCAN1:  select ME.RUNPC[1] */	
+    ME.PCTL[68].R = 0x01;           /* MPC56xxB/S SIUL:      select ME.RUNPC[1] */	
+    ME.PCTL[91].R = 0x01;           /* MPC56xxB/S RTC/API:   select ME.RUNPC[1] */	
+    ME.PCTL[92].R = 0x01;           /* MPC56xxB/S PIT_RTI:   select ME.RUNPC[1] */	
+    ME.PCTL[4].R = 0x01;           	/* MPC56xxB/S DSPI0:     select ME.RUNPC[1] */	
+    ME.PCTL[5].R = 0x01;           	/* MPC56xxB/S DSPI1:     select ME.RUNPC[1] */	
+    ME.PCTL[48].R = 0x01;           /* MPC56xxB/S LINFLEX0:  select ME.RUNPC[1] */	
+    ME.PCTL[49].R = 0x01;           /* MPC56xxB/S LINFLEX1:  select ME.RUNPC[1] */	
+    
+	//ADC
+	ME.PCTL[33].R = 0x01;           /* MPC5646C   ADC_1:     select ME.RUNPC[1] */
+}
+
+
+
+void init_Mode_and_Clock()
+{
+	//--PLL--
+	//Nur einstellen, wenn PLL nicht Sysclk
+	//F_vco = F_xtal * NDIV/(IDIF+1) = 256...512
+	//F_PLL_outclk = F_vco / 2^(ODIF+1)
+	CGM.FMPLL_CR.B.IDF= 3; /* Divide by 4 */
+	CGM.FMPLL_CR.B.ODF= 1; /* Divide by 4 */
+	CGM.FMPLL_CR.B.NDIV=48; /* Multiply 48 */
+	
+	/* Switch on external osc in DRUN mode */
+	ME.DRUN.B.FXOSC0ON=1;
+	//Set PLL to Soure in DRUN
+	ME.DRUN.B.SYSCLK=4;
+	
+	ME.MCTL.R = 0x30005AF0; /* Mode & Key */
+	ME.MCTL.R = 0x3000A50F; /* Mode & Key inverted */
+	while(ME.GS.B.S_MTRANS == 1) {} /* Wait for mode transition complete */
+	/* Error trap - if current mode is not DRUM (eg safe mode), then loop */
+	while(ME.GS.B.S_CURRENTMODE != 3) {}
+
+	/* Wait for external OSC to stabilize */
+	while(ME.GS.B.S_FXOSC != 1) {}
+
+	// wait for PLL to lock
+	while(CGM.FMPLL_CR.B.S_LOCK==0) {}
+	
+	/* Enable CLKOUT pin so clock frequency can be verified */
+	CGM.OC_EN.B.EN=1; 		/* Enable Output clock */
+	CGM.OCDS_SC.R =0x23; 	/* And seclect output as system clock / 4 */
+	SIU.PCR[0].R = 0x0A04; 	/* PA0 ALT2 function (Clkout), MAX SRC */
+}
+
+
+
+/* ----------------------------- */
+/* PLL to 120Mhz (40Mhz xtal) */
+/* ----------------------------- */
+void setPLL()
+{
+	/* Note - in example code below the flow is: */
+	/* Switch on osc, change mode and wait for osc ON */
+	/* Configure and enable PLL, change mode and wait for PLL to lock */
+	/* Set clock source as PLL, change mode and check clock is PLL */
+	/* */
+
+	/* However, do not actually have to do all 3 mode changes. Can */
+	/* switch on osc, enable PLL and Set PLL as clock source THEN do a */
+	/* single mode change. The ME module must be smart enough to look */
+	/* at which bits are set and see if it's a valid combination of */
+	/* bits. However, if there is an issue, there is no way of seeing */
+	/* what caused the problem! */
+#ifdef EVALBOARD
+	/* Switch on external osc in DRUN mode */
+	ME.DRUN.B.FXOSC0ON=1;
+#else
+	//MasterBoard
+	CGM.FXOSC_CTL.B.OSCBYP=1;
+	ME.DRUN.B.FXOSC0ON=1;
+#endif
+	/* Re-Enter DRUN mode (mode=0x3) to activate change */
+	ME.MCTL.R = 0x30005AF0; /* Mode & Key */
+	ME.MCTL.R = 0x3000A50F; /* Mode & Key inverted */
+	while(ME.GS.B.S_MTRANS == 1) {} /* Wait for mode transition complete */
+
+	/* Error trap - if current mode is not DRUM (eg in safe mode), then loop */
+	while(ME.GS.B.S_CURRENTMODE != 3) {}
+
+	/* Wait for external OSC to stabilize */
+	while(ME.GS.B.S_FXOSC != 1) {}
+
+	/* Select External OSC as the FMPLL Reference Clock Source */
+#if CHIPVERSION == F1
+	CGM.AC0_SC.B.SELCTL = 0x0;
+#elif CHIPVERSION == F0
+	CGM.AC0_SC.B.SELCTL = 0x1;
+#else
+	#error Device.c: Keine gültige Cipversion ausgewählt
+#endif
+
+	/* Configure PLL for 120MHz with 40MHz xtal */
+	/* PLL frequency = (40 * NDIV) / (IDF * ODF) */
+	/* VCO (PLL * ODF) must be between 256 and 512MHz */
+	/* */
+	/* For 120Mhz Output: */
+
+	/* ODF deliviers are 2, 4, 8, 16. /4 gives VCO of 480 (in range) */
+	/* With ODF = 2, NDIV = 12xIDF. Chose IDF =5, therefore NDIV = 60 */
+	CGM.FMPLL_CR.B.IDF=0x4; /* Divide by 5 */
+	CGM.FMPLL_CR.B.ODF=0x1; /* Divide by 4 */
+	CGM.FMPLL_CR.B.NDIV=60; /* Divide by 60 */
+	/* Enable PLL in DRUN mode. */
+	ME.DRUN.B.FMPLLON = 1;
+
+	/* Re-Enter DRUN mode (mode=0x3) to activate change */
+	ME.MCTL.R = 0x30005AF0; /* Mode & Key */
+	ME.MCTL.R = 0x3000A50F; /* Mode & Key inverted */
+
+	while(ME.GS.B.S_MTRANS == 1) {} /* Wait for mode transition complete */
+	/* Error trap - if current mode is not DRUM (eg safe mode), then loop */
+	while(ME.GS.B.S_CURRENTMODE != 3) {}
+	/* wait for PLL to lock (will not lock until re-enter DRUN mode */
+	while(CGM.FMPLL_CR.B.S_LOCK==0) {}
+	/* Finally set system clock to be PLL in DRUN mode */
+	ME.DRUN.B.SYSCLK=0x4;
+
+	/* Re-Enter DRUN mode (mode=0x3) to activate change */
+	// Application Code
+	// Getting started with the MPC564xB/C Microcontroller, Rev. 0, 12/2010
+	// 20 Freescale Semiconductor, Inc.
+	ME.MCTL.R = 0x30005AF0; /* Mode & Key */
+	ME.MCTL.R = 0x3000A50F; /* Mode & Key inverted */
+	while(ME.GS.B.S_MTRANS == 1) {} /* Wait for mode transition complete */
+
+	/* Error trap - if current mode is not DRUM (eg safe mode), then loop */
+	while(ME.GS.B.S_CURRENTMODE != 3) {}
+
+	/* Final check - ensure ME_GS reports clock as system PLL (0x4) */
+	while(ME.GS.B.S_SYSCLK != 4) {} /* fail if stuck here */
+
+	/* Enable CLKOUT pin so clock frequency can be verified */
+	CGM.OC_EN.B.EN=1; 		/* Enable Output clock */
+	CGM.OCDS_SC.R =0x23; 	/* And seclect output as system clock / 4 */
+	SIU.PCR[0].R = 0x0A04; 	/* PA0 ALT2 function (Clkout), MAX SRC */
+}
+
+
+
+void disableWatchdog()
+{
+  SWT.SR.R = 0x0000c520;     /* Write keys to clear soft lock bit */
+  SWT.SR.R = 0x0000d928; 
+  SWT.CR.R = 0x8000010A;     /* Clear watchdog enable (WEN) */
+}        
+
+
+
+void initINTC()
+{	
+  INTC.MCR.B.HVEN_PRC0 = 1;       /* 0 -> SW vector mode */
+  INTC.MCR.B.VTES_PRC0 = 0;       /* Single core: Use default vector table 4B offsets */
+  INTC.IACKR_PRC0.R = 2;    /* MPC555x: INTC ISR table base */
+  INTC.PSR[59].R = 4;           /* PIT 0 interrupt vector with priority 1 */
+  INTC.PSR[0].R = 3;		/* Software interrupt 0 IRQ priority = 2 */
+  INTC.PSR[1].R = 2;		/* Software interrupt 1 IRQ priority = 2 */
+  INTC.PSR[2].R = 1;		/* Software interrupt 2 IRQ priority = 2 */
+}
+
+
+
+void enableIrq()
+{
+  INTC.CPR_PRC0.B.PRI = 0;          /* Single Core: Lower INTC's current priority */
+  asm(" wrteei 1");	    	   /* Enable external interrupts */
+}
+
+
+
+void Asm_initIrqVectors( void )
+{
+  asm(" lis r3, __IVPR_VALUE@h");   /* IVPR value is passed from link file */
+  asm(" ori r3, r3, __IVPR_VALUE@l"); 
+  asm(" mtivpr  r3");
+  asm(" li r3, 0x40");  
+  asm(" mtivor4 r3");  							 
+}

+ 356 - 356
BMS Master/Sources/FlexCAN.c

@@ -1,356 +1,356 @@
-//==============================================================================
-// Purpose:    allgemeines CAN Interface für FlexCAN von MPC5646
-//
-// Created on:  20.04.2012 by IPE
-//
-// History
-//		20.04.2012 neu, T.Maurer
-//		29.07.2013 CAN_Init() modified V.Reiling
-//      26.02.2016 CAN_Init() modified V.Reiling: Sample Point at 87.5%
-//==============================================================================
-
-#include "BMS_Master.h"
-
-
-//CAN - MESSAGEBOX-STATUS-CODES
-#define CAN_MBCODE_RXINACTIVE		0
-#define CAN_MBCODE_RXEMPTY			4
-#define CAN_MBCODE_RXFULL			2
-#define CAN_MBCODE_RXOVERRUN		6	//	MB war voll und wurde nicht von CPU ausgelesen
-#define CAN_MBCODE_RXBUSY			1	//	(XXX1)
-
-#define CAN_MBCODE_TXINACTIVE		8	//Grundzustand
-#define CAN_MBCODE_TXABORT			9	//ABORT muss mit MCR.AEN freigegeben werden
-#define CAN_MBCODE_TXSEND			12	//RTR=0 -> sende Data, wenn beendet: Rückkehr zu INACTIVE;
-										//RTR=1 -> sende RemoteFrame, Wenn fertig: neuer Zustand = CAN_MBCODE_RXEMPTY
-#define CAN_MBCODE_TXREMOTEWAIT		10	//warte auf Remote request und sende Data zurück (-> CAN_MBCODE_TXREMOTESEND)
-#define CAN_MBCODE_TXREMOTESEND		16	//sende Data nach Remote request, wenn beendet: Rückkehr zu CAN_MBCODE_TXREMOTEWAIT;
-
-
-//Abort Enable des Boards verwenden?
-#define CAN_AEN 	0
-
-
-//Funktionen
-int8_t CAN_Init(CAN_CONFIG *config)
-{
-	volatile struct FLEXCAN_tag *p_CAN = config->CAN_Modul; 
-	uint8_t	i;
-	
-																// Fehler-Check: CAN-Modul-Adresse vorhanden?
-	if ((p_CAN != &CAN_0) && 
-		(p_CAN != &CAN_1) && 
-		(p_CAN != &CAN_2) &&
-		(p_CAN != &CAN_3) && 
-		(p_CAN != &CAN_4) && 
-		(p_CAN != &CAN_5) )
-		return CAN_ERROR;
-																// MCR-Register, die meisten Bits koennen nur im FreezeMode beschrieben werden
-	p_CAN->MCR.B.MDIS = 0;										// Module Disable (init=1)
-	while (p_CAN->MCR.B.LPMACK) {}
-	p_CAN->MCR.B.FRZ = 1; 										// FreezeMode enable (initVal=1)
-	p_CAN->MCR.B.HALT = 1; 										// FreezeMode ON (wenn FRZ=1);(initVal=1) Clear after module-init 
-	while (!p_CAN->MCR.B.FRZACK) {}								// warte auf FreezeMode
-	
-	p_CAN->MCR.B.BCC = 1; 										// 1 = Enable Indididual RxMasking
-	if (config->RxMaskType == RxMask_Global) 
-	{
-		p_CAN->MCR.B.BCC = 0; 									// 0 = Enable Global RxMasking
-		p_CAN->RXGMASK.R = config->GlobalRxMask;				// Global Acceptance Mask (InitVal = 0xFFFF_FFFF)
-	}
-		
-	p_CAN->MCR.B.AEN = CAN_AEN; 								// Abort Enable
-	p_CAN->MCR.B.SUPV = 0;										// Freeze mode only:
-															
-	switch( config->BaudConfig )
-	{
-		case CANBaud_1000kHz_OSC_40MHz :						// @ 40m Buslength
-			p_CAN->CR.B.CLKSRC 	= 0;							// CPI-ClockSource:  0=oscillator clock (40MHz); 1=bus clock (PLL/2=60MHz)   
-			p_CAN->CR.B.PRESDIV = 1;  							// f_SerialClock = f_CPI_clock / (PRESDIV + 1)
-			p_CAN->CR.B.PROPSEG = 7; 							// Propagation Segment Time = (PROPSEG + 1) * Time-Quanta.
-			p_CAN->CR.B.PSEG1 	= 7; 							// Phase Buffer Segment 1 = (PSEG1 + 1) x Time-Quanta.
-			p_CAN->CR.B.PSEG2 	= 2;							// Phase Buffer Segment 2 = (PSEG1 + 1) x Time-Quanta.
-			p_CAN->CR.B.RJW 	= 0;							// Resync Jump Width = RJW + 1.
-			break;
-	
-		case CANBaud_500kHz_OSC_40MHz :							// @ 100m Buslength
-			p_CAN->CR.B.CLKSRC 	= 0;							// CPI-ClockSource:  0=oscillator clock (40MHz); 1=bus clock (PLL/2=60MHz)   
-			p_CAN->CR.B.PRESDIV = 4;  							// f_SerialClock = f_CPI_clock / (PRESDIV + 1)
-			p_CAN->CR.B.PROPSEG = 4; 							// Propagation Segment Time = (PROPSEG + 1) * Time-Quanta.
-			p_CAN->CR.B.PSEG1 	= 7; 							// Phase Buffer Segment 1 = (PSEG1 + 1) x Time-Quanta.
-			p_CAN->CR.B.PSEG2 	= 1;							// Phase Buffer Segment 2 = (PSEG1 + 1) x Time-Quanta.
-			p_CAN->CR.B.RJW 	= 0;							// Resync Jump Width = RJW + 1.
-			break;
-				
-		case CANBaud_250kHz_OSC_40MHz :							// @ 200m Buslength
-			p_CAN->CR.B.CLKSRC 	= 0;							// CPI-ClockSource:  0=oscillator clock (40MHz); 1=bus clock (PLL/2=60MHz)   
-			p_CAN->CR.B.PRESDIV = 9;  							// f_SerialClock = f_CPI_clock / (PRESDIV + 1)
-			p_CAN->CR.B.PROPSEG = 4; 							// Propagation Segment Time = (PROPSEG + 1) * Time-Quanta.
-			p_CAN->CR.B.PSEG1 	= 7; 							// Phase Buffer Segment 1 = (PSEG1 + 1) x Time-Quanta.
-			p_CAN->CR.B.PSEG2 	= 1;							// Phase Buffer Segment 2 = (PSEG1 + 1) x Time-Quanta.
-			p_CAN->CR.B.RJW 	= 0;							// Resync Jump Width = RJW + 1.
-			break;
-				
-		case CANBaud_125kHz_OSC_40MHz :							// @ 420m Buslength
-			p_CAN->CR.B.CLKSRC 	= 0;							// CPI-ClockSource:  0=oscillator clock (40MHz); 1=bus clock (PLL/2=60MHz)   
-			p_CAN->CR.B.PRESDIV = 19;  							// f_SerialClock = f_CPI_clock / (PRESDIV + 1)
-			p_CAN->CR.B.PROPSEG = 4; 							// Propagation Segment Time = (PROPSEG + 1) * Time-Quanta.
-			p_CAN->CR.B.PSEG1 	= 7; 							// Phase Buffer Segment 1 = (PSEG1 + 1) x Time-Quanta.
-			p_CAN->CR.B.PSEG2 	= 1;							// Phase Buffer Segment 2 = (PSEG1 + 1) x Time-Quanta.
-			p_CAN->CR.B.RJW 	= 0;							// Resync Jump Width = RJW + 1.
-			break;
-								
-		default :
-			return CAN_ERROR;
-	}
-	p_CAN->CR.B.SMP = 1;										// Sampling Mode: 0=1 Sample, 1=3 Samples
-
-	switch( config->Port )
-	{
-		case CAN0_PortB0_1 :									// Config Ports: PB0 = CAN0_Tx, PB1 = CAN0_Rx
-			SIU.PCR[16].B.OBE 	= 1;							// Output Buffer Enable = Output
-			SIU.PCR[16].B.PA 	= 1;							// Pad Output Assignment = CAN0TX
-			SIU.PCR[16].B.ODE 	= (config->TxPortType==Tx_OpenDrain)? 1:0; // Open Drain Output Enable
-			SIU.PCR[16].B.SRC 	= 1;							// Slew Rate Control = Fast
-			SIU.PCR[17].B.IBE 	= 1;							// Input Buffer Enable = Input
-			break;
-			
-		case CAN1_PortC10_11 :									// Config Ports: PC10 = CAN1_Tx, PC11 = CAN1_Rx
-			SIU.PCR[42].B.OBE 	= 1;							// Output Buffer Enable = Output
-			SIU.PCR[42].B.PA 	= 1;							// Pad Output Assignment = CAN1TX
-			SIU.PCR[42].B.ODE 	= (config->TxPortType==Tx_OpenDrain)? 1:0; // Open Drain Output Enable
-			SIU.PCR[42].B.SRC 	= 1;							// Slew Rate Control = Fast
-			SIU.PCR[43].B.IBE 	= 1;							// Input Buffer Enable = Input
-			SIU.PSMI[0].R 		= 0x01;							// Peripheral input pin selection: CAN1RX -> PCR[43]
-			break;
-			
-		case CAN2_PortE8_9 :									// Config Ports: PE8 = CAN2_Tx, PE9 = CAN2_Rx
-			SIU.PCR[72].B.OBE 	= 1;							// Output Buffer Enable = Output
-			SIU.PCR[72].B.PA 	= 1;							// Pad Output Assignment = CAN2TX
-			SIU.PCR[72].B.ODE 	= (config->TxPortType==Tx_OpenDrain)? 1:0; // Open Drain Output Enable
-			SIU.PCR[72].B.SRC 	= 1;							// Slew Rate Control = Fast
-			SIU.PCR[73].B.IBE 	= 1;							// Input Buffer Enable = Input
-			SIU.PSMI[1].R 		= 0x00;							// Peripheral input pin selection: CAN2RX -> PCR[73]
-			break;
-
-		case CAN3_PortF8_9 :									// Config Ports: PF8 = CAN3_Tx, PF9 = CAN3_Rx
-			SIU.PCR[88].B.OBE 	= 1;							// Output Buffer Enable = Output
-			SIU.PCR[88].B.PA 	= 1;							// Pad Output Assignment = CAN3TX
-			SIU.PCR[88].B.ODE 	= (config->TxPortType==Tx_OpenDrain)? 1:0; // Open Drain Output Enable
-			SIU.PCR[88].B.SRC 	= 1;							// Slew Rate Control = Fast
-			SIU.PCR[89].B.IBE 	= 1;							// Input Buffer Enable = Input
-			SIU.PSMI[2].R 		= 0x02;							// Peripheral input pin selection: CAN3RX -> PCR[89]
-			break;			
-		
-		default :
-			return CAN_ERROR;
-	}
-	
-	p_CAN->MCR.B.MAXMB 	= 55;									// Max 64 Massage Buffer	
-	for (i=0; i<64; i++)
-		p_CAN->BUF[i].CS.B.CODE = CAN_MBCODE_RXINACTIVE;   		// Inactivate all message buffers 
-		
-	p_CAN->MCR.B.HALT 	= 0; 									// FreezeModeON-Bit; Clear after module-init (init=1)
-	p_CAN->MCR.B.FRZ 	= 0; 									// FreezeMode
-
-	return CAN_OK;
-}
-
-
-
-int8_t CAN_Init_Mailbox(CAN_MAILBOX *mbox)
-{
-	volatile struct FLEXCAN_BUF_t *p_BUF;	//pointer auf einen Message Buffer
-	volatile struct FLEXCAN_tag *p_CAN = mbox->p_CAN_Config->CAN_Modul;
-	
-	if (mbox->MBNumber >= 64) return CAN_ERROR;
-	p_BUF = p_CAN->BUF + mbox->MBNumber;
-	if (p_CAN->MCR.B.LPMACK) return CAN_ERROR;	//CAN in DisableMode
-	p_CAN->MCR.B.FRZ = 1; // FreezeMode enable (initVal=1)
-	p_CAN->MCR.B.HALT = 1; // FreezeMode ON (wenn FRZ=1);(initVal=1) Clear after module-init 
-	while (!p_CAN->MCR.B.FRZACK) {}	//warte auf FreezeMode
-	
-	if (mbox->RemoteEn >= 2) return CAN_ERROR;
-	p_BUF->CS.B.RTR =  mbox->RemoteEn;           /* Data frame, not remote Tx request frame */
-	if (mbox->Direction == MB_Tx) {
-		//TX-Box
-		if (mbox->DataBytes >= 9) return CAN_ERROR;
-		p_BUF->CS.B.LENGTH = mbox->DataBytes; /* # bytes to transmit*/
-		p_BUF->CS.B.CODE = CAN_MBCODE_TXINACTIVE;
-	}
-	else if (mbox->Direction == MB_Rx) {
-		//RX-Box
-		p_BUF->CS.B.CODE = CAN_MBCODE_RXEMPTY;
-		//Individuelle Acceptance Mask
-		if (mbox->p_CAN_Config->RxMaskType == RxMask_Individual)
-			p_CAN->RXIMR[mbox->MBNumber].R = mbox->AcceptMask;
-		//MB-Interrupt-Enable
-	}
-	else return CAN_ERROR;
-		
-	if( mbox->IDE == SHORT_ID)
-	{
-		p_BUF->CS.B.IDE = 0;          	// Use standard ID length
-		p_BUF->ID.B.STD_ID = mbox->ID;
-	}
-	else
-	{
-		p_BUF->CS.B.IDE = 1;          	// Use extended ID length
-		p_BUF->ID.B.EXT_ID = (mbox->ID & 0x3FFFF);
-		p_BUF->ID.B.STD_ID = (mbox->ID >> 18);
-	}
-	
-	if (mbox->Interrupt) {
-		if (mbox->MBNumber <= 31)			
-			SETBIT(p_CAN->IMRL.R, mbox->MBNumber); // Interrupt Mask 1
-		else
-			SETBIT(p_CAN->IMRH.R, mbox->MBNumber - 32);	// Interrupt Mask 2
-	}
-
-
-	p_CAN->MCR.B.HALT = 0; // FreezeMode ON (wenn FRZ=1);(initVal=1) Clear after module-init 
-	p_CAN->MCR.B.FRZ = 0; //FreezeMode; 
-	//init Ende
-	return CAN_OK;
-}
-
-
-int8_t CAN_Write(CAN_MAILBOX *mbox, uint8_t *data)
-{
-	uint8_t i;
-	volatile struct FLEXCAN_BUF_t *p_BUF;
-	volatile struct FLEXCAN_tag *p_CAN = mbox->p_CAN_Config->CAN_Modul;
-	
-	if (p_CAN->MCR.B.NOTRDY) return CAN_ERROR;
-	p_BUF = p_CAN->BUF + mbox->MBNumber;
-	if (mbox->MBNumber >= 64) return CAN_ERROR;
-
-	p_BUF->CS.B.CODE = CAN_MBCODE_TXINACTIVE;
-	//I-Flag löschen, um die MB zu entsperren
-/*	if (mbox->MBNumber < 32)
-		p_CAN->IFRL.R = 1 << mbox->MBNumber;
-	else
-		p_CAN->IFRH.R = 1 << (mbox->MBNumber-32);  
-
-*/	p_BUF = p_CAN->BUF + mbox->MBNumber;	//pointer auf einen Message Buffer
-	
-	if( mbox->IDE == SHORT_ID)
-		p_BUF->ID.B.STD_ID = mbox->ID;
-	else
-		p_BUF->ID.B.EXT_ID = mbox->ID;
-
-	for (i=0; i<mbox->DataBytes; i++) {
-		p_BUF->DATA.B[i] = *(data+i);      /* Data to be transmitted */
-	}
-//	CAN_0.BUF[0].CS.B.SRR = 1;           /* Tx frame (not req'd for standard frame)*/
-	p_BUF->CS.B.CODE = CAN_MBCODE_TXSEND;         /* Activate msg. buf. to transmit data frame */ 
-	return CAN_OK;
-}
-
-int8_t CAN_Write_dataset(CAN_MAILBOX *mbox, uint8_t* data,uint32_t timestamp)
-{
-	uint8_t i;
-	int8_t CAN_status=CAN_OK;
-	uint8_t	 dataSetSize= mbox->DataBytes;
-	volatile struct FLEXCAN_BUF_t *p_BUF;
-	volatile struct FLEXCAN_tag *p_CAN = mbox->p_CAN_Config->CAN_Modul;
-	p_BUF = p_CAN->BUF + mbox->MBNumber;
-	while(p_BUF->CS.B.CODE !=CAN_MBCODE_TXINACTIVE) {
-		//wait
-		if(Global_1msCounter >= timestamp + CAN1_TX_TIMEOUT) {
-			return CAN_ERROR;
-		}
-	}
-	CAN_status=CAN_Write(mbox,data);
-	timestamp=Global_1msCounter;
-	if(CAN_status != CAN_OK) {
-		return CAN_ERROR;
-	}
-	
-	return CAN_OK;
-}
-
-
-
-
-int8_t CAN_Read(CAN_MAILBOX *mbox, uint8_t *data)
-{
-	uint8_t i;
-	int8_t returnval;
-	uint32_t dummy;
-	volatile struct FLEXCAN_BUF_t *p_BUF;	//pointer auf einen Message Buffer
-	volatile struct FLEXCAN_tag *p_CAN = mbox->p_CAN_Config->CAN_Modul;
-	returnval = CAN_OK;
-	
-	if (mbox->MBNumber >= 64) return CAN_ERROR;
-	p_BUF = p_CAN->BUF + mbox->MBNumber;
-	dummy = p_BUF->CS.B.CODE;	//Muss ausgelesen werden zum Lock des Puffers
-	if (p_BUF->CS.B.LENGTH > CAN_DATA_ARR_LEN) returnval = CAN_ERROR;
-	if (p_BUF->CS.B.LENGTH != mbox->DataBytes) returnval = CAN_ERROR;
-	
-	if( mbox->IDE == SHORT_ID)
-		mbox->ID = p_BUF->ID.B.STD_ID;		// copy received ID to MailBox
-	else
-		mbox->ID = p_BUF->ID.B.EXT_ID;		// copy received ID to MailBox
-	
-	for (i=0; i < p_BUF->CS.B.LENGTH; i++){
-		*(data+i) = p_BUF->DATA.B[i];
-	}
-	//Timer auslesen und I-Flag löschen, um die MB zu entsperren	
-	dummy = p_CAN->TIMER.R;
-	// Clear Int-Flag 
-	if (mbox->MBNumber < 32)
-		p_CAN->IFRL.R = 1 << mbox->MBNumber;
-	else
-		p_CAN->IFRH.R = 1 << (mbox->MBNumber-32);  
-
-	return returnval;
-}
-
-// Funktionen
-
-int8_t CAN_Abort(CAN_MAILBOX *mbox)
-{
-	volatile struct FLEXCAN_BUF_t *p_BUF;
-	volatile struct FLEXCAN_tag *p_CAN = mbox->p_CAN_Config->CAN_Modul;
-	
-	p_BUF = p_CAN->BUF + mbox->MBNumber;	//pointer auf einen Message Buffer
-	if (mbox->Direction == MB_Rx) return CAN_ERROR;
-	#if CAN_AEN == 1
-		p_BUF->CS.B.CODE = CAN_MBCODE_TXABORT;
-	#else
-		p_BUF->CS.B.CODE = CAN_MBCODE_TXINACTIVE;
-	#endif
-	return CAN_OK;
-}
-
-/**
- * @function Check CAN Error State Register for Errors
- * @param config	pointer to CAN Module
- * @param	can_esr	 32 Bi vaiable for error state
- * @return TRUE if CAN IS OK, FALSE IF Error occured
- * 
- */
-uint8_t CAN_Get_error_Register(CAN_CONFIG *config,uint32_t* can_esr) {
-	volatile struct FLEXCAN_tag *p_CAN = config->CAN_Modul; 
-	if(p_CAN->ESR.R == 0) {
-		return TRUE;
-	}
-	else {
-		*can_esr=p_CAN->ESR.R;
-		return FALSE;
-	}
-}
-
-/**
- *@brief Check if CAN Errors occured
- */
-int8_t CAN_Check_error_Register(CAN_CONFIG *config) {
-	volatile struct FLEXCAN_tag *p_CAN = config->CAN_Modul; 
-	if(p_CAN->ESR.R == 0) {
-		return CAN_OK;
-	}
-	else {
-		return CAN_ERROR;
-	}
-}
+//==============================================================================
+// Purpose:    allgemeines CAN Interface für FlexCAN von MPC5646
+//
+// Created on:  20.04.2012 by IPE
+//
+// History
+//		20.04.2012 neu, T.Maurer
+//		29.07.2013 CAN_Init() modified V.Reiling
+//      26.02.2016 CAN_Init() modified V.Reiling: Sample Point at 87.5%
+//==============================================================================
+
+#include "BMS_Master.h"
+
+
+//CAN - MESSAGEBOX-STATUS-CODES
+#define CAN_MBCODE_RXINACTIVE		0
+#define CAN_MBCODE_RXEMPTY			4
+#define CAN_MBCODE_RXFULL			2
+#define CAN_MBCODE_RXOVERRUN		6	//	MB war voll und wurde nicht von CPU ausgelesen
+#define CAN_MBCODE_RXBUSY			1	//	(XXX1)
+
+#define CAN_MBCODE_TXINACTIVE		8	//Grundzustand
+#define CAN_MBCODE_TXABORT			9	//ABORT muss mit MCR.AEN freigegeben werden
+#define CAN_MBCODE_TXSEND			12	//RTR=0 -> sende Data, wenn beendet: Rückkehr zu INACTIVE;
+										//RTR=1 -> sende RemoteFrame, Wenn fertig: neuer Zustand = CAN_MBCODE_RXEMPTY
+#define CAN_MBCODE_TXREMOTEWAIT		10	//warte auf Remote request und sende Data zurück (-> CAN_MBCODE_TXREMOTESEND)
+#define CAN_MBCODE_TXREMOTESEND		16	//sende Data nach Remote request, wenn beendet: Rückkehr zu CAN_MBCODE_TXREMOTEWAIT;
+
+
+//Abort Enable des Boards verwenden?
+#define CAN_AEN 	0
+
+
+//Funktionen
+int8_t CAN_Init(CAN_CONFIG *config)
+{
+	volatile struct FLEXCAN_tag *p_CAN = config->CAN_Modul; 
+	uint8_t	i;
+	
+																// Fehler-Check: CAN-Modul-Adresse vorhanden?
+	if ((p_CAN != &CAN_0) && 
+		(p_CAN != &CAN_1) && 
+		(p_CAN != &CAN_2) &&
+		(p_CAN != &CAN_3) && 
+		(p_CAN != &CAN_4) && 
+		(p_CAN != &CAN_5) )
+		return CAN_ERROR;
+																// MCR-Register, die meisten Bits koennen nur im FreezeMode beschrieben werden
+	p_CAN->MCR.B.MDIS = 0;										// Module Disable (init=1)
+	while (p_CAN->MCR.B.LPMACK) {}
+	p_CAN->MCR.B.FRZ = 1; 										// FreezeMode enable (initVal=1)
+	p_CAN->MCR.B.HALT = 1; 										// FreezeMode ON (wenn FRZ=1);(initVal=1) Clear after module-init 
+	while (!p_CAN->MCR.B.FRZACK) {}								// warte auf FreezeMode
+	
+	p_CAN->MCR.B.BCC = 1; 										// 1 = Enable Indididual RxMasking
+	if (config->RxMaskType == RxMask_Global) 
+	{
+		p_CAN->MCR.B.BCC = 0; 									// 0 = Enable Global RxMasking
+		p_CAN->RXGMASK.R = config->GlobalRxMask;				// Global Acceptance Mask (InitVal = 0xFFFF_FFFF)
+	}
+		
+	p_CAN->MCR.B.AEN = CAN_AEN; 								// Abort Enable
+	p_CAN->MCR.B.SUPV = 0;										// Freeze mode only:
+															
+	switch( config->BaudConfig )
+	{
+		case CANBaud_1000kHz_OSC_40MHz :						// @ 40m Buslength
+			p_CAN->CR.B.CLKSRC 	= 0;							// CPI-ClockSource:  0=oscillator clock (40MHz); 1=bus clock (PLL/2=60MHz)   
+			p_CAN->CR.B.PRESDIV = 1;  							// f_SerialClock = f_CPI_clock / (PRESDIV + 1)
+			p_CAN->CR.B.PROPSEG = 7; 							// Propagation Segment Time = (PROPSEG + 1) * Time-Quanta.
+			p_CAN->CR.B.PSEG1 	= 7; 							// Phase Buffer Segment 1 = (PSEG1 + 1) x Time-Quanta.
+			p_CAN->CR.B.PSEG2 	= 2;							// Phase Buffer Segment 2 = (PSEG1 + 1) x Time-Quanta.
+			p_CAN->CR.B.RJW 	= 0;							// Resync Jump Width = RJW + 1.
+			break;
+	
+		case CANBaud_500kHz_OSC_40MHz :							// @ 100m Buslength
+			p_CAN->CR.B.CLKSRC 	= 0;							// CPI-ClockSource:  0=oscillator clock (40MHz); 1=bus clock (PLL/2=60MHz)   
+			p_CAN->CR.B.PRESDIV = 4;  							// f_SerialClock = f_CPI_clock / (PRESDIV + 1)
+			p_CAN->CR.B.PROPSEG = 4; 							// Propagation Segment Time = (PROPSEG + 1) * Time-Quanta.
+			p_CAN->CR.B.PSEG1 	= 7; 							// Phase Buffer Segment 1 = (PSEG1 + 1) x Time-Quanta.
+			p_CAN->CR.B.PSEG2 	= 1;							// Phase Buffer Segment 2 = (PSEG1 + 1) x Time-Quanta.
+			p_CAN->CR.B.RJW 	= 0;							// Resync Jump Width = RJW + 1.
+			break;
+				
+		case CANBaud_250kHz_OSC_40MHz :							// @ 200m Buslength
+			p_CAN->CR.B.CLKSRC 	= 0;							// CPI-ClockSource:  0=oscillator clock (40MHz); 1=bus clock (PLL/2=60MHz)   
+			p_CAN->CR.B.PRESDIV = 9;  							// f_SerialClock = f_CPI_clock / (PRESDIV + 1)
+			p_CAN->CR.B.PROPSEG = 4; 							// Propagation Segment Time = (PROPSEG + 1) * Time-Quanta.
+			p_CAN->CR.B.PSEG1 	= 7; 							// Phase Buffer Segment 1 = (PSEG1 + 1) x Time-Quanta.
+			p_CAN->CR.B.PSEG2 	= 1;							// Phase Buffer Segment 2 = (PSEG1 + 1) x Time-Quanta.
+			p_CAN->CR.B.RJW 	= 0;							// Resync Jump Width = RJW + 1.
+			break;
+				
+		case CANBaud_125kHz_OSC_40MHz :							// @ 420m Buslength
+			p_CAN->CR.B.CLKSRC 	= 0;							// CPI-ClockSource:  0=oscillator clock (40MHz); 1=bus clock (PLL/2=60MHz)   
+			p_CAN->CR.B.PRESDIV = 19;  							// f_SerialClock = f_CPI_clock / (PRESDIV + 1)
+			p_CAN->CR.B.PROPSEG = 4; 							// Propagation Segment Time = (PROPSEG + 1) * Time-Quanta.
+			p_CAN->CR.B.PSEG1 	= 7; 							// Phase Buffer Segment 1 = (PSEG1 + 1) x Time-Quanta.
+			p_CAN->CR.B.PSEG2 	= 1;							// Phase Buffer Segment 2 = (PSEG1 + 1) x Time-Quanta.
+			p_CAN->CR.B.RJW 	= 0;							// Resync Jump Width = RJW + 1.
+			break;
+								
+		default :
+			return CAN_ERROR;
+	}
+	p_CAN->CR.B.SMP = 1;										// Sampling Mode: 0=1 Sample, 1=3 Samples
+
+	switch( config->Port )
+	{
+		case CAN0_PortB0_1 :									// Config Ports: PB0 = CAN0_Tx, PB1 = CAN0_Rx
+			SIU.PCR[16].B.OBE 	= 1;							// Output Buffer Enable = Output
+			SIU.PCR[16].B.PA 	= 1;							// Pad Output Assignment = CAN0TX
+			SIU.PCR[16].B.ODE 	= (config->TxPortType==Tx_OpenDrain)? 1:0; // Open Drain Output Enable
+			SIU.PCR[16].B.SRC 	= 1;							// Slew Rate Control = Fast
+			SIU.PCR[17].B.IBE 	= 1;							// Input Buffer Enable = Input
+			break;
+			
+		case CAN1_PortC10_11 :									// Config Ports: PC10 = CAN1_Tx, PC11 = CAN1_Rx
+			SIU.PCR[42].B.OBE 	= 1;							// Output Buffer Enable = Output
+			SIU.PCR[42].B.PA 	= 1;							// Pad Output Assignment = CAN1TX
+			SIU.PCR[42].B.ODE 	= (config->TxPortType==Tx_OpenDrain)? 1:0; // Open Drain Output Enable
+			SIU.PCR[42].B.SRC 	= 1;							// Slew Rate Control = Fast
+			SIU.PCR[43].B.IBE 	= 1;							// Input Buffer Enable = Input
+			SIU.PSMI[0].R 		= 0x01;							// Peripheral input pin selection: CAN1RX -> PCR[43]
+			break;
+			
+		case CAN2_PortE8_9 :									// Config Ports: PE8 = CAN2_Tx, PE9 = CAN2_Rx
+			SIU.PCR[72].B.OBE 	= 1;							// Output Buffer Enable = Output
+			SIU.PCR[72].B.PA 	= 1;							// Pad Output Assignment = CAN2TX
+			SIU.PCR[72].B.ODE 	= (config->TxPortType==Tx_OpenDrain)? 1:0; // Open Drain Output Enable
+			SIU.PCR[72].B.SRC 	= 1;							// Slew Rate Control = Fast
+			SIU.PCR[73].B.IBE 	= 1;							// Input Buffer Enable = Input
+			SIU.PSMI[1].R 		= 0x00;							// Peripheral input pin selection: CAN2RX -> PCR[73]
+			break;
+
+		case CAN3_PortF8_9 :									// Config Ports: PF8 = CAN3_Tx, PF9 = CAN3_Rx
+			SIU.PCR[88].B.OBE 	= 1;							// Output Buffer Enable = Output
+			SIU.PCR[88].B.PA 	= 1;							// Pad Output Assignment = CAN3TX
+			SIU.PCR[88].B.ODE 	= (config->TxPortType==Tx_OpenDrain)? 1:0; // Open Drain Output Enable
+			SIU.PCR[88].B.SRC 	= 1;							// Slew Rate Control = Fast
+			SIU.PCR[89].B.IBE 	= 1;							// Input Buffer Enable = Input
+			SIU.PSMI[2].R 		= 0x02;							// Peripheral input pin selection: CAN3RX -> PCR[89]
+			break;			
+		
+		default :
+			return CAN_ERROR;
+	}
+	
+	p_CAN->MCR.B.MAXMB 	= 55;									// Max 64 Massage Buffer	
+	for (i=0; i<64; i++)
+		p_CAN->BUF[i].CS.B.CODE = CAN_MBCODE_RXINACTIVE;   		// Inactivate all message buffers 
+		
+	p_CAN->MCR.B.HALT 	= 0; 									// FreezeModeON-Bit; Clear after module-init (init=1)
+	p_CAN->MCR.B.FRZ 	= 0; 									// FreezeMode
+
+	return CAN_OK;
+}
+
+
+
+int8_t CAN_Init_Mailbox(CAN_MAILBOX *mbox)
+{
+	volatile struct FLEXCAN_BUF_t *p_BUF;	//pointer auf einen Message Buffer
+	volatile struct FLEXCAN_tag *p_CAN = mbox->p_CAN_Config->CAN_Modul;
+	
+	if (mbox->MBNumber >= 64) return CAN_ERROR;
+	p_BUF = p_CAN->BUF + mbox->MBNumber;
+	if (p_CAN->MCR.B.LPMACK) return CAN_ERROR;	//CAN in DisableMode
+	p_CAN->MCR.B.FRZ = 1; // FreezeMode enable (initVal=1)
+	p_CAN->MCR.B.HALT = 1; // FreezeMode ON (wenn FRZ=1);(initVal=1) Clear after module-init 
+	while (!p_CAN->MCR.B.FRZACK) {}	//warte auf FreezeMode
+	
+	if (mbox->RemoteEn >= 2) return CAN_ERROR;
+	p_BUF->CS.B.RTR =  mbox->RemoteEn;           /* Data frame, not remote Tx request frame */
+	if (mbox->Direction == MB_Tx) {
+		//TX-Box
+		if (mbox->DataBytes >= 9) return CAN_ERROR;
+		p_BUF->CS.B.LENGTH = mbox->DataBytes; /* # bytes to transmit*/
+		p_BUF->CS.B.CODE = CAN_MBCODE_TXINACTIVE;
+	}
+	else if (mbox->Direction == MB_Rx) {
+		//RX-Box
+		p_BUF->CS.B.CODE = CAN_MBCODE_RXEMPTY;
+		//Individuelle Acceptance Mask
+		if (mbox->p_CAN_Config->RxMaskType == RxMask_Individual)
+			p_CAN->RXIMR[mbox->MBNumber].R = mbox->AcceptMask;
+		//MB-Interrupt-Enable
+	}
+	else return CAN_ERROR;
+		
+	if( mbox->IDE == SHORT_ID)
+	{
+		p_BUF->CS.B.IDE = 0;          	// Use standard ID length
+		p_BUF->ID.B.STD_ID = mbox->ID;
+	}
+	else
+	{
+		p_BUF->CS.B.IDE = 1;          	// Use extended ID length
+		p_BUF->ID.B.EXT_ID = (mbox->ID & 0x3FFFF);
+		p_BUF->ID.B.STD_ID = (mbox->ID >> 18);
+	}
+	
+	if (mbox->Interrupt) {
+		if (mbox->MBNumber <= 31)			
+			SETBIT(p_CAN->IMRL.R, mbox->MBNumber); // Interrupt Mask 1
+		else
+			SETBIT(p_CAN->IMRH.R, mbox->MBNumber - 32);	// Interrupt Mask 2
+	}
+
+
+	p_CAN->MCR.B.HALT = 0; // FreezeMode ON (wenn FRZ=1);(initVal=1) Clear after module-init 
+	p_CAN->MCR.B.FRZ = 0; //FreezeMode; 
+	//init Ende
+	return CAN_OK;
+}
+
+
+int8_t CAN_Write(CAN_MAILBOX *mbox, uint8_t *data)
+{
+	uint8_t i;
+	volatile struct FLEXCAN_BUF_t *p_BUF;
+	volatile struct FLEXCAN_tag *p_CAN = mbox->p_CAN_Config->CAN_Modul;
+	
+	if (p_CAN->MCR.B.NOTRDY) return CAN_ERROR;
+	p_BUF = p_CAN->BUF + mbox->MBNumber;
+	if (mbox->MBNumber >= 64) return CAN_ERROR;
+
+	p_BUF->CS.B.CODE = CAN_MBCODE_TXINACTIVE;
+	//I-Flag löschen, um die MB zu entsperren
+/*	if (mbox->MBNumber < 32)
+		p_CAN->IFRL.R = 1 << mbox->MBNumber;
+	else
+		p_CAN->IFRH.R = 1 << (mbox->MBNumber-32);  
+
+*/	p_BUF = p_CAN->BUF + mbox->MBNumber;	//pointer auf einen Message Buffer
+	
+	if( mbox->IDE == SHORT_ID)
+		p_BUF->ID.B.STD_ID = mbox->ID;
+	else
+		p_BUF->ID.B.EXT_ID = mbox->ID;
+
+	for (i=0; i<mbox->DataBytes; i++) {
+		p_BUF->DATA.B[i] = *(data+i);      /* Data to be transmitted */
+	}
+//	CAN_0.BUF[0].CS.B.SRR = 1;           /* Tx frame (not req'd for standard frame)*/
+	p_BUF->CS.B.CODE = CAN_MBCODE_TXSEND;         /* Activate msg. buf. to transmit data frame */ 
+	return CAN_OK;
+}
+
+int8_t CAN_Write_dataset(CAN_MAILBOX *mbox, uint8_t* data,uint64_t timestamp)
+{
+	uint8_t i;
+	int8_t CAN_status=CAN_OK;
+	uint8_t	 dataSetSize= mbox->DataBytes;
+	volatile struct FLEXCAN_BUF_t *p_BUF;
+	volatile struct FLEXCAN_tag *p_CAN = mbox->p_CAN_Config->CAN_Modul;
+	p_BUF = p_CAN->BUF + mbox->MBNumber;
+	while(p_BUF->CS.B.CODE !=CAN_MBCODE_TXINACTIVE) {
+		//wait
+		if(Global_1msCounter >= timestamp + CAN1_TX_TIMEOUT) {
+			return CAN_ERROR;
+		}
+	}
+	CAN_status=CAN_Write(mbox,data);
+	timestamp=Global_1msCounter;
+	if(CAN_status != CAN_OK) {
+		return CAN_ERROR;
+	}
+	
+	return CAN_OK;
+}
+
+
+
+
+int8_t CAN_Read(CAN_MAILBOX *mbox, uint8_t *data)
+{
+	uint8_t i;
+	int8_t returnval;
+	uint32_t dummy;
+	volatile struct FLEXCAN_BUF_t *p_BUF;	//pointer auf einen Message Buffer
+	volatile struct FLEXCAN_tag *p_CAN = mbox->p_CAN_Config->CAN_Modul;
+	returnval = CAN_OK;
+	
+	if (mbox->MBNumber >= 64) return CAN_ERROR;
+	p_BUF = p_CAN->BUF + mbox->MBNumber;
+	dummy = p_BUF->CS.B.CODE;	//Muss ausgelesen werden zum Lock des Puffers
+	if (p_BUF->CS.B.LENGTH > CAN_DATA_ARR_LEN) returnval = CAN_ERROR;
+	if (p_BUF->CS.B.LENGTH != mbox->DataBytes) returnval = CAN_ERROR;
+	
+	if( mbox->IDE == SHORT_ID)
+		mbox->ID = p_BUF->ID.B.STD_ID;		// copy received ID to MailBox
+	else
+		mbox->ID = p_BUF->ID.B.EXT_ID;		// copy received ID to MailBox
+	
+	for (i=0; i < p_BUF->CS.B.LENGTH; i++){
+		*(data+i) = p_BUF->DATA.B[i];
+	}
+	//Timer auslesen und I-Flag löschen, um die MB zu entsperren	
+	dummy = p_CAN->TIMER.R;
+	// Clear Int-Flag 
+	if (mbox->MBNumber < 32)
+		p_CAN->IFRL.R = 1 << mbox->MBNumber;
+	else
+		p_CAN->IFRH.R = 1 << (mbox->MBNumber-32);  
+
+	return returnval;
+}
+
+// Funktionen
+
+int8_t CAN_Abort(CAN_MAILBOX *mbox)
+{
+	volatile struct FLEXCAN_BUF_t *p_BUF;
+	volatile struct FLEXCAN_tag *p_CAN = mbox->p_CAN_Config->CAN_Modul;
+	
+	p_BUF = p_CAN->BUF + mbox->MBNumber;	//pointer auf einen Message Buffer
+	if (mbox->Direction == MB_Rx) return CAN_ERROR;
+	#if CAN_AEN == 1
+		p_BUF->CS.B.CODE = CAN_MBCODE_TXABORT;
+	#else
+		p_BUF->CS.B.CODE = CAN_MBCODE_TXINACTIVE;
+	#endif
+	return CAN_OK;
+}
+
+/**
+ * @function Check CAN Error State Register for Errors
+ * @param config	pointer to CAN Module
+ * @param	can_esr	 32 Bi vaiable for error state
+ * @return TRUE if CAN IS OK, FALSE IF Error occured
+ * 
+ */
+uint8_t CAN_Get_error_Register(CAN_CONFIG *config,uint32_t* can_esr) {
+	volatile struct FLEXCAN_tag *p_CAN = config->CAN_Modul; 
+	if(p_CAN->ESR.R == 0) {
+		return TRUE;
+	}
+	else {
+		*can_esr=p_CAN->ESR.R;
+		return FALSE;
+	}
+}
+
+/**
+ *@brief Check if CAN Errors occured
+ */
+int8_t CAN_Check_error_Register(CAN_CONFIG *config) {
+	volatile struct FLEXCAN_tag *p_CAN = config->CAN_Modul; 
+	if(p_CAN->ESR.R == 0) {
+		return CAN_OK;
+	}
+	else {
+		return CAN_ERROR;
+	}
+}

+ 75 - 138
BMS Master/Sources/MultitaskOS.c

@@ -1,138 +1,75 @@
-//##############################################################################
-//
-// FILE:	MultitaskOS.c
-//
-// TITLE:	Real Time 1ms Generator
-//
-//			- void MultitaskOS_init	( void )
-//			- void ISR_Timer_OS		( void )
-//
-//##############################################################################
-//
-//==============================================================================
-// Change History:
-//==============================================================================
-// Datum:   | Name | Version:| Change / Cause:                            | No
-//------------------------------------------------------------------------------
-//          |      |         |                                            | 002
-//------------------------------------------------------------------------------
-// 05.07.13 |  VR  |   1.1   | Change for ReilingOS                       | 001
-//------------------------------------------------------------------------------
-// 02.05.12 |  TM  |   1.0   | New Build                                  | 000
-//==============================================================================
-//==============================================================================
-// Comment Change / Cause:
-//==============================================================================
-// Change: 003                                                           // 003
-//----------------------
-//                                                       
-//
-//==============================================================================
-// Change: 002                                                           // 002
-//----------------------
-//                                           
-//
-//==============================================================================
-// Change: 001                                                           // 001
-//----------------------
-// 
-//
-//==============================================================================
-
-#include "BMS_Master.h"
-
-	volatile uint32_t ISO_Start = 0;
-	volatile uint32_t ISO_PWM   = 0;
-	volatile uint16_t ISO_PIN   = 0;
-
-
-// ***** MultitaskOS_init ******************************************************
-void MultitaskOS_init( void )
-{
-	PIT.PITMCR.B.MDIS = 0;				// Enable Periodic Interrupt Timer
-	PIT.PITMCR.B.MDIS_RTI = 0;			// Enable Real Time Interrupt
-	PIT.PITMCR.B.FRZ = 1;				// Freeze in Debug Mode
-	
-	PIT.CH[0].LDVAL.R = SYSCLK_KHZ;		// Timeout Period 1ms 64MHz/1kHz
-	PIT.CH[0].TFLG.B.TIF = 1;           // Timer Interrupt Request Clear
-	PIT.CH[0].TCTRL.B.TIE = 1;			// Timer Interrupt Enable
-
-	PIT.CH[0].TCTRL.B.TEN = 1; 			// Timer Active
-}
-
-
-
-// ***** ISR_Timer_OS **********************************************************
-void ISR_Timer_OS( void ) 
-{
-	uint32_t ISO_CycleTime;
-	asm(" wrteei 0");					// disable Interrupts
-
-	PIT.CH[0].TFLG.B.TIF = 1;    		// CLear PIT 1 flag by writing 1
-	Global_1msCounter++;
- 
-//''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
-    if( Global_1msCounter > 12000 )
-    {
-  	  if( !READ_INPIN(PIN_REGNR_OKHS) )       			// if General Error: Off, Undervoltage, Grounderror, Uniterror, Underrange
-	  {
-	    gISO_R = 0;									  	// show General Error
-	    gBSE.ErrorBMS |= ERROR_ISO_GENERAL;
-	    gErrorEvent = EEV__SHUT_DOWN_EMERGENCY;         // and load rejection
-	  }
-	  else
-	    if( READ_INPIN(PIN_REGNR_MHS) != ISO_PIN )      // PWM Signal changed ?
-	    {
-	 	  ISO_PIN = ISO_PIN?0:1;						// new PWM Signal store
-		    
-	      if( ISO_PIN )								  	// new Cycle ?
-		  {
-		    ISO_CycleTime = Global_1msCounter - ISO_Start;  // Cycle Time compute
-		    ISO_Start = Global_1msCounter;              // new Initial Value store
-			   
-		    if( ISO_CycleTime < 35)                     // 30 Hz ? >>Quickstart<<
-		    {
-			  if( ISO_CycleTime > 31 )
-			  {
-			    gISO_R = 120000;						// ISO OK?
-			    if(ISO_PWM > 4)                         // > 10%
-		        {
-		    	  gISO_R  = 0;						  	// ISO NOK
-		    	  gBSE.ErrorBMS |= ERROR_ISO_BAD;
-		    	  gErrorEvent = EEV__SHUT_DOWN_EMERGENCY;     // load rejection
-		        }
-			  }
-		    }
-		    else
-			  if( ISO_CycleTime < 102)                  // 10 Hz ? >>regular Operation<<
-			  {
-			    if( ISO_CycleTime > 98 )
-			    {
-				  if(ISO_PWM < 6)                       // yes, Duty < 6 % => Overflow
-			        gISO_R = 120000;					// yes, show Overflow
-				  else
-				    gISO_R = ( 90 * 1200 ) / ( ISO_PWM - 5 ) - 1200;
-					
-				  if(gCANErrorInsert == 14)                                   //!! 1.5-3
-					  gISO_R = MIN_ISO_R_TEST;	
-				  
-				  if( gISO_R < MIN_ISO_R)               // ISO-R low
-				  {
-					gBSE.ErrorBMS |= ERROR_ISO_LOW;
-				    gErrorEvent = EEV__SHUT_DOWN_EMERGENCY;   // load rejection
-				  }
-			    } 
-		      }
-		    }
-	        else                                        // Duty End
-	    	  ISO_PWM = Global_1msCounter - ISO_Start;  // Duty store
-         }
-    }
-//''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
-	
-	asm(" wrteei 1");					// enable Interrupts
-}
-
-
-
-// ***** End MultitaskOS.c *****************************************************
+//##############################################################################
+//
+// FILE:	MultitaskOS.c
+//
+// TITLE:	Real Time 1ms Generator
+//
+//			- void MultitaskOS_init	( void )
+//			- void ISR_Timer_OS		( void )
+//
+//##############################################################################
+//
+//==============================================================================
+// Change History:
+//==============================================================================
+// Datum:   | Name | Version:| Change / Cause:                            | No
+//------------------------------------------------------------------------------
+//          |      |         |                                            | 002
+//------------------------------------------------------------------------------
+// 05.07.13 |  VR  |   1.1   | Change for ReilingOS                       | 001
+//------------------------------------------------------------------------------
+// 02.05.12 |  TM  |   1.0   | New Build                                  | 000
+//==============================================================================
+//==============================================================================
+// Comment Change / Cause:
+//==============================================================================
+// Change: 003                                                           // 003
+//----------------------
+//                                                       
+//
+//==============================================================================
+// Change: 002                                                           // 002
+//----------------------
+//                                           
+//
+//==============================================================================
+// Change: 001                                                           // 001
+//----------------------
+// 
+//
+//==============================================================================
+
+#include "BMS_Master.h"
+
+
+
+// ***** MultitaskOS_init ******************************************************
+void MultitaskOS_init( void )
+{
+	PIT.PITMCR.B.MDIS = 0;				// Enable Periodic Interrupt Timer
+	PIT.PITMCR.B.MDIS_RTI = 0;			// Enable Real Time Interrupt
+	PIT.PITMCR.B.FRZ = 1;				// Freeze in Debug Mode
+	
+	PIT.CH[0].LDVAL.R = SYSCLK_KHZ;		// Timeout Period 1ms 64MHz/1kHz
+	PIT.CH[0].TFLG.B.TIF = 1;           // Timer Interrupt Request Clear
+	PIT.CH[0].TCTRL.B.TIE = 1;			// Timer Interrupt Enable
+
+	PIT.CH[0].TCTRL.B.TEN = 1; 			// Timer Active
+}
+
+
+
+// ***** ISR_Timer_OS **********************************************************
+void ISR_Timer_OS( void ) 
+{
+	asm(" wrteei 0");					// disable Interrupts
+
+	PIT.CH[0].TFLG.B.TIF = 1;    		// CLear PIT 1 flag by writing 1
+	Global_1msCounter++;
+ 
+	asm(" wrteei 1");					// enable Interrupts
+}
+
+
+
+// ***** End MultitaskOS.c *****************************************************

+ 201 - 198
BMS Master/Sources/main.c

@@ -1,198 +1,201 @@
-//##############################################################################
-//
-//  BMS_Master - Battery Management System Master 
-//
-//  Firmware for 
-//	- Collecting and Checking Data of BMS_Slave and BMS_UI
-//  - Flow Control for START, STOP, LOAD and DRIVE
-//  - SOC/SOH computing
-//  - Balancer computing
-//  - Error Check
-//  - Emergency Shut Off
-//  
-//
-//  CENTRAL - FILE
-//  
-//  - void	Main( void )
-//
-// 
-//##############################################################################
-//
-//  Hardware Revision:  V1
-// 
-//  uController:        Freescale MPC5646C
-//  
-//  Autor:              M. Maurer, V. Reiling, KIT Campus Nord, IPE
-//
-//  Date:               April 2012
-//
-//  Built with:         CodeWarrior Development Studio 10.4 ( Build Id: 130425 )
-//
-//##############################################################################
-
-
-//==============================================================================
-// History:
-//==============================================================================
-// Datum:   | Name | Version:| Cause:			                         | rev.:
-//------------------------------------------------------------------------------
-// 04.05.15 |  VR  |   1.5   | Change for BaSyTec                        | 005   
-//------------------------------------------------------------------------------
-// 18.11.14 |  VR  |   1.4   | upgrade 2 CodeWarrior 10.6 id: 140329     | 004   
-//------------------------------------------------------------------------------
-// 18.03.14 |  VR  |   1.3   | Error Handling changed, Derating added    | 003   
-//------------------------------------------------------------------------------
-// 07.02.14 |  VR  |   1.2   | upgrade 2 CodeWarrior 10.5 id: 130916     | 002    
-//------------------------------------------------------------------------------
-// 05.07.13 |  VR  |   1.1   | BMS Master Project					     | 001 
-//------------------------------------------------------------------------------
-// 20.04.12 |  TM  |   1.0   | Hardware Test Code & Drivers              | 000
-//==============================================================================
-#include "BMS_Master.h"
-
-
-uint8_t const   ucMainVersion  =  0x1;
-uint8_t const   ucSubVersion   =  0x5;
-
-
-
-// ***** Global Variables *******************************************************************
-BSD_t		gBSD;							// Global Battery Management System Slave Data 
-BSE_t		gBSE;							// Global Battery Management System Slave Errors
-uint8_t     gMaxDischargeCurrent = 60;      // Maximum Discharge Current = 120A / 2A per Bit
-uint32_t	Global_1msCounter = 0;			// 1.5 Months till Overrun
-uint32_t	gEvent;							// Control of Main FSM
-uint32_t    gErrorEvent;                    // Control of Error FSM
-uint32_t    gISO_R = 0;                     // Resistance of Isolation
-uint8_t     gCANErrorInsert = 0;            // Automatic Test over CAN
-MASTER_CAN0_STRUCT_t gDUMMY_data_struct;
-
-
-
-
-
-void main(void)
-{
-	/**
-	 * @brief Main Function of BMS Master
-	 */	
-	volatile    uint16_t	Vbat 						= 0;
-	volatile 	uint16_t	StartTryCounter 			= 0;
-	volatile    uint32_t	DelayCount 					= 0;
-	volatile	uint32_t	NextEvent					= 0;
-	volatile	uint32_t	CounterCheckVoltageMSG		= 12000;
-	volatile	uint32_t	CounterCheckStatusUIMSG		= 12000;
-	volatile	uint32_t	CounterCheckTemperatureMSG	= 12000;
-	volatile	uint32_t	Counter_20ms				= 5000;
-	volatile	uint32_t	Counter_50ms				= 5000;
-	volatile	uint32_t	Counter_100ms				= 5000;
-	volatile	uint16_t	Copy_r_Voltage				= 200;
-	volatile	uint16_t	Copy_r_Status				= 200;
-	volatile	uint16_t	Copy_r_Temperature 			= 200;
-	volatile	uint16_t	Copy_r_UI         			= 200;
-	volatile    uint32_t	ErrorTimeCount              = 0;
-	static float SoC_test;
-	
-	static	uint32_t	test_timestamp				= 0;
-	static 	uint8_t		test_data_send[4]			= {1,2,3,4};	
-
-	static	MASTER_CAN0_STRUCT_t CAN0_fsm_state;
-	static  MASTER_CAN1_STRUCT_t CAN1_fsm_state;
-	static BMS_MASTER_OPERATION_t operation_Fsm;
-	static  uint8_t		active_states[2]= {4,15} ;
-	static BMS_SLAVE_CONFIGURATION_t cellConfig[CAN0_MAX_NR_OF_SLAVES-1];
-	static BMS_UI_CONFIGURATION_t uiConfig;
-	static uint8_t fram_test[8] ={1,2,3,4,5,6,7,8};
-	static uint8_t fram_rx_text[8] ={0,0,0,0,0,0,0,0};
-	
-	
-	
-	
-	
-				 int32_t	SOC 	 		= 0;		// State of Charge for DICO in 0.4%
-	  			uint32_t	BalanceOn		= 1;        // Send empty Balancing
-	  			uint32_t	i = 0;
-	  			uint32_t	j = 0;
-	  			uint32_t    test = 0;
-	  			
-	  			
-//-------------------------------------------------------------------------------------------	
-	init_Device();    						// Device.h
-	BoardPeriph_init();						// BoardPeripherals.h
-	
-	CAN0_init();							// CAN Master to Slave
-	CAN1_init();							// CAN Master to INVERTER
-	CAN1_init_tx_structure(&(CAN0_fsm_state.inverter.txStruct));
-	//CAN2_init();							// CAN Master to DICO
-
-	
-	MultitaskOS_init();						// MultitaskOS.h
-	  
-	enableIrq();							// Device.h
-  
-	BoardPeriph_test_init();				// BoardPeripherals.h
-
-	gEvent = EV__INITIALISE;				// Start Main FSM
-	gErrorEvent = EEV__NO_ERROR;            // Clear Error FSM
-	
-	SwitchRelais( PWR_SUPPLY, 0) ;// Activate PWR Supply by setting pin to low
-
-	//CAN_Tx_BMU_DICO( );
-	gen_data_initSlave(&gDUMMY_data_struct, 3600, 25, 36000, 1000); 
-	
-	initCellConfig(cellConfig);
-	initUiConfig(&uiConfig);
-	
-	CAN0_init_telegrams(&TelegramTxContainer[0],CAN0_MAX_NR_OF_SLAVES);
-	init_master_CAN0_fsm(&CAN0_fsm_state,cellConfig,&uiConfig);
-	Master_CAN1_fsm_init(&CAN1_fsm_state);
-	
-	BMS_Can_ID_init_init_startupConfig (&CAN0_fsm_state); 
-	
-	//init_master_operation_fsm(&operation_Fsm);
-	
-	// read fram start State
-
-	
-	
-
-	while(Global_1msCounter < DELAY_START)
-	{
-	}
-	
-	while(BMS_Can_ID_init_fsm (&CAN0_fsm_state) == BMS_CAN_ID_INIT_RETURN_RUNNING ) {
-		// wait
-	}
-	//write_fram_clear_startup_state(&CAN0_fsm_state); 
-	//write_fram_clear_error_buffer(&CAN0_fsm_state); 
-	//write_fram_set_SoC(0.03); 
-	
-	while(Global_1msCounter < DELAY_START*2)
-	{
-	}
-
-	read_fram_get_startup_state(&CAN0_fsm_state);
-	read_fram_read_error_buffer(&CAN0_fsm_state);
-	
-	SoC_test= read_fram_get_SoC();
-	test_timestamp=Global_1msCounter ;
-	while(1) {
-		
-		Master_CAN0_fsm(&CAN0_fsm_state,Global_1msCounter);
-		//Master_operation_fsm(&CAN0_fsm_state,Global_1msCounter,&operation_Fsm);
-		
-		//Master_CAN1_fsm(&CAN0_fsm_state,&CAN1_fsm_state,Global_1msCounter);
-		//if(Global_1msCounter > 20000 + test_timestamp) {
-		//	SwitchRelais( PWR_SUPPLY, 1);
-		//}
-		
-
-		
-	}
-	
-
-}
-
-
-
-// ***** End Main.c *************************************************************************
+//##############################################################################
+//
+//  BMS_Master - Battery Management System Master 
+//
+//  Firmware for 
+//	- Collecting and Checking Data of BMS_Slave and BMS_UI
+//  - Flow Control for START, STOP, LOAD and DRIVE
+//  - SOC/SOH computing
+//  - Balancer computing
+//  - Error Check
+//  - Emergency Shut Off
+//  
+//
+//  CENTRAL - FILE
+//  
+//  - void	Main( void )
+//
+// 
+//##############################################################################
+//
+//  Hardware Revision:  V1
+// 
+//  uController:        Freescale MPC5646C
+//  
+//  Autor:              M. Maurer, V. Reiling, KIT Campus Nord, IPE
+//
+//  Date:               April 2012
+//
+//  Built with:         CodeWarrior Development Studio 10.4 ( Build Id: 130425 )
+//
+//##############################################################################
+
+
+//==============================================================================
+// History:
+//==============================================================================
+// Datum:   | Name | Version:| Cause:			                         | rev.:
+//------------------------------------------------------------------------------
+// 04.05.15 |  VR  |   1.5   | Change for BaSyTec                        | 005   
+//------------------------------------------------------------------------------
+// 18.11.14 |  VR  |   1.4   | upgrade 2 CodeWarrior 10.6 id: 140329     | 004   
+//------------------------------------------------------------------------------
+// 18.03.14 |  VR  |   1.3   | Error Handling changed, Derating added    | 003   
+//------------------------------------------------------------------------------
+// 07.02.14 |  VR  |   1.2   | upgrade 2 CodeWarrior 10.5 id: 130916     | 002    
+//------------------------------------------------------------------------------
+// 05.07.13 |  VR  |   1.1   | BMS Master Project					     | 001 
+//------------------------------------------------------------------------------
+// 20.04.12 |  TM  |   1.0   | Hardware Test Code & Drivers              | 000
+//==============================================================================
+#include "BMS_Master.h"
+
+
+uint8_t const   ucMainVersion  =  0x1;
+uint8_t const   ucSubVersion   =  0x5;
+
+
+
+// ***** Global Variables *******************************************************************
+BSD_t		gBSD;							// Global Battery Management System Slave Data 
+BSE_t		gBSE;							// Global Battery Management System Slave Errors
+uint8_t     gMaxDischargeCurrent = 60;      // Maximum Discharge Current = 120A / 2A per Bit
+uint64_t	Global_1msCounter = 0;			// Million Years till Overrun
+uint32_t	gEvent;							// Control of Main FSM
+uint32_t    gErrorEvent;                    // Control of Error FSM
+uint32_t    gISO_R = 0;                     // Resistance of Isolation
+uint8_t     gCANErrorInsert = 0;            // Automatic Test over CAN
+MASTER_CAN0_STRUCT_t gDUMMY_data_struct;
+
+
+
+
+
+void main(void)
+{
+	/**
+	 * @brief Main Function of BMS Master
+	 */	
+	volatile    uint16_t	Vbat 						= 0;
+	volatile 	uint16_t	StartTryCounter 			= 0;
+	volatile    uint32_t	DelayCount 					= 0;
+	volatile	uint32_t	NextEvent					= 0;
+	volatile	uint32_t	CounterCheckVoltageMSG		= 12000;
+	volatile	uint32_t	CounterCheckStatusUIMSG		= 12000;
+	volatile	uint32_t	CounterCheckTemperatureMSG	= 12000;
+	volatile	uint32_t	Counter_20ms				= 5000;
+	volatile	uint32_t	Counter_50ms				= 5000;
+	volatile	uint32_t	Counter_100ms				= 5000;
+	volatile	uint16_t	Copy_r_Voltage				= 200;
+	volatile	uint16_t	Copy_r_Status				= 200;
+	volatile	uint16_t	Copy_r_Temperature 			= 200;
+	volatile	uint16_t	Copy_r_UI         			= 200;
+	volatile    uint32_t	ErrorTimeCount              = 0;
+	static float SoC_test;
+	
+	static	uint32_t	test_timestamp				= 0;
+	static 	uint8_t		test_data_send[4]			= {1,2,3,4};	
+
+	static	MASTER_CAN0_STRUCT_t CAN0_fsm_state;
+	static  MASTER_CAN1_STRUCT_t CAN1_fsm_state;
+	static BMS_MASTER_OPERATION_t operation_Fsm;
+	static  uint8_t		active_states[2]= {4,15} ;
+	static BMS_SLAVE_CONFIGURATION_t cellConfig[CAN0_MAX_NR_OF_SLAVES-1];
+	static BMS_UI_CONFIGURATION_t uiConfig;
+	static uint8_t fram_test[8] ={1,2,3,4,5,6,7,8};
+	static uint8_t fram_rx_text[8] ={0,0,0,0,0,0,0,0};
+	
+	
+	
+	
+	
+				 int32_t	SOC 	 		= 0;		// State of Charge for DICO in 0.4%
+	  			uint32_t	BalanceOn		= 1;        // Send empty Balancing
+	  			uint32_t	i = 0;
+	  			uint32_t	j = 0;
+	  			uint32_t    test = 0;
+	  			uint16_t    U12, U33;     				//!! Test der Betriebsspannung
+	  			
+	  			
+//-------------------------------------------------------------------------------------------	
+	init_Device();    						// Device.h
+	BoardPeriph_init();						// BoardPeripherals.h
+	
+	CAN0_init();							// CAN Master to Slave
+	CAN1_init();							// CAN Master to INVERTER
+	CAN1_init_tx_structure(&(CAN0_fsm_state.inverter.txStruct));
+	//CAN2_init();							// CAN Master to DICO
+
+	
+	MultitaskOS_init();						// MultitaskOS.h
+	  
+	enableIrq();							// Device.h
+  
+	BoardPeriph_test_init();				// BoardPeripherals.h
+
+	gEvent = EV__INITIALISE;				// Start Main FSM
+	gErrorEvent = EEV__NO_ERROR;            // Clear Error FSM
+	
+	SwitchRelais( PWR_SUPPLY, 0) ;// Activate PWR Supply by setting pin to low
+
+	//CAN_Tx_BMU_DICO( );
+	gen_data_initSlave(&gDUMMY_data_struct, 3600, 25, 36000, 1000); 
+	
+	initCellConfig(cellConfig);
+	initUiConfig(&uiConfig);
+	
+	CAN0_init_telegrams(&TelegramTxContainer[0],CAN0_MAX_NR_OF_SLAVES);
+	init_master_CAN0_fsm(&CAN0_fsm_state,cellConfig,&uiConfig);
+	Master_CAN1_fsm_init(&CAN1_fsm_state);
+	
+	BMS_Can_ID_init_init_startupConfig (&CAN0_fsm_state); 
+	
+	//init_master_operation_fsm(&operation_Fsm);
+	
+	// read fram start State
+
+	
+	
+
+	while(Global_1msCounter < DELAY_START)
+	{
+	}
+	
+	while(BMS_Can_ID_init_fsm (&CAN0_fsm_state) == BMS_CAN_ID_INIT_RETURN_RUNNING ) {
+		// wait
+	}
+	//write_fram_clear_startup_state(&CAN0_fsm_state); 
+	//write_fram_clear_error_buffer(&CAN0_fsm_state); 
+	//write_fram_set_SoC(0.03); 
+	
+	while(Global_1msCounter < DELAY_START*2)
+	{
+	}
+
+	CheckSupplyVoltages( &U12, &U33 );   //!! Test der Betriebsspannung
+	
+	read_fram_get_startup_state(&CAN0_fsm_state);
+	read_fram_read_error_buffer(&CAN0_fsm_state);
+	
+	SoC_test= read_fram_get_SoC();
+	test_timestamp=Global_1msCounter ;
+	while(1) {
+		
+		Master_CAN0_fsm(&CAN0_fsm_state,Global_1msCounter);
+		//Master_operation_fsm(&CAN0_fsm_state,Global_1msCounter,&operation_Fsm);
+		
+		//Master_CAN1_fsm(&CAN0_fsm_state,&CAN1_fsm_state,Global_1msCounter);
+		//if(Global_1msCounter > 20000 + test_timestamp) {
+		//	SwitchRelais( PWR_SUPPLY, 1);
+		//}
+		
+
+		
+	}
+	
+
+}
+
+
+
+// ***** End Main.c *************************************************************************