diff --git a/.github/workflows/format-check.yml b/.github/workflows/format-check.yml new file mode 100644 index 0000000..b370b61 --- /dev/null +++ b/.github/workflows/format-check.yml @@ -0,0 +1,19 @@ +name: Code Style Check + +on: [push] + +jobs: + formatting-check: + name: Check format of C + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + - name: Run clang-format style check for C/C++ sources + uses: Northeastern-Electric-Racing/clang-format-action@main + with: + clang-format-version: '18' + # exclude vl6180x + # use the clang-format from embedded base + format-filepath: "./clang-format" diff --git a/.gitignore b/.gitignore index 835cd1f..825d20a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ .vscode/ __pycache__/ -*.egg-info/ \ No newline at end of file +*.egg-info/ + +*.nix \ No newline at end of file diff --git a/aliases.txt b/aliases.txt deleted file mode 100644 index 860c590..0000000 --- a/aliases.txt +++ /dev/null @@ -1,8 +0,0 @@ -build="docker compose run --rm ner-gcc-arm make" -cerbcon="sudo modprobe vhci_hcd && sudo usbip attach -r 192.168.100.12 -b 1-1.3" -disconnect="sudo usbip detach -p 0" -shepcon="sudo modprobe vhci_hcd && sudo usbip attach -r 192.168.100.12 -b 1-1.4" -peyton="echo \" Shut the fuck up Peyton, fucking hell\" " -flash="bash -c \"probe-rs download --verify --chip STM32F405RGTx ./build/*.elf && probe-rs reset --chip STM32F405RGTx\" " -reset-target="bash -c \"probe-rs reset --chip STM32F405RGTx\" " -debug="bash -c 'probe-rs gdb --gdb-connection-string 0.0.0.0:1337 --chip STM32F405RGTx & sleep 1; docker compose run --rm -P ner-gcc-arm "arm-none-eabi-gdb" /home/app$(ls ./build/*.elf | cut -c2-) -ex \"target remote host.docker.internal:1337\" && killall probe-rs && probe-rs reset --chip STM32F405RGTx' " diff --git a/cangen/CANField.py b/cangen/CANField.py index 03c867c..e823502 100644 --- a/cangen/CANField.py +++ b/cangen/CANField.py @@ -43,3 +43,7 @@ class NetField: points: list[CANPoint] send: bool = True topic_append: bool = False + sim_min: Optional[float] = -1.0 + sim_max: Optional[float] = -1.0 + sim_inc_min: Optional[float] = -1.0 + sim_inc_max: Optional[float] = -1.0 diff --git a/cangen/CANMsg.py b/cangen/CANMsg.py index 6d2a1bd..c81616a 100644 --- a/cangen/CANMsg.py +++ b/cangen/CANMsg.py @@ -11,6 +11,7 @@ class CANMsg: id: str # Hex value of CAN ID, i.e. `0x88` desc: str # Brief name of CAN message, used for generating function names fields: list[NetField] # List of CAN fields in the message + sim_freq: Optional[int] # Frequency to simulate this message at, in ms @dataclass class EncodableCANMsg(CANMsg): diff --git a/cangen/Result.py b/cangen/Result.py index c1c01f0..a42d7cc 100644 --- a/cangen/Result.py +++ b/cangen/Result.py @@ -10,10 +10,12 @@ class Result: encode_data: str encode_master_mapping: str format_data: str + simulate_data: str - def __init__(self, decode_data: str, master_mapping: str, encode_data: str, encode_master_mapping: str, format_data: str): + def __init__(self, decode_data: str, master_mapping: str, encode_data: str, encode_master_mapping: str, format_data: str, simulate_data: str = ""): self.decode_data = decode_data self.decode_master_mapping = master_mapping self.encode_data = encode_data self.encode_master_mapping = encode_master_mapping self.format_data = format_data + self.simulate_data = simulate_data diff --git a/cangen/RustSynthFromJSON.py b/cangen/RustSynthFromJSON.py index 27ffb45..9ac5979 100644 --- a/cangen/RustSynthFromJSON.py +++ b/cangen/RustSynthFromJSON.py @@ -1,6 +1,8 @@ from cangen.Result import Result from typing import List, Dict, Optional import math +import re +import logging class RustSynthFromJSON: """ @@ -13,7 +15,8 @@ def parse_messages(self, msgs: List[Dict]) -> Result: returns a Result object that contains the synthesized Rust code for the decode_data.rs and master_mapping.rs files """ - result = Result("", "", "", "", "") + + result = Result("", "", "", "", "", "") result.decode_data += RustSnippets.ignore_clippy result.decode_data += RustSnippets.decode_data_import result.decode_data += RustSnippets.decode_mock @@ -49,6 +52,7 @@ def parse_messages(self, msgs: List[Dict]) -> Result: result.format_data = RustSnippets.format_impl + result.simulate_data = self.create_simulate_data(msgs) return result @@ -343,6 +347,72 @@ def encode_data_inst(self, msg: Dict) -> str: is_ext: {str(msg['is_ext'] if 'is_ext' in msg else 'false').lower()}, }}""" + def create_simulate_data(self, msgs: List[Dict]) -> str: + def sanitize_fnname(name): + name = re.sub(r'\W|^(?=\d)', '_', name) + name = name.lower() + return name + + sim_funcbody = "" + # process each CAN message + for msg in msgs: + if ('sim_freq' in msg.keys()): + id = msg['id'] + desc = msg['desc'] + sim_freq = msg['sim_freq'] + net_fields = msg['fields'] + for netfield in net_fields: + # check if sim_min, sim_max, sim_inc_max, sim_inc_min, points are present + if ("sim_min" not in netfield.keys() or + "sim_max" not in netfield.keys() or + "sim_inc_max" not in netfield.keys() or + "sim_inc_min" not in netfield.keys()): + continue + + component_name = netfield['name'] + component_var = sanitize_fnname(component_name) + unit = netfield['unit'] + sim_min = netfield['sim_min'] + sim_max = netfield['sim_max'] + sim_inc_max = netfield['sim_inc_max'] + sim_inc_min = netfield['sim_inc_min'] + n_canpoints = len(netfield['points']) + + new_component = f""" + let {component_var}_attr: SimulatedComponentAttr = SimulatedComponentAttr {{ + sim_min: {float(sim_min)}, + sim_max: {float(sim_max)}, + sim_inc_min: {float(sim_inc_min)}, + sim_inc_max: {float(sim_inc_max)}, + sim_freq: {float(sim_freq)}, + n_canpoints: {n_canpoints}, + id: "{id}".to_string(), + }}; + + + let {component_var} = SimulatedComponent::new( + "{component_name}".to_string(), + "{unit}".to_string(), + {component_var}_attr, + ); + simulatable_messages.push({component_var}); + """ + sim_funcbody += new_component + + + sim_fnblock = f""" + #![allow(clippy::all)] + use crate::simulatable_message::{{SimulatedComponent, SimulatedComponentAttr}}; + pub fn create_simulated_components() -> Vec {{ + let mut simulatable_messages: Vec = Vec::new(); + + {sim_funcbody} + + simulatable_messages + }} + """ + return sim_fnblock + class RustSnippets: diff --git a/cangen/__init__.py b/cangen/__init__.py index 926ac82..4c415fa 100644 --- a/cangen/__init__.py +++ b/cangen/__init__.py @@ -1,6 +1,4 @@ -from cangen.RustSynth import RustSynth from cangen.RustSynthFromJSON import RustSynthFromJSON -from cangen.YAMLParser import YAMLParser from cangen.CANMsg import CANMsg from cangen.CANMsg import EncodableCANMsg from cangen.CANField import NetField diff --git a/cangen/can-messages/bms.json b/cangen/can-messages/bms.json index a162843..9d2da6f 100644 --- a/cangen/can-messages/bms.json +++ b/cangen/can-messages/bms.json @@ -1,587 +1,529 @@ [ { - "id": "0x80", - "desc": "accumulator status", - "fields": [ - { - "name": "BMS/Pack/Voltage", - "unit": "V", - "points": [ - { - "size": 16, - "format": "divide10" - } - ] - } - , - { - "name": "BMS/Pack/Current", - "unit": "A", - "send": false, - "points": [ - { - "size": 16 - } - ] - } - , - { - "name": "BMS/Pack/Amp-hours", - "unit": "Ah", - "points": [ - { - "size": 16 - } - ] - } - , - { - "name": "BMS/Pack/SOC", - "unit": "%", - "points": [ - { - "size": 8 - } - ] - } - , - { - "name": "BMS/Pack/Health", - "unit": "%", - "points": [ - { - "size": 8 - } - ] - } - ] - } - , - { - "id": "0x81", - "desc": "BMS Status", - "fields": [ - { - "name": "BMS/Status/State", - "unit": "", - "points": [ - { - "size": 8 - } - ] - } - , - { - "name": "BMS/Status/Faults", - "unit": "", - "points": [ - { - "size": 32 - } - ] - } - , - { - "name": "BMS/Status/Temp_Average", - "unit": "C", - "points": [ - { - "size": 8 - } - ] - } - , - { - "name": "BMS/Status/Temp_Internal", - "unit": "C", - "points": [ - { - "size": 8 - } - ] - } - , - { - "name": "BMS/Status/Balancing", - "unit": "", - "points": [ - { - "size": 8 - } - ] - } - ] - } - , - { - "id": "0x82", - "desc": "Shutdown Control", - "fields": [ - { - "name": "BMS/Shutdown/MPE", - "unit": "", - "points": [ - { - "size": 8 - } - ] - } - ] - } - , - { - "id": "0x83", - "desc": "Cell Data", - "fields": [ - { - "name": "BMS/Cells/Volts_High_Value", - "unit": "V", - "points": [ - { - "size": 16, - "format": "divide10000" - } - ] - } - , - { - "name": "BMS/Cells/Volts_High_Chip", - "unit": "", - "points": [ - { - "size": 4 - } - ] - } - , - { - "name": "BMS/Cells/Volts_High_Cell", - "unit": "", - "points": [ - { - "size": 4 - } - ] - } - , - { - "name": "BMS/Cells/Volts_Low_Value", - "unit": "V", - "points": [ - { - "size": 16, - "format": "divide10000" - } - ] - } - , - { - "name": "BMS/Cells/Volts_Low_Chip", - "unit": "", - "points": [ - { - "size": 4 - } - ] - } - , - { - "name": "BMS/Cells/Volts_Low_Cell", - "unit": "", - "points": [ - { - "size": 4 - } - ] - } - , - { - "name": "BMS/Cells/Volts_Avg_Value", - "unit": "V", - "points": [ - { - "size": 16, - "format": "divide10000" - } - ] - } - ] - } - , - { - "id": "0x84", - "desc": "Cell Temperatures", - "fields": [ - { - "name": "BMS/Cells/Temp_High_Value", - "unit": "C", - "points": [ - { - "size": 16 - } - ] - } - , - { - "name": "BMS/Cells/Temp_High_Cell", - "unit": "", - "points": [ - { - "size": 4 - } - ] - } - , - { - "name": "BMS/Cells/Temp_High_Chip", - "unit": "", - "points": [ - { - "size": 4 - } - ] - } - , - { - "name": "BMS/Cells/Temp_Low_Value", - "unit": "C", - "points": [ - { - "size": 16 - } - ] - } - , - { - "name": "BMS/Cells/Temp_Low_Cell", - "unit": "", - "points": [ - { - "size": 4 - } - ] - } - , - { - "name": "BMS/Cells/Temp_Low_Chip", - "unit": "", - "points": [ - { - "size": 4 - } - ] - } - , - { - "name": "BMS/Cells/Temp_Avg_Value", - "unit": "C", - "points": [ - { - "size": 16 - } - ] - } - ] - } - , + "id": "0x80", + "desc": "accumulator status", + "sim_freq": 700, + "fields": [ + { + "name": "BMS/Pack/Voltage", + "unit": "V", + "sim_min": 400, + "sim_max": 505, + "sim_inc_min": 0.01, + "sim_inc_max": 0.3, + "points": [ + { + "size": 16, + "format": "divide10" + } + ] + }, + { + "name": "BMS/Pack/Current", + "unit": "A", + "sim_min": 0, + "sim_max": 50, + "sim_inc_min": 0, + "sim_inc_max": 3, + "send": false, + "points": [ + { + "size": 16 + } + ] + }, + { + "name": "BMS/Pack/Amp-hours", + "unit": "Ah", + "sim_min": 0, + "sim_max": 100, + "sim_inc_min": 0, + "sim_inc_max": 0.1, + "points": [ + { + "size": 16 + } + ] + }, + { + "name": "BMS/Pack/SOC", + "unit": "%", + "sim_min": 0, + "sim_max": 100, + "sim_inc_min": 0.01, + "sim_inc_max": 0.1, + "points": [ + { + "size": 8 + } + ] + }, + { + "name": "BMS/Pack/Health", + "unit": "%", + "sim_min": 0, + "sim_max": 100, + "sim_inc_min": 0, + "sim_inc_max": 0.1, + "points": [ + { + "size": 8 + } + ] + } + ] + }, { - "id": "0x85", - "desc": "Segment Temperatures", - "fields": [ - { - "name": "BMS/Segment_Temp/1", - "unit": "C", - "points": [ - { - "size": 8, - "signed": true - } - ] - } - , - { - "name": "BMS/Segment_Temp/2", - "unit": "C", - "points": [ - { - "size": 8, - "signed": true - } - ] - } - , - { - "name": "BMS/Segment_Temp/3", - "unit": "C", - "points": [ - { - "size": 8, - "signed": true - } - ] - } - , - { - "name": "BMS/Segment_Temp/4", - "unit": "C", - "points": [ - { - "size": 8, - "signed": true - } - ] - } - , - { - "name": "BMS/Segment_Temp/5", - "unit": "C", - "points": [ - { - "size": 8, - "signed": true - } - ] - } - , - { - "name": "BMS/Segment_Temp/6", - "unit": "C", - "points": [ - { - "size": 8, - "signed": true - } - ] - } - ] - } - , + "id": "0x81", + "desc": "BMS Status", + "sim_freq": 700, + "fields": [ + { + "name": "BMS/Status/State", + "unit": "", + "sim_min": 0, + "sim_max": 4, + "sim_inc_min": 1, + "sim_inc_max": 1, + "points": [ + { + "size": 8 + } + ] + }, + { + "name": "BMS/Status/Faults", + "unit": "", + "sim_min": 0, + "sim_max": 131072, + "sim_inc_min": 4, + "sim_inc_max": 16, + "points": [ + { + "size": 32 + } + ] + }, + { + "name": "BMS/Status/Temp_Average", + "unit": "C", + "sim_min": 10, + "sim_max": 50, + "sim_inc_min": 0.01, + "sim_inc_max": 0.5, + "points": [ + { + "size": 8 + } + ] + }, + { + "name": "BMS/Status/Temp_Internal", + "unit": "C", + "sim_min": 10, + "sim_max": 50, + "sim_inc_min": 1, + "sim_inc_max": 1, + "points": [ + { + "size": 8 + } + ] + }, + { + "name": "BMS/Status/Balancing", + "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 0, + "sim_inc_max": 1, + "points": [ + { + "size": 8 + } + ] + } + ] + }, { - "id": "0x86", - "desc": "Current Limits", - "fields": [ - { - "name": "BMS/Pack/DCL", - "unit": "", - "points": [ - { - "size": 16 - } - ] - } - , - { - "name": "BMS/Pack/CCL", - "unit": "", - "points": [ - { - "size": 16, - "signed": true - } - ] - } - , - { - "name": "BMS/Pack/Current", - "unit": "", - "points": [ - { - "size": 16, - "signed": true - } - ] - } - ] - } - , + "id": "0x83", + "desc": "Cell Data", + "sim_freq": 700, + "fields": [ + { + "name": "BMS/Cells/Volts_High_Value", + "unit": "V", + "sim_min": 2.5, + "sim_max": 4.25, + "sim_inc_min": 0.001, + "sim_inc_max": 0.1, + "points": [ + { + "size": 16, + "format": "divide10000" + } + ] + }, + { + "name": "BMS/Cells/Volts_High_Chip", + "unit": "", + "sim_min": 1, + "sim_max": 12, + "sim_inc_min": 1, + "sim_inc_max": 1, + "points": [ + { + "size": 4 + } + ] + }, + { + "name": "BMS/Cells/Volts_High_Cell", + "unit": "", + "sim_min": 1, + "sim_max": 120, + "sim_inc_min": 1, + "sim_inc_max": 1, + "points": [ + { + "size": 4 + } + ] + }, + { + "name": "BMS/Cells/Volts_Low_Value", + "unit": "V", + "sim_min": 2.5, + "sim_max": 4.25, + "sim_inc_min": 0.001, + "sim_inc_max": 0.1, + "points": [ + { + "size": 16, + "format": "divide10000" + } + ] + }, + { + "name": "BMS/Cells/Volts_Low_Chip", + "unit": "", + "sim_min": 1, + "sim_max": 12, + "sim_inc_min": 1, + "sim_inc_max": 1, + "points": [ + { + "size": 4 + } + ] + }, + { + "name": "BMS/Cells/Volts_Low_Cell", + "unit": "", + "sim_min": 1, + "sim_max": 120, + "sim_inc_min": 1, + "sim_inc_max": 1, + "points": [ + { + "size": 4 + } + ] + }, + { + "name": "BMS/Cells/Volts_Avg_Value", + "unit": "V", + "sim_min": 2.5, + "sim_max": 4.25, + "sim_inc_min": 0.001, + "sim_inc_max": 0.1, + "points": [ + { + "size": 16, + "format": "divide10000" + } + ] + } + ] + }, { - "id": "0x87", - "desc": "Cell Voltage", - "fields": [ - { - "name": "BMS/PerCell/CellVoltage", - "unit": "", - "topic_append": true, - "points": [ - { - "size": 8 - } - , - { - "size": 16 - } - ] - } - , - { - "name": "BMS/PerCell/InstantVoltage", - "unit": "", - "points": [ - { - "size": 16 - } - ] - } - , - { - "name": "BMS/PerCell/InternalResistance", - "unit": "", - "points": [ - { - "size": 16 - } - ] - } - ] - } - , + "id": "0x84", + "desc": "Cell Temperatures", + "sim_freq": 700, + "fields": [ + { + "name": "BMS/Cells/Temp_High_Value", + "unit": "C", + "sim_min": 10, + "sim_max": 50, + "sim_inc_min": 0.01, + "sim_inc_max": 0.3, + "points": [ + { + "size": 16 + } + ] + }, + { + "name": "BMS/Cells/Temp_High_Cell", + "unit": "", + "sim_min": 1, + "sim_max": 120, + "sim_inc_min": 1, + "sim_inc_max": 1, + "points": [ + { + "size": 4 + } + ] + }, + { + "name": "BMS/Cells/Temp_High_Chip", + "unit": "", + "sim_min": 1, + "sim_max": 12, + "sim_inc_min": 1, + "sim_inc_max": 1, + "points": [ + { + "size": 4 + } + ] + }, + { + "name": "BMS/Cells/Temp_Low_Value", + "unit": "C", + "sim_min": 10, + "sim_max": 50, + "sim_inc_min": 0.01, + "sim_inc_max": 0.3, + "points": [ + { + "size": 16 + } + ] + }, + { + "name": "BMS/Cells/Temp_Low_Cell", + "unit": "", + "sim_min": 1, + "sim_max": 120, + "sim_inc_min": 1, + "sim_inc_max": 1, + "points": [ + { + "size": 4 + } + ] + }, + { + "name": "BMS/Cells/Temp_Low_Chip", + "unit": "", + "sim_min": 1, + "sim_max": 12, + "sim_inc_min": 1, + "sim_inc_max": 1, + "points": [ + { + "size": 4 + } + ] + }, + { + "name": "BMS/Cells/Temp_Avg_Value", + "unit": "C", + "sim_min": 10, + "sim_max": 50, + "sim_inc_min": 0.01, + "sim_inc_max": 0.3, + "points": [ + { + "size": 16 + } + ] + } + ] + }, { - "id": "0x88", - "desc": "BMS Voltage Noise", - "fields": [ - { - "name": "BMS/NoiseVoltage/1", - "unit": "%", - "points": [ - { - "size": 8 - } - ] - } - , - { - "name": "BMS/NoiseVoltage/2", - "unit": "%", - "points": [ - { - "size": 8 - } - ] - } - , - { - "name": "BMS/NoiseVoltage/3", - "unit": "%", - "points": [ - { - "size": 8 - } - ] - } - , - { - "name": "BMS/NoiseVoltage/4", - "unit": "%", - "points": [ - { - "size": 8 - } - ] - } - , - { - "name": "BMS/NoiseVoltage/5", - "unit": "%", - "points": [ - { - "size": 8 - } - ] - } - , - { - "name": "BMS/NoiseVoltage/6", - "unit": "%", - "points": [ - { - "size": 8 - } - ] - } - ] - } - , + "id": "0x85", + "desc": "Segment Temperatures", + "sim_freq": 700, + "fields": [ + { + "name": "BMS/Segment_Temp/1", + "unit": "C", + "sim_min": 10, + "sim_max": 50, + "sim_inc_min": 0.01, + "sim_inc_max": 0.3, + "points": [ + { + "size": 8, + "signed": true + } + ] + }, + { + "name": "BMS/Segment_Temp/2", + "unit": "C", + "sim_min": 10, + "sim_max": 50, + "sim_inc_min": 0.01, + "sim_inc_max": 0.3, + "points": [ + { + "size": 8, + "signed": true + } + ] + }, + { + "name": "BMS/Segment_Temp/3", + "unit": "C", + "sim_min": 10, + "sim_max": 50, + "sim_inc_min": 0.01, + "sim_inc_max": 0.3, + "points": [ + { + "size": 8, + "signed": true + } + ] + }, + { + "name": "BMS/Segment_Temp/4", + "unit": "C", + "sim_min": 10, + "sim_max": 50, + "sim_inc_min": 0.01, + "sim_inc_max": 0.3, + "points": [ + { + "size": 8, + "signed": true + } + ] + }, + { + "name": "BMS/Segment_Temp/5", + "unit": "C", + "sim_min": 10, + "sim_max": 50, + "sim_inc_min": 0.01, + "sim_inc_max": 0.3, + "points": [ + { + "size": 8, + "signed": true + } + ] + }, + { + "name": "BMS/Segment_Temp/6", + "unit": "C", + "sim_min": 10, + "sim_max": 50, + "sim_inc_min": 0.01, + "sim_inc_max": 0.3, + "points": [ + { + "size": 8, + "signed": true + } + ] + } + ] + }, { - "id": "0x702", - "desc": "BMS Debug", - "fields": [ - { - "name": "BMS/Debug/Spare0", - "unit": "", - "points": [ - { - "size": 8 - } - ] - } - , - { - "name": "BMS/Debug/Spare1", - "unit": "", - "points": [ - { - "size": 8 - } - ] - } - , - { - "name": "BMS/Debug/Spare2", - "unit": "", - "points": [ - { - "size": 16 - } - ] - } - , - { - "name": "BMS/Debug/Spare3", - "unit": "", - "points": [ - { - "size": 32 - } - ] - } - ] - } - , + "id": "0x86", + "desc": "Current Limits", + "sim_freq": 700, + "fields": [ + { + "name": "BMS/Pack/DCL", + "unit": "", + "sim_min": 20, + "sim_max": 520, + "sim_inc_min": 0.1, + "sim_inc_max": 4, + "points": [ + { + "size": 16 + } + ] + }, + { + "name": "BMS/Pack/CCL", + "unit": "", + "sim_min": 0, + "sim_max": 25, + "sim_inc_min": 0, + "sim_inc_max": 2, + "points": [ + { + "size": 16, + "signed": true + } + ] + }, + { + "name": "BMS/Pack/Current", + "unit": "", + "sim_min": 0, + "sim_max": 100, + "sim_inc_min": 0, + "sim_inc_max": 5, + "points": [ + { + "size": 16, + "signed": true + } + ] + } + ] + }, { - "id": "0x703", - "desc": "BMS Fault Debug", - "fields": [ - { - "name": "BMS/FaultDebug/Status", - "unit": "", - "points": [ - { - "size": 8 - } - ] - } - , - { - "name": "BMS/FaultDebug/PackCurrent", - "unit": "", - "points": [ - { - "size": 16, - "signed": true - } - ] - } - , - { - "name": "BMS/FaultDebug/DCL", - "unit": "", - "points": [ - { - "size": 16, - "signed": true - } - ] - } - ] + "id": "0x702", + "desc": "BMS Debug", + "sim_freq": 700, + "fields": [ + { + "name": "BMS/Debug/Spare0", + "unit": "", + "points": [ + { + "size": 8 + } + ] + }, + { + "name": "BMS/Debug/Spare1", + "unit": "", + "points": [ + { + "size": 8 + } + ] + }, + { + "name": "BMS/Debug/Spare2", + "unit": "", + "points": [ + { + "size": 16 + } + ] + }, + { + "name": "BMS/Debug/Spare3", + "unit": "", + "points": [ + { + "size": 32 + } + ] + } + ] } ] diff --git a/cangen/can-messages/calypso_cmd.json b/cangen/can-messages/calypso_cmd.json index 6ba5e9a..d21bea8 100644 --- a/cangen/can-messages/calypso_cmd.json +++ b/cangen/can-messages/calypso_cmd.json @@ -3,10 +3,15 @@ "id": "0x450", "desc": "Example Enc Msg", "key": "FirstOff", + "sim_freq": 750, "fields": [ { "name": "Calypso/Bidir/State/FirstOff/A", "unit": "Z", + "sim_min": 1, + "sim_max": 100, + "sim_inc_min": 1, + "sim_inc_max": 2, "points": [ { "size": 32, @@ -19,6 +24,10 @@ { "name": "Calypso/Bidir/State/FirstOff/B", "unit": "G", + "sim_min": 1, + "sim_max": 100, + "sim_inc_min": 1, + "sim_inc_max": 2, "points": [ { "size": 8, @@ -31,6 +40,10 @@ { "name": "Calypso/Bidir/State/FirstOff/C", "unit": "G", + "sim_min": 1, + "sim_max": 100, + "sim_inc_min": 1, + "sim_inc_max": 2, "points": [ { "size": 8, @@ -42,6 +55,10 @@ { "name": "Calypso/Bidir/State/FirstOff/D", "unit": "G", + "sim_min": 1, + "sim_max": 100, + "sim_inc_min": 1, + "sim_inc_max": 2, "points": [ { "size": 16, @@ -60,10 +77,15 @@ "desc": "Example Enc Msg Ext", "key": "SecondOff", "is_ext": true, + "sim_freq": 750, "fields": [ { "name": "Calypso/Bidir/State/SecondOff/A", "unit": "GG", + "sim_min": 1, + "sim_max": 100, + "sim_inc_min": 1, + "sim_inc_max": 2, "points": [ { "size": 32, @@ -77,10 +99,15 @@ { "id": "0x7FF", "desc": "Calypso bidir unknown key", + "sim_freq": 750, "fields": [ { "name": "Calypso/Bidir/Unknown", "unit": "pts", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 0, + "sim_inc_max": 1, "points": [ { "size": 8 diff --git a/cangen/can-messages/charger.json b/cangen/can-messages/charger.json index 71b0f76..d81c033 100644 --- a/cangen/can-messages/charger.json +++ b/cangen/can-messages/charger.json @@ -2,10 +2,15 @@ { "id": "0x1806E5F4", "desc": "BMS Message Send", + "sim_freq": 700, "fields": [ { "name": "BMS/Charging/Voltage", "unit": "V", + "sim_min": 400, + "sim_max": 505, + "sim_inc_min": 0.01, + "sim_inc_max": 0.3, "points": [ { "size": 16, @@ -17,6 +22,10 @@ { "name": "BMS/Charging/Current", "unit": "A", + "sim_min": 0, + "sim_max": 12, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 16, @@ -28,6 +37,10 @@ { "name": "BMS/Charging/Control", "unit": "", + "sim_min": 0, + "sim_max": 255, + "sim_inc_min": 255, + "sim_inc_max": 255, "points": [ { "size": 8 @@ -51,10 +64,15 @@ { "id": "0x18FF50E5", "desc": "Charger Box Status", + "sim_freq": 1000, "fields": [ { "name": "Charger/Box/Voltage", "unit": "V", + "sim_min": 400, + "sim_max": 505, + "sim_inc_min": 0.01, + "sim_inc_max": 0.3, "points": [ { "size": 16, @@ -66,6 +84,10 @@ { "name": "Charger/Box/Current", "unit": "A", + "sim_min": 0, + "sim_max": 12, + "sim_inc_min": 0.1, + "sim_inc_max": 1, "points": [ { "size": 16, @@ -78,6 +100,10 @@ { "name": "Charger/Box/F_CommTimeout", "unit": "bool", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -88,6 +114,10 @@ { "name": "Charger/Box/F_WrongBatConnection", "unit": "bool", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -98,6 +128,10 @@ { "name": "Charger/Box/F_VoltageWrong", "unit": "bool", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -108,6 +142,10 @@ { "name": "Charger/Box/F_OverTemp", "unit": "bool", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -118,6 +156,10 @@ { "name": "Charger/Box/F_HardwareFailure", "unit": "bool", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 diff --git a/cangen/can-messages/dti.json b/cangen/can-messages/dti.json index 72f153c..8753759 100644 --- a/cangen/can-messages/dti.json +++ b/cangen/can-messages/dti.json @@ -2,10 +2,15 @@ { "id": "0x416", "desc": "ERPM_Duty_Input_Voltage_Status", + "sim_freq": 25, "fields": [ { "name": "DTI/RPM/ERPM", "unit": "ERPM", + "sim_min": -2147483648, + "sim_max": 2147483648, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 32, @@ -17,6 +22,10 @@ { "name": "DTI/Power/Duty_Cycle", "unit": "%", + "sim_min": -32768, + "sim_max": 32767, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 16, @@ -29,6 +38,10 @@ { "name": "DTI/Power/Input_Voltage", "unit": "V", + "sim_min": 0, + "sim_max": 505, + "sim_inc_min": 0.01, + "sim_inc_max": 10, "points": [ { "size": 16, @@ -42,10 +55,15 @@ { "id": "0x436", "desc": "Currents_Status", + "sim_freq": 25, "fields": [ { "name": "DTI/Power/AC_Current", "unit": "A", + "sim_min": -125, + "sim_max": 250, + "sim_inc_min": 0.01, + "sim_inc_max": 20, "points": [ { "size": 16, @@ -58,6 +76,10 @@ { "name": "DTI/Power/DC_Current", "unit": "A", + "sim_min": -300, + "sim_max": 300, + "sim_inc_min": 2, + "sim_inc_max": 5, "points": [ { "size": 16, @@ -83,10 +105,15 @@ { "id": "0x456", "desc": "Temps_Fault_Code_Status", + "sim_freq": 25, "fields": [ { "name": "DTI/Temps/Controller_Temperature", "unit": "C", + "sim_min": 5, + "sim_max": 80, + "sim_inc_min": 0.05, + "sim_inc_max": 0.5, "points": [ { "size": 16, @@ -99,6 +126,10 @@ { "name": "DTI/Temps/Motor_Temperature", "unit": "C", + "sim_min": 5, + "sim_max": 80, + "sim_inc_min": 0.05, + "sim_inc_max": 0.5, "points": [ { "size": 16, @@ -111,6 +142,10 @@ { "name": "DTI/Fault/Fault_Code", "unit": "", + "sim_min": 0, + "sim_max": 10, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 8 @@ -134,10 +169,15 @@ { "id": "0x476", "desc": "MC_FOC_Algorithm", + "sim_freq": 25, "fields": [ { "name": "DTI/FOC/Component_Id", "unit": "A", + "sim_min": -2147483648, + "sim_max": 2147483648, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 32, @@ -150,6 +190,10 @@ { "name": "DTI/FOC/Component_Iq", "unit": "A", + "sim_min": -2147483648, + "sim_max": 2147483648, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 32, @@ -164,10 +208,15 @@ { "id": "0x496", "desc": "MC_General_Data", + "sim_freq": 25, "fields": [ { "name": "DTI/General/Throttle_Signal", "unit": "%", + "sim_min": -100, + "sim_max": 100, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 8, @@ -179,6 +228,10 @@ { "name": "DTI/General/Brake_Signal", "unit": "%", + "sim_min": -100, + "sim_max": 100, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 8, @@ -190,6 +243,10 @@ { "name": "DTI/General/Digital_Out_4", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -200,6 +257,10 @@ { "name": "DTI/General/Digital_Out_3", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -210,6 +271,10 @@ { "name": "DTI/General/Digital_Out_2", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -220,6 +285,10 @@ { "name": "DTI/General/Digital_Out_1", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -230,6 +299,10 @@ { "name": "DTI/General/Digital_In_4", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -240,6 +313,10 @@ { "name": "DTI/General/Digital_In_3", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -250,6 +327,10 @@ { "name": "DTI/General/Digital_In_2", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -260,6 +341,10 @@ { "name": "DTI/General/Digital_In_1", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -270,6 +355,10 @@ { "name": "DTI/General/Drive_Enable", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 8 @@ -280,6 +369,10 @@ { "name": "DTI/Limit/Motor_Temp_Limit", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -290,6 +383,10 @@ { "name": "DTI/Limit/Motor_Acc_Temp_Limit", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -300,6 +397,10 @@ { "name": "DTI/Limit/Input_Voltage_Limit", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -310,6 +411,10 @@ { "name": "DTI/Limit/IGBT_Temp_Limit", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -320,6 +425,10 @@ { "name": "DTI/Limit/IGBT_Acc_Temp_Limit", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -330,6 +439,10 @@ { "name": "DTI/Limit/Drive_Enable_Limit", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -340,6 +453,10 @@ { "name": "DTI/Limit/DC_Current_Limit", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -350,6 +467,10 @@ { "name": "DTI/Limit/Cap_Temp_Limit", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -360,6 +481,10 @@ { "name": "DTI/Limit/Power_Limit", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -370,6 +495,10 @@ { "name": "DTI/Limit/RPM_Max_Limit", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -380,6 +509,10 @@ { "name": "DTI/Limit/RPM_Min_Limit", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -412,6 +545,10 @@ { "name": "DTI/General/CAN_Map_Version", "unit": "", + "sim_min": 20, + "sim_max": 24, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 8 @@ -424,10 +561,15 @@ { "id": "0x036", "desc": "AC_Current_Command", + "sim_freq": 25, "fields": [ { "name": "MPU/Commands/AC_Current_Target", "unit": "A", + "sim_min": 0, + "sim_max": 380, + "sim_inc_min": 0.01, + "sim_inc_max": 25, "points": [ { "size": 16, @@ -442,10 +584,15 @@ { "id": "0x056", "desc": "Brake_Current_Command", + "sim_freq": 25, "fields": [ { "name": "MPU/Commands/Brake_Current_Target", "unit": "A", + "sim_min": 0, + "sim_max": 150, + "sim_inc_min": 0.01, + "sim_inc_max": 10, "points": [ { "size": 16, @@ -471,10 +618,15 @@ { "id": "0x076", "desc": "ERPM_Command", + "sim_freq": 25, "fields": [ { "name": "DTI/Commands/ERPM_Target", "unit": "A", + "sim_min": -2147483648, + "sim_max": 2147483648, + "sim_inc_min": 1, + "sim_inc_max": 10, "points": [ { "size": 32, @@ -499,10 +651,15 @@ { "id": "0x096", "desc": "Position_Command", + "sim_freq": 25, "fields": [ { "name": "DTI/Commands/Position_Target", "unit": "degree", + "sim_min": 0, + "sim_max": 360, + "sim_inc_min": 0.05, + "sim_inc_max": 5, "points": [ { "size": 16, @@ -528,10 +685,15 @@ { "id": "0x0B6", "desc": "Relative_Current_Command", + "sim_freq": 25, "fields": [ { "name": "DTI/Commands/Relative_Current_Target", "unit": "A", + "sim_min": -100, + "sim_max": 100, + "sim_inc_min": 0.01, + "sim_inc_max": 5, "points": [ { "size": 16, @@ -557,10 +719,15 @@ { "id": "0x0D6", "desc": "Relative_Brake_Current_Command", + "sim_freq": 25, "fields": [ { "name": "DTI/Commands/Relative_Brake_Current_Target", "unit": "A", + "sim_min": -100, + "sim_max": 100, + "sim_inc_min": 0.01, + "sim_inc_max": 5, "points": [ { "size": 16, @@ -586,10 +753,15 @@ { "id": "0x0F6", "desc": "Digital_Output_Command", + "sim_freq": 25, "fields": [ { "name": "DTI/Commands/Digital_Output_1_Target", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -600,6 +772,10 @@ { "name": "DTI/Commands/Digital_Output_2_Target", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -610,6 +786,10 @@ { "name": "DTI/Commands/Digital_Output_3_Target", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -620,6 +800,10 @@ { "name": "DTI/Commands/Digital_Output_4_Target", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -643,10 +827,15 @@ { "id": "0x116", "desc": "Max_AC_Current_Command", + "sim_freq": 25, "fields": [ { "name": "BMS/Commands/Max_AC_Current_Target", "unit": "A", + "sim_min": 0, + "sim_max": 250, + "sim_inc_min": 0.01, + "sim_inc_max": 25, "points": [ { "size": 16, @@ -672,10 +861,15 @@ { "id": "0x136", "desc": "Max_AC_Brake_Current_Command", + "sim_freq": 25, "fields": [ { "name": "BMS/Commands/Max_AC_Brake_Current_Target", "unit": "A", + "sim_min": -250, + "sim_max": 0, + "sim_inc_min": 0.01, + "sim_inc_max": 25, "points": [ { "size": 16, @@ -701,10 +895,15 @@ { "id": "0x156", "desc": "Max_DC_Current_Command", + "sim_freq": 25, "fields": [ { "name": "BMS/Commands/Max_DC_Current_Target", "unit": "A", + "sim_min": 0, + "sim_max": 505, + "sim_inc_min": 0.05, + "sim_inc_max": 5, "points": [ { "size": 16, @@ -719,10 +918,15 @@ { "id": "0x176", "desc": "Max_DC_Brake_Current_Command", + "sim_freq": 25, "fields": [ { "name": "BMS/Commands/Max_DC_Brake_Current_Target", "unit": "A", + "sim_min": -250, + "sim_max": 0, + "sim_inc_min": 0.01, + "sim_inc_max": 10, "points": [ { "size": 16, @@ -737,10 +941,15 @@ { "id": "0x196", "desc": "Drive_Enable_Command", + "sim_freq": 25, "fields": [ { "name": "MPU/Commands/Drive_Enable_Target", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 8 diff --git a/cangen/can-messages/mpu.json b/cangen/can-messages/mpu.json index 3a4e89b..62d43cd 100644 --- a/cangen/can-messages/mpu.json +++ b/cangen/can-messages/mpu.json @@ -2,10 +2,15 @@ { "id": "0x501", "desc": "MPU Status", + "sim_freq": 250, "fields": [ { "name": "MPU/State/Mode", "unit": "", + "sim_min": 0, + "sim_max": 4, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 8 @@ -16,6 +21,10 @@ { "name": "MPU/State/ModeIndex", "unit": "", + "sim_min": 0, + "sim_max": 6, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 8 @@ -26,6 +35,10 @@ { "name": "MPU/State/Speed", "unit": "mph", + "sim_min": 0, + "sim_max": 88, + "sim_inc_min": 0, + "sim_inc_max": 2, "points": [ { "size": 8, @@ -37,6 +50,10 @@ { "name": "MPU/State/TSMS", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 8 @@ -49,10 +66,15 @@ { "id": "0x500", "desc": "MPU Sense Acceleromter", + "sim_freq": 250, "fields": [ { "name": "MPU/Sense/Accel", "unit": "g", + "sim_min": 0, + "sim_max": 2, + "sim_inc_min": 0.01, + "sim_inc_max": 0.25, "points": [ { "size": 16 @@ -73,10 +95,16 @@ { "id": "0x506", "desc": "MPU Sense Gyro", + "sim_freq": 250, + "fields": [ { "name": "MPU/Sense/Gyro", "unit": "", + "sim_min": 0, + "sim_max": 7, + "sim_inc_min": 0.01, + "sim_inc_max": 0.5, "points": [ { "size": 16 @@ -97,10 +125,15 @@ { "id": "0x507", "desc": "MPU Sense Temp", + "sim_freq": 1000, "fields": [ { "name": "MPU/Sense/Temp_IMU", "unit": "C", + "sim_min": 0, + "sim_max": 70, + "sim_inc_min": 1, + "sim_inc_max": 2, "points": [ { "size": 16, @@ -114,10 +147,15 @@ { "id": "0x502", "desc": "MPU Fault", + "sim_freq": 250, "fields": [ { "name": "MPU/Fault/Code", "unit": "", + "sim_min": 0, + "sim_max": 2048, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 32 @@ -128,6 +166,10 @@ { "name": "MPU/Fault/Severity", "unit": "", + "sim_min": 0, + "sim_max": 5, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 8 @@ -140,10 +182,15 @@ { "id": "0x503", "desc": "MPU Sense Voltage", + "sim_freq": 1000, "fields": [ { "name": "MPU/Sense/Voltage", "unit": "V", + "sim_min": 22.5, + "sim_max": 29, + "sim_inc_min": 0.02, + "sim_inc_max": 0.15, "points": [ { "size": 32, @@ -158,10 +205,15 @@ { "id": "0x504", "desc": "MPU Accel Pedals", + "sim_freq": 100, "fields": [ { "name": "MPU/Pedals/Accelerator_1", "unit": "", + "sim_min": 800, + "sim_max": 1900, + "sim_inc_min": 1, + "sim_inc_max": 24, "points": [ { "size": 32 @@ -172,6 +224,10 @@ { "name": "MPU/Pedals/Accelerator_2", "unit": "", + "sim_min": 1200, + "sim_max": 2300, + "sim_inc_min": 1, + "sim_inc_max": 24, "points": [ { "size": 32 @@ -184,10 +240,15 @@ { "id": "0x505", "desc": "MPU Brake Pedals", + "sim_freq": 100, "fields": [ { "name": "MPU/Pedals/Brake_1", "unit": "", + "sim_min": 580, + "sim_max": 990, + "sim_inc_min": 1, + "sim_inc_max": 10, "points": [ { "size": 32 @@ -198,6 +259,10 @@ { "name": "MPU/Pedals/Brake_2", "unit": "", + "sim_min": 580, + "sim_max": 990, + "sim_inc_min": 1, + "sim_inc_max": 10, "points": [ { "size": 32 @@ -210,10 +275,15 @@ { "id": "0x701", "desc": "MPU Debug", + "sim_freq": 1000, "fields": [ { "name": "MPU/Debug/Spare0", "unit": "", + "sim_min": 580, + "sim_max": 990, + "sim_inc_min": 1, + "sim_inc_max": 10, "points": [ { "size": 8 @@ -224,6 +294,10 @@ { "name": "MPU/Debug/Spare1", "unit": "", + "sim_min": 580, + "sim_max": 990, + "sim_inc_min": 1, + "sim_inc_max": 10, "points": [ { "size": 8, @@ -235,6 +309,10 @@ { "name": "MPU/Debug/Spare2", "unit": "", + "sim_min": 580, + "sim_max": 990, + "sim_inc_min": 1, + "sim_inc_max": 10, "points": [ { "size": 16, @@ -246,6 +324,10 @@ { "name": "MPU/Debug/Spare3", "unit": "", + "sim_min": 580, + "sim_max": 990, + "sim_inc_min": 1, + "sim_inc_max": 10, "points": [ { "size": 32, @@ -260,10 +342,15 @@ { "id": "0x123", "desc": "MPU Shutdown", + "sim_freq": 1000, "fields": [ { "name": "MPU/Shutdown/CockpitBRB", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -274,6 +361,10 @@ { "name": "MPU/Shutdown/BMS", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -284,6 +375,10 @@ { "name": "MPU/Shutdown/Inertia", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -294,6 +389,10 @@ { "name": "MPU/Shutdown/Spare_GPIO_1", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -304,6 +403,10 @@ { "name": "MPU/Shutdown/IMD", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -314,6 +417,10 @@ { "name": "MPU/Shutdown/BSPD", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -324,6 +431,10 @@ { "name": "MPU/Shutdown/BOTS", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -334,6 +445,10 @@ { "name": "MPU/Shutdown/HVD_Interlock", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -344,6 +459,10 @@ { "name": "MPU/Shutdown/HVC_Interlock", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -367,10 +486,15 @@ { "id": "0x111", "desc": "MPU Fuses", + "sim_freq": 1000, "fields": [ { "name": "MPU/Fuses/Battbox", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -381,6 +505,10 @@ { "name": "MPU/Fuses/LVBox", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -391,6 +519,10 @@ { "name": "MPU/Fuses/FanRadiator", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -401,6 +533,10 @@ { "name": "MPU/Fuses/MC", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -411,6 +547,10 @@ { "name": "MPU/Fuses/FanBattbox", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -421,6 +561,10 @@ { "name": "MPU/Fuses/Pump", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -431,6 +575,10 @@ { "name": "MPU/Fuses/Dashboard", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -441,6 +589,10 @@ { "name": "MPU/Fuses/Brakelight", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 @@ -451,6 +603,10 @@ { "name": "MPU/Fuses/BRB", "unit": "", + "sim_min": 0, + "sim_max": 1, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 1 diff --git a/cangen/can-messages/msb.json b/cangen/can-messages/msb.json index b67baa9..30636e3 100644 --- a/cangen/can-messages/msb.json +++ b/cangen/can-messages/msb.json @@ -2,10 +2,15 @@ { "id": "0x602", "desc": "Front Left MSB Env", + "sim_freq": 500, "fields": [ { "name": "MSB/FL/Temp", "unit": "C", + "sim_min": 0, + "sim_max": 80, + "sim_inc_min": 0.01, + "sim_inc_max": 0.25, "points": [ { "size": 16 @@ -16,6 +21,10 @@ { "name": "MSB/FL/Humidity", "unit": "", + "sim_min": 20, + "sim_max": 80, + "sim_inc_min": 1, + "sim_inc_max": 2.5, "points": [ { "size": 16 @@ -28,10 +37,15 @@ { "id": "0x603", "desc": "Front Left MSB Accel", + "sim_freq": 500, "fields": [ { "name": "MSB/FL/Accel", "unit": "g", + "sim_min": 0, + "sim_max": 2, + "sim_inc_min": 0.01, + "sim_inc_max": 0.25, "points": [ { "size": 16 @@ -52,9 +66,14 @@ { "id": "0x604", "desc": "Front Left MSB Gyro", + "sim_freq": 500, "fields": [ { "name": "MSB/FL/Gyro", + "sim_min": 0, + "sim_max": 15, + "sim_inc_min": 0.1, + "sim_inc_max": 0.5, "unit": "", "points": [ { @@ -76,10 +95,15 @@ { "id": "0x605", "desc": "Front Left MSB Strain", + "sim_freq": 500, "fields": [ { "name": "MSB/FL/Strain", "unit": "", + "sim_min": 0, + "sim_max": 10, + "sim_inc_min": 0.001, + "sim_inc_max": 0.020, "points": [ { "size": 32 @@ -96,10 +120,15 @@ { "id": "0x606", "desc": "Front Left Shockpot", + "sim_freq": 500, "fields": [ { "name": "MSB/FL/Shock", "unit": "", + "sim_min": 0, + "sim_max": 10, + "sim_inc_min": 0.001, + "sim_inc_max": 0.020, "points": [ { "size": 32 @@ -112,10 +141,15 @@ { "id": "0x607", "desc": "Front Left Ride Height", + "sim_freq": 500, "fields": [ { "name": "MSB/FL/RideHeight", "unit": "", + "sim_min": 0, + "sim_max": 10, + "sim_inc_min": 0.001, + "sim_inc_max": 0.020, "points": [ { "size": 16, @@ -129,10 +163,15 @@ { "id": "0x608", "desc": "Front Left Wheel Temp", + "sim_freq": 500, "fields": [ { "name": "MSB/FL/WheelTemp", "unit": "C", + "sim_min": 0, + "sim_max": 110, + "sim_inc_min": 0.5, + "sim_inc_max": 1.5, "points": [ { "size": 16 @@ -145,10 +184,15 @@ { "id": "0x622", "desc": "Front Right MSB Env", + "sim_freq": 500, "fields": [ { "name": "MSB/FR/Temp", "unit": "C", + "sim_min": 0, + "sim_max": 80, + "sim_inc_min": 0.01, + "sim_inc_max": 0.25, "points": [ { "size": 16 @@ -159,6 +203,10 @@ { "name": "MSB/FR/Humidity", "unit": "", + "sim_min": 20, + "sim_max": 80, + "sim_inc_min": 1, + "sim_inc_max": 2.5, "points": [ { "size": 16 @@ -171,10 +219,15 @@ { "id": "0x623", "desc": "Front Right MSB Accel", + "sim_freq": 500, "fields": [ { "name": "MSB/FR/Accel", "unit": "g", + "sim_min": 0, + "sim_max": 2, + "sim_inc_min": 0.01, + "sim_inc_max": 0.25, "points": [ { "size": 16 @@ -195,10 +248,15 @@ { "id": "0x624", "desc": "Front Right MSB Gyro", + "sim_freq": 500, "fields": [ { "name": "MSB/FR/Gyro", "unit": "", + "sim_min": 0, + "sim_max": 15, + "sim_inc_min": 0.1, + "sim_inc_max": 0.5, "points": [ { "size": 16 @@ -219,10 +277,15 @@ { "id": "0x625", "desc": "Front Right MSB Strain", + "sim_freq": 500, "fields": [ { "name": "MSB/FR/Strain", "unit": "", + "sim_min": 0, + "sim_max": 10, + "sim_inc_min": 0.001, + "sim_inc_max": 0.020, "points": [ { "size": 32 @@ -239,10 +302,15 @@ { "id": "0x626", "desc": "Front Right Shockpot", + "sim_freq": 500, "fields": [ { "name": "MSB/FR/Shock", "unit": "", + "sim_min": 0, + "sim_max": 10, + "sim_inc_min": 0.001, + "sim_inc_max": 0.020, "points": [ { "size": 32 @@ -255,10 +323,15 @@ { "id": "0x627", "desc": "Front Right Ride Height", + "sim_freq": 500, "fields": [ { "name": "MSB/FR/RideHeight", "unit": "", + "sim_min": 0, + "sim_max": 10, + "sim_inc_min": 0.001, + "sim_inc_max": 0.020, "points": [ { "size": 16, @@ -272,10 +345,15 @@ { "id": "0x628", "desc": "Front Right Wheel Temp", + "sim_freq": 500, "fields": [ { "name": "MSB/FR/WheelTemp", "unit": "C", + "sim_min": 0, + "sim_max": 110, + "sim_inc_min": 0.5, + "sim_inc_max": 1.5, "points": [ { "size": 16 @@ -288,10 +366,15 @@ { "id": "0x642", "desc": "Back Left MSB Env", + "sim_freq": 500, "fields": [ { "name": "MSB/BL/Temp", "unit": "C", + "sim_min": 0, + "sim_max": 80, + "sim_inc_min": 0.01, + "sim_inc_max": 0.25, "points": [ { "size": 16 @@ -302,6 +385,10 @@ { "name": "MSB/BL/Humidity", "unit": "", + "sim_min": 20, + "sim_max": 80, + "sim_inc_min": 1, + "sim_inc_max": 2.5, "points": [ { "size": 16 @@ -314,10 +401,15 @@ { "id": "0x643", "desc": "Back Left MSB Accel", + "sim_freq": 500, "fields": [ { "name": "MSB/BL/Accel", "unit": "g", + "sim_min": 0, + "sim_max": 2, + "sim_inc_min": 0.01, + "sim_inc_max": 0.25, "points": [ { "size": 16 @@ -338,10 +430,15 @@ { "id": "0x644", "desc": "Back Left MSB Gyro", + "sim_freq": 500, "fields": [ { "name": "MSB/BL/Gyro", "unit": "", + "sim_min": 0, + "sim_max": 15, + "sim_inc_min": 0.1, + "sim_inc_max": 0.5, "points": [ { "size": 16 @@ -362,10 +459,15 @@ { "id": "0x645", "desc": "Back Left MSB Strain", + "sim_freq": 500, "fields": [ { "name": "MSB/BL/Strain", "unit": "", + "sim_min": 0, + "sim_max": 10, + "sim_inc_min": 0.001, + "sim_inc_max": 0.020, "points": [ { "size": 32 @@ -382,10 +484,15 @@ { "id": "0x646", "desc": "Back Left Shockpot", + "sim_freq": 500, "fields": [ { "name": "MSB/BL/Shock", "unit": "", + "sim_min": 0, + "sim_max": 10, + "sim_inc_min": 0.001, + "sim_inc_max": 0.020, "points": [ { "size": 32 @@ -398,10 +505,15 @@ { "id": "0x647", "desc": "Front Back Ride Height", + "sim_freq": 500, "fields": [ { "name": "MSB/BL/RideHeight", "unit": "", + "sim_min": 0, + "sim_max": 10, + "sim_inc_min": 0.001, + "sim_inc_max": 0.020, "points": [ { "size": 16, @@ -415,10 +527,15 @@ { "id": "0x648", "desc": "Back Left Wheel Temp", + "sim_freq": 500, "fields": [ { "name": "MSB/BL/WheelTemp", "unit": "C", + "sim_min": 0, + "sim_max": 110, + "sim_inc_min": 0.5, + "sim_inc_max": 1.5, "points": [ { "size": 16 @@ -431,10 +548,15 @@ { "id": "0x662", "desc": "Back Right MSB Env", + "sim_freq": 500, "fields": [ { "name": "MSB/BR/Temp", "unit": "C", + "sim_min": 0, + "sim_max": 80, + "sim_inc_min": 0.01, + "sim_inc_max": 0.25, "points": [ { "size": 16 @@ -445,6 +567,10 @@ { "name": "MSB/BR/Humidity", "unit": "", + "sim_min": 20, + "sim_max": 80, + "sim_inc_min": 1, + "sim_inc_max": 2.5, "points": [ { "size": 16 @@ -457,10 +583,15 @@ { "id": "0x663", "desc": "Back Right MSB Accel", + "sim_freq": 500, "fields": [ { "name": "MSB/BR/Accel", "unit": "g", + "sim_min": 0, + "sim_max": 2, + "sim_inc_min": 0.01, + "sim_inc_max": 0.25, "points": [ { "size": 16 @@ -481,10 +612,15 @@ { "id": "0x664", "desc": "Back Right MSB Gyro", + "sim_freq": 500, "fields": [ { "name": "MSB/BR/Gyro", "unit": "", + "sim_min": 0, + "sim_max": 15, + "sim_inc_min": 0.1, + "sim_inc_max": 0.5, "points": [ { "size": 16 @@ -505,10 +641,15 @@ { "id": "0x665", "desc": "Back Right MSB Strain", + "sim_freq": 500, "fields": [ { "name": "MSB/BR/Strain", "unit": "", + "sim_min": 0, + "sim_max": 10, + "sim_inc_min": 0.001, + "sim_inc_max": 0.020, "points": [ { "size": 32 @@ -525,10 +666,15 @@ { "id": "0x666", "desc": "Back Right Shockpot", + "sim_freq": 500, "fields": [ { "name": "MSB/BR/Shock", "unit": "", + "sim_min": 0, + "sim_max": 10, + "sim_inc_min": 0.001, + "sim_inc_max": 0.020, "points": [ { "size": 32 @@ -541,10 +687,15 @@ { "id": "0x667", "desc": "Back Right Ride Height", + "sim_freq": 500, "fields": [ { "name": "MSB/BR/RideHeight", "unit": "", + "sim_min": 0, + "sim_max": 10, + "sim_inc_min": 0.001, + "sim_inc_max": 0.020, "points": [ { "size": 16, @@ -558,10 +709,15 @@ { "id": "0x668", "desc": "Back Right Wheel Temp", + "sim_freq": 500, "fields": [ { "name": "MSB/BR/WheelTemp", "unit": "C", + "sim_min": 0, + "sim_max": 110, + "sim_inc_min": 0.5, + "sim_inc_max": 1.5, "points": [ { "size": 16 diff --git a/cangen/can-messages/wheel.json b/cangen/can-messages/wheel.json index 66e1366..dc79dab 100644 --- a/cangen/can-messages/wheel.json +++ b/cangen/can-messages/wheel.json @@ -2,10 +2,15 @@ { "id": "0x680", "desc": "Wheel State", + "sim_freq": 8, "fields": [ { "name": "WHEEL/Buttons/1", "unit": "", + "sim_min": 0, + "sim_max": 8, + "sim_inc_min": 1, + "sim_inc_max": 8, "points": [ { "size": 8 @@ -16,6 +21,10 @@ { "name": "WHEEL/Buttons/2", "unit": "", + "sim_min": 0, + "sim_max": 2, + "sim_inc_min": 1, + "sim_inc_max": 1, "points": [ { "size": 8 diff --git a/ftdi_flash.cfg b/ftdi_flash.cfg new file mode 100644 index 0000000..a80dc2b --- /dev/null +++ b/ftdi_flash.cfg @@ -0,0 +1,16 @@ +adapter driver ftdi +ftdi_vid_pid 0x0403 0x6010 + +# Initial state: Assuming 0x0008 doesn't interfere with your setup +# and 0x000b sets the required initial states for your other signals. +ftdi_layout_init 0x0008 0x000b + +ftdi_layout_signal LED_Tx -data 0x00F0 -oe 0x00F0 +ftdi_layout_signal LED_Rx -data 0x00F0 -oe 0x00F0 + +# Configure GPIOL0 (ADBUS4) as nSRST, assuming active low reset +# Setting `-data` for active low, `-oe` to enable output. +# If tri-state isn't supported, this configures the pin as push-pull. +ftdi_layout_signal nSRST -data 0x0010 -oe 0x0010 + +transport select jtag diff --git a/general/.clang-format-ignore b/general/.clang-format-ignore new file mode 100644 index 0000000..4830892 --- /dev/null +++ b/general/.clang-format-ignore @@ -0,0 +1 @@ +./*/vl6180x* \ No newline at end of file diff --git a/general/include/LTC4015.h b/general/include/LTC4015.h index 76a59b5..b6de735 100644 --- a/general/include/LTC4015.h +++ b/general/include/LTC4015.h @@ -12,45 +12,47 @@ #include #include "stm32xx_hal.h" -//Device address -#define LTC4015_ADDR_68 (0x68) +//Device address +#define LTC4015_ADDR_68 (0x68) //Enable Register for Specified alert register, page 49-50 -#define EN_LIMIT_ALERTS 0x0D //LIMIT_ALERTS +#define EN_LIMIT_ALERTS 0x0D //LIMIT_ALERTS #define EN_CHARGER_STATE_ALERTS 0x0E //CHARGER_STATUS_ALERTS #define EN_CHARGE_STATUS_ALERTS 0x0F //CHARGE_STATUS_ALERTS //Register storing if specifed fault has occurred, each bit represents different fault, page 52-53 #define LTC4015_CHGSTATE 0x34 //Real time battery charger state indicator -#define CHARGE_STATUS 0x35 +#define CHARGE_STATUS 0x35 -//Errors need to be enabled, with remain high once flagged till reset or disabled -#define LIMIT_ALERTS 0x36 +//Errors need to be enabled, with remain high once flagged till reset or disabled +#define LIMIT_ALERTS 0x36 #define CHARGER_STATE_ALERTS 0x37 #define CHARGE_STATUS_ALERTS 0x38 -#define SYSTEM_STATUS 0x39 - - +#define SYSTEM_STATUS 0x39 //Coulomb Counter -#define QCOUNT_LO_ALERT_LIMIT 0x10 -#define QCOUNT_HI_ALERT_LIMIT 0x11 +#define QCOUNT_LO_ALERT_LIMIT 0x10 +#define QCOUNT_HI_ALERT_LIMIT 0x11 #define QCOUNT_PRESCALE_FACTOR 0x12 -#define QCOUNT 0x13 -#define CONFIG_BITS 0x14 +#define QCOUNT 0x13 +#define CONFIG_BITS 0x14 //Enable Coulomb Counter Low Alert.(0xOD Bit 13) //Enable Coulomb Counter High Alert.(0xOD Bit 12) -typedef struct -{ - I2C_HandleTypeDef *i2cHandle; - uint16_t chargeFaults; //Stores error faults from CHGSTATE register - uint16_t qcount; - uint16_t limitAlerts; +typedef int (*Read_Ptr)(uint16_t DevAddress, uint16_t MemAddress, + uint16_t MemAddSize, uint8_t *pData, uint16_t Size); +typedef int (*Write_Ptr)(uint16_t DevAddress, uint16_t MemAddress, + uint16_t MemAddSize, uint8_t *pData, uint16_t Size); -}LTC4015_T; +typedef struct { + uint16_t chargeFaults; //Stores error faults from CHGSTATE register + uint16_t qcount; + uint16_t limitAlerts; + Read_Ptr read; + Write_Ptr write; +} LTC4015_T; /** * @brief Initializes the LTC4015EUHF#PBF @@ -59,8 +61,7 @@ typedef struct * @param hi2c * @return HAL_StatusTypeDef */ -HAL_StatusTypeDef LTC4015_Init(LTC4015_T *dev, I2C_HandleTypeDef *i2cHandle); - +int LTC4015_Init(LTC4015_T *dev, Read_Ptr read, Write_Ptr write); /** * @brief Reads from the LTC4015EUHF#PBF load switch @@ -69,8 +70,7 @@ HAL_StatusTypeDef LTC4015_Init(LTC4015_T *dev, I2C_HandleTypeDef *i2cHandle); * @param dev * @param i2c_handle */ -HAL_StatusTypeDef LTC4015_read(LTC4015_T *dev, uint16_t reg, uint16_t *data); - +int LTC4015_read(LTC4015_T *dev, uint16_t reg, uint16_t *data); /** * @brief Writes to the LTC4015EUHF#PBF load switch @@ -80,8 +80,7 @@ HAL_StatusTypeDef LTC4015_read(LTC4015_T *dev, uint16_t reg, uint16_t *data); * @param i2c_handle * @return HAL_StatusTypeDef */ -HAL_StatusTypeDef LTC4015_write(LTC4015_T *dev, uint16_t reg, uint16_t data); - +int LTC4015_write(LTC4015_T *dev, uint16_t reg, uint16_t data); /** * @brief Checks coulombs of charger to see if within a given range, more info on page 38-40 @@ -93,12 +92,11 @@ HAL_StatusTypeDef LTC4015_write(LTC4015_T *dev, uint16_t reg, uint16_t data); * @param lowAlert * @return HAL_StatusTypeDef, QCOUNT, Faulted */ -HAL_StatusTypeDef LTC4015_Qcounter(LTC4015_T *dev,uint16_t prescaler, uint16_t highAlert, uint16_t lowAlert); - +int LTC4015_Qcounter(LTC4015_T *dev, uint16_t prescaler, uint16_t highAlert, + uint16_t lowAlert); #ifndef MAX_NUM_LTC4015_INSTANCES #define MAX_NUM_LTC4015_INSTANCES 1 #endif - -#endif +#endif diff --git a/general/include/ads131m04.h b/general/include/ads131m04.h index 8a00da2..6cb9719 100644 --- a/general/include/ads131m04.h +++ b/general/include/ads131m04.h @@ -4,15 +4,15 @@ #include "stm32xx_hal.h" typedef struct { - SPI_HandleTypeDef *spi; - GPIO_TypeDef *gpio; - uint8_t cs_pin; + SPI_HandleTypeDef *spi; + GPIO_TypeDef *gpio; + uint8_t cs_pin; } ads131_t; /* Method to initialize communication over SPI and configure the ADC into * Continuous Conversion Mode*/ void ads131m04_init(ads131_t *adc, SPI_HandleTypeDef *hspi, GPIO_TypeDef *hgpio, - uint8_t cs_pin); + uint8_t cs_pin); /* Method to read values out of the ADC */ HAL_StatusTypeDef ads131m04_read_adc(ads131_t *adc, uint32_t *adc_values); diff --git a/general/include/lsm6dso.h b/general/include/lsm6dso.h index a27dfd2..67ae0e1 100644 --- a/general/include/lsm6dso.h +++ b/general/include/lsm6dso.h @@ -14,29 +14,29 @@ #define LSM6DSO_I2C_ADDRESS 0x6A << 1 /* Shifted because datasheet said to */ // Not sure if these are all needed, also not sure if more need to be added /* For register descriptions reference datasheet pages 47 - 98 */ -#define LSM6DSO_REG_FUNC_CFG_ACCESS \ - 0x01 /* Enable embedded functions register */ -#define LSM6DSO_REG_INTERRUPT_CTRL_1 \ - 0x0D /* INT1 pin control, used for interrupts */ -#define LSM6DSO_REG_INTERRUPT_CTRL_2 \ - 0x0E /* INT2 pin control, used for interrupts */ -#define LSM6DSO_REG_DEVICE_ID 0x0F /* Register for checking communication */ +#define LSM6DSO_REG_FUNC_CFG_ACCESS \ + 0x01 /* Enable embedded functions register */ +#define LSM6DSO_REG_INTERRUPT_CTRL_1 \ + 0x0D /* INT1 pin control, used for interrupts */ +#define LSM6DSO_REG_INTERRUPT_CTRL_2 \ + 0x0E /* INT2 pin control, used for interrupts */ +#define LSM6DSO_REG_DEVICE_ID 0x0F /* Register for checking communication */ #define LSM6DSO_REG_ACCEL_CTRL 0x10 /* Accelerometer Control Register */ -#define LSM6DSO_REG_GYRO_CTRL 0x11 /* Gyroscope Control Register */ -#define LSM6DSO_REG_ALL_INTERRUPT_SRC \ - 0x1A /* Source Register for all interupsts */ -#define LSM6DSO_REG_WAKEUP_INTERRUPT_SRC \ - 0x1B /* Wake up interupt source register */ +#define LSM6DSO_REG_GYRO_CTRL 0x11 /* Gyroscope Control Register */ +#define LSM6DSO_REG_ALL_INTERRUPT_SRC \ + 0x1A /* Source Register for all interupsts */ +#define LSM6DSO_REG_WAKEUP_INTERRUPT_SRC \ + 0x1B /* Wake up interupt source register */ #define LSM6DSO_REG_TAP_INTERRUPT_SRC 0x1C /* Tap Interrupt source register */ -#define LSM6DSO_REG_6D_INTERRUPT_SRC \ - 0x1D /* 6-direction Interrupt source register */ -#define LSM6DSO_REG_STATUS 0x1E /* Status register */ -#define LSM6DSO_REG_GYRO_X_AXIS_L 0x22 /* Gyro pitch axis lower bits */ -#define LSM6DSO_REG_GYRO_X_AXIS_H 0x23 /* Gyro pitch axis upper bits */ -#define LSM6DSO_REG_GYRO_Y_AXIS_L 0x24 /* Gyro roll axis lower bits */ -#define LSM6DSO_REG_GYRO_Y_AXIS_H 0x25 /* Gyro roll axis upper bits */ -#define LSM6DSO_REG_GYRO_Z_AXIS_L 0x26 /* Gyro yaw axis lower bits */ -#define LSM6DSO_REG_GYRO_Z_AXIS_H 0x27 /* Gyro yaw axis higher bits */ +#define LSM6DSO_REG_6D_INTERRUPT_SRC \ + 0x1D /* 6-direction Interrupt source register */ +#define LSM6DSO_REG_STATUS 0x1E /* Status register */ +#define LSM6DSO_REG_GYRO_X_AXIS_L 0x22 /* Gyro pitch axis lower bits */ +#define LSM6DSO_REG_GYRO_X_AXIS_H 0x23 /* Gyro pitch axis upper bits */ +#define LSM6DSO_REG_GYRO_Y_AXIS_L 0x24 /* Gyro roll axis lower bits */ +#define LSM6DSO_REG_GYRO_Y_AXIS_H 0x25 /* Gyro roll axis upper bits */ +#define LSM6DSO_REG_GYRO_Z_AXIS_L 0x26 /* Gyro yaw axis lower bits */ +#define LSM6DSO_REG_GYRO_Z_AXIS_H 0x27 /* Gyro yaw axis higher bits */ #define LSM6DSO_REG_ACCEL_X_AXIS_L 0x28 /* Accelerometer X axis lower bits */ #define LSM6DSO_REG_ACCEL_X_AXIS_H 0x29 /* Accelerometer X axis upper bits */ #define LSM6DSO_REG_ACCEL_Y_AXIS_L 0x2A /* Accelerometer Y axis lower bits */ @@ -44,14 +44,20 @@ #define LSM6DSO_REG_ACCEL_Z_AXIS_L 0x2C /* Accelerometer Z axis lower bits */ #define LSM6DSO_REG_ACCEL_Z_AXIS_H 0x2D /* Accelerometer Z axis upper bits */ +/* Function Pointers*/ +typedef int (*I2C_Read)(uint8_t *data, uint8_t reg, uint8_t length); +typedef int (*I2C_Write)(uint8_t *data, uint8_t reg, uint8_t length); + /** * @brief Enumeration of axes of data available from the LSM6DSO IMU * */ enum lsm6dso_axes { - LSM6DSO_X_AXIS = 0, - LSM6DSO_Y_AXIS = 1, - LSM6DSO_Z_AXIS = 2 + + LSM6DSO_X_AXIS = 0, + LSM6DSO_Y_AXIS = 1, + LSM6DSO_Z_AXIS = 2 + }; /** @@ -59,27 +65,27 @@ enum lsm6dso_axes { * */ typedef struct { - I2C_HandleTypeDef *i2c_handle; + uint8_t accel_config; // TODO: We should make these cfg packed unions with + // bitfield structs - uint8_t accel_config; // TODO: We should make these cfg packed unions with - // bitfield structs + uint8_t gyro_config; - uint8_t gyro_config; + int16_t accel_data[3]; - int16_t accel_data[3]; + int16_t gyro_data[3]; - int16_t gyro_data[3]; + I2C_Read read_reg; + + I2C_Write write_reg; } lsm6dso_t; /** * @brief Initializes the LSM6DSO IMU * - * @param imu - * @param i2c_handle - * @return HAL_StatusTypeDef + * @return 0 if OK, other if ERROR */ -HAL_StatusTypeDef lsm6dso_init(lsm6dso_t *imu, I2C_HandleTypeDef *i2c_handle); +int lsm6dso_init(lsm6dso_t *imu, I2C_Read read_func, I2C_Write write_func); /* IMU Setting Configuration */ /** @@ -89,38 +95,35 @@ HAL_StatusTypeDef lsm6dso_init(lsm6dso_t *imu, I2C_HandleTypeDef *i2c_handle); * @param odr_sel * @param fs_sel * @param lp_f2_enable - * @return HAL_StatusTypeDef + * @return 0 if OK, other if ERROR */ -HAL_StatusTypeDef lsm6dso_set_accel_cfg(lsm6dso_t *imu, int8_t odr_sel, - int8_t fs_sel, int8_t lp_f2_enable); + +int lsm6dso_set_accel_cfg(lsm6dso_t *imu, int8_t odr_sel, int8_t fs_sel, + int8_t lp_f2_enable); /** * @brief Configures the accelerometer of the LSM6DSO IMU * - * @param imu * @param odr_sel * @param fs_sel * @param fs_125 - * @return HAL_StatusTypeDef + * @return 0 if OK, other if ERROR */ -HAL_StatusTypeDef lsm6dso_set_gyro_cfg(lsm6dso_t *imu, int8_t odr_sel, - int8_t fs_sel, int8_t fs_125); + +int lsm6dso_set_gyro_cfg(lsm6dso_t *imu, int8_t odr_sel, int8_t fs_sel, + int8_t fs_125); /* Data Aquisition */ /** * @brief Retrieves accelerometer data from the LSM6DSO IMU - * - * @param imu - * @return HAL_StatusTypeDef + * @return 0 if OK, other if ERROR */ -HAL_StatusTypeDef lsm6dso_read_accel(lsm6dso_t *imu); +int lsm6dso_read_accel(lsm6dso_t *imu); /** * @brief Retreives the gyroscope data from the LSM6DSO IMU - * - * @param imu - * @return HAL_StatusTypeDef + * @return 0 if OK, other if ERROR */ -HAL_StatusTypeDef lsm6dso_read_gyro(lsm6dso_t *imu); +int lsm6dso_read_gyro(lsm6dso_t *imu); #endif // LSM6DSO_H diff --git a/general/include/ltc68041.h b/general/include/ltc68041.h index c64265a..d764df7 100644 --- a/general/include/ltc68041.h +++ b/general/include/ltc68041.h @@ -53,12 +53,12 @@ Copyright 2013 Linear Technology Corp. (LTC) #include "stm32xx_hal.h" #define LTC_MAX_RETRIES 10 -#define LTC_BAD_READ 0xFEEEEEEE +#define LTC_BAD_READ 0xFEEEEEEE typedef struct { - SPI_HandleTypeDef *spi; - GPIO_TypeDef *gpio; - uint8_t cs_pin; + SPI_HandleTypeDef *spi; + GPIO_TypeDef *gpio; + uint8_t cs_pin; } ltc_config; @@ -95,36 +95,37 @@ check for MSB */ static const unsigned int crc15Table[256] = { - 0x0, 0xc599, 0xceab, 0xb32, 0xd8cf, 0x1d56, 0x1664, 0xd3fd, 0xf407, - 0x319e, 0x3aac, //!< precomputed CRC15 Table - 0xff35, 0x2cc8, 0xe951, 0xe263, 0x27fa, 0xad97, 0x680e, 0x633c, 0xa6a5, - 0x7558, 0xb0c1, 0xbbf3, 0x7e6a, 0x5990, 0x9c09, 0x973b, 0x52a2, 0x815f, - 0x44c6, 0x4ff4, 0x8a6d, 0x5b2e, 0x9eb7, 0x9585, 0x501c, 0x83e1, 0x4678, - 0x4d4a, 0x88d3, 0xaf29, 0x6ab0, 0x6182, 0xa41b, 0x77e6, 0xb27f, 0xb94d, - 0x7cd4, 0xf6b9, 0x3320, 0x3812, 0xfd8b, 0x2e76, 0xebef, 0xe0dd, 0x2544, - 0x2be, 0xc727, 0xcc15, 0x98c, 0xda71, 0x1fe8, 0x14da, 0xd143, 0xf3c5, - 0x365c, 0x3d6e, 0xf8f7, 0x2b0a, 0xee93, 0xe5a1, 0x2038, 0x7c2, 0xc25b, - 0xc969, 0xcf0, 0xdf0d, 0x1a94, 0x11a6, 0xd43f, 0x5e52, 0x9bcb, 0x90f9, - 0x5560, 0x869d, 0x4304, 0x4836, 0x8daf, 0xaa55, 0x6fcc, 0x64fe, 0xa167, - 0x729a, 0xb703, 0xbc31, 0x79a8, 0xa8eb, 0x6d72, 0x6640, 0xa3d9, 0x7024, - 0xb5bd, 0xbe8f, 0x7b16, 0x5cec, 0x9975, 0x9247, 0x57de, 0x8423, 0x41ba, - 0x4a88, 0x8f11, 0x57c, 0xc0e5, 0xcbd7, 0xe4e, 0xddb3, 0x182a, 0x1318, - 0xd681, 0xf17b, 0x34e2, 0x3fd0, 0xfa49, 0x29b4, 0xec2d, 0xe71f, 0x2286, - 0xa213, 0x678a, 0x6cb8, 0xa921, 0x7adc, 0xbf45, 0xb477, 0x71ee, 0x5614, - 0x938d, 0x98bf, 0x5d26, 0x8edb, 0x4b42, 0x4070, 0x85e9, 0xf84, 0xca1d, - 0xc12f, 0x4b6, 0xd74b, 0x12d2, 0x19e0, 0xdc79, 0xfb83, 0x3e1a, 0x3528, - 0xf0b1, 0x234c, 0xe6d5, 0xede7, 0x287e, 0xf93d, 0x3ca4, 0x3796, 0xf20f, - 0x21f2, 0xe46b, 0xef59, 0x2ac0, 0xd3a, 0xc8a3, 0xc391, 0x608, 0xd5f5, - 0x106c, 0x1b5e, 0xdec7, 0x54aa, 0x9133, 0x9a01, 0x5f98, 0x8c65, 0x49fc, - 0x42ce, 0x8757, 0xa0ad, 0x6534, 0x6e06, 0xab9f, 0x7862, 0xbdfb, 0xb6c9, - 0x7350, 0x51d6, 0x944f, 0x9f7d, 0x5ae4, 0x8919, 0x4c80, 0x47b2, 0x822b, - 0xa5d1, 0x6048, 0x6b7a, 0xaee3, 0x7d1e, 0xb887, 0xb3b5, 0x762c, 0xfc41, - 0x39d8, 0x32ea, 0xf773, 0x248e, 0xe117, 0xea25, 0x2fbc, 0x846, 0xcddf, - 0xc6ed, 0x374, 0xd089, 0x1510, 0x1e22, 0xdbbb, 0xaf8, 0xcf61, 0xc453, - 0x1ca, 0xd237, 0x17ae, 0x1c9c, 0xd905, 0xfeff, 0x3b66, 0x3054, 0xf5cd, - 0x2630, 0xe3a9, 0xe89b, 0x2d02, 0xa76f, 0x62f6, 0x69c4, 0xac5d, 0x7fa0, - 0xba39, 0xb10b, 0x7492, 0x5368, 0x96f1, 0x9dc3, 0x585a, 0x8ba7, 0x4e3e, - 0x450c, 0x8095}; + 0x0, 0xc599, 0xceab, 0xb32, 0xd8cf, 0x1d56, 0x1664, 0xd3fd, 0xf407, + 0x319e, 0x3aac, //!< precomputed CRC15 Table + 0xff35, 0x2cc8, 0xe951, 0xe263, 0x27fa, 0xad97, 0x680e, 0x633c, 0xa6a5, + 0x7558, 0xb0c1, 0xbbf3, 0x7e6a, 0x5990, 0x9c09, 0x973b, 0x52a2, 0x815f, + 0x44c6, 0x4ff4, 0x8a6d, 0x5b2e, 0x9eb7, 0x9585, 0x501c, 0x83e1, 0x4678, + 0x4d4a, 0x88d3, 0xaf29, 0x6ab0, 0x6182, 0xa41b, 0x77e6, 0xb27f, 0xb94d, + 0x7cd4, 0xf6b9, 0x3320, 0x3812, 0xfd8b, 0x2e76, 0xebef, 0xe0dd, 0x2544, + 0x2be, 0xc727, 0xcc15, 0x98c, 0xda71, 0x1fe8, 0x14da, 0xd143, 0xf3c5, + 0x365c, 0x3d6e, 0xf8f7, 0x2b0a, 0xee93, 0xe5a1, 0x2038, 0x7c2, 0xc25b, + 0xc969, 0xcf0, 0xdf0d, 0x1a94, 0x11a6, 0xd43f, 0x5e52, 0x9bcb, 0x90f9, + 0x5560, 0x869d, 0x4304, 0x4836, 0x8daf, 0xaa55, 0x6fcc, 0x64fe, 0xa167, + 0x729a, 0xb703, 0xbc31, 0x79a8, 0xa8eb, 0x6d72, 0x6640, 0xa3d9, 0x7024, + 0xb5bd, 0xbe8f, 0x7b16, 0x5cec, 0x9975, 0x9247, 0x57de, 0x8423, 0x41ba, + 0x4a88, 0x8f11, 0x57c, 0xc0e5, 0xcbd7, 0xe4e, 0xddb3, 0x182a, 0x1318, + 0xd681, 0xf17b, 0x34e2, 0x3fd0, 0xfa49, 0x29b4, 0xec2d, 0xe71f, 0x2286, + 0xa213, 0x678a, 0x6cb8, 0xa921, 0x7adc, 0xbf45, 0xb477, 0x71ee, 0x5614, + 0x938d, 0x98bf, 0x5d26, 0x8edb, 0x4b42, 0x4070, 0x85e9, 0xf84, 0xca1d, + 0xc12f, 0x4b6, 0xd74b, 0x12d2, 0x19e0, 0xdc79, 0xfb83, 0x3e1a, 0x3528, + 0xf0b1, 0x234c, 0xe6d5, 0xede7, 0x287e, 0xf93d, 0x3ca4, 0x3796, 0xf20f, + 0x21f2, 0xe46b, 0xef59, 0x2ac0, 0xd3a, 0xc8a3, 0xc391, 0x608, 0xd5f5, + 0x106c, 0x1b5e, 0xdec7, 0x54aa, 0x9133, 0x9a01, 0x5f98, 0x8c65, 0x49fc, + 0x42ce, 0x8757, 0xa0ad, 0x6534, 0x6e06, 0xab9f, 0x7862, 0xbdfb, 0xb6c9, + 0x7350, 0x51d6, 0x944f, 0x9f7d, 0x5ae4, 0x8919, 0x4c80, 0x47b2, 0x822b, + 0xa5d1, 0x6048, 0x6b7a, 0xaee3, 0x7d1e, 0xb887, 0xb3b5, 0x762c, 0xfc41, + 0x39d8, 0x32ea, 0xf773, 0x248e, 0xe117, 0xea25, 0x2fbc, 0x846, 0xcddf, + 0xc6ed, 0x374, 0xd089, 0x1510, 0x1e22, 0xdbbb, 0xaf8, 0xcf61, 0xc453, + 0x1ca, 0xd237, 0x17ae, 0x1c9c, 0xd905, 0xfeff, 0x3b66, 0x3054, 0xf5cd, + 0x2630, 0xe3a9, 0xe89b, 0x2d02, 0xa76f, 0x62f6, 0x69c4, 0xac5d, 0x7fa0, + 0xba39, 0xb10b, 0x7492, 0x5368, 0x96f1, 0x9dc3, 0x585a, 0x8ba7, 0x4e3e, + 0x450c, 0x8095 +}; /*! @@ -134,8 +135,8 @@ static const unsigned int crc15Table[256] = { |10| 2 | Normal | |11| 3 | Filtered | */ -#define MD_FAST 1 -#define MD_NORMAL 2 +#define MD_FAST 1 +#define MD_NORMAL 2 #define MD_FILTERED 3 /*! @@ -150,10 +151,10 @@ static const unsigned int crc15Table[256] = { |110| 6 | Cell 6 and Cell 12 | */ -#define CELL_CH_ALL 0 -#define CELL_CH_1and7 1 -#define CELL_CH_2and8 2 -#define CELL_CH_3and9 3 +#define CELL_CH_ALL 0 +#define CELL_CH_1and7 1 +#define CELL_CH_2and8 2 +#define CELL_CH_3and9 3 #define CELL_CH_4and10 4 #define CELL_CH_5and11 5 #define CELL_CH_6and12 6 @@ -171,7 +172,7 @@ static const unsigned int crc15Table[256] = { |110 | 6 | Vref2 | */ -#define AUX_CH_ALL 0 +#define AUX_CH_ALL 0 #define AUX_CH_GPIO1 1 #define AUX_CH_GPIO2 2 #define AUX_CH_GPIO3 3 @@ -191,10 +192,10 @@ static const unsigned int crc15Table[256] = { ********************************************************/ #define DCP_DISABLED 0 -#define DCP_ENABLED 1 +#define DCP_ENABLED 1 void LTC6804_initialize(ltc_config *conf, SPI_HandleTypeDef *hspi, - GPIO_TypeDef *hgpio, uint8_t cs_pin); + GPIO_TypeDef *hgpio, uint8_t cs_pin); void set_adc(uint8_t MD, uint8_t DCP, uint8_t CH, uint8_t CHG); @@ -203,10 +204,10 @@ void LTC6804_adcv(ltc_config *config); void LTC6804_adax(ltc_config *config); uint8_t LTC6804_rdcv(ltc_config *config, uint8_t reg, uint8_t total_ic, - uint16_t cell_codes[][12]); + uint16_t cell_codes[][12]); int8_t LTC6804_rdaux(ltc_config *config, uint8_t reg, uint8_t nIC, - uint16_t aux_codes[][6]); + uint16_t aux_codes[][6]); void LTC6804_clraux(ltc_config *config); @@ -215,7 +216,7 @@ void LTC6804_wrcfg(ltc_config *config, uint8_t nIC, uint8_t data_config[][6]); int8_t LTC6804_rdcfg(ltc_config *config, uint8_t nIC, uint8_t r_config[][8]); void LTC6804_wrcomm(ltc_config *config, uint8_t total_ic, - uint8_t writeData[][6]); + uint8_t writeData[][6]); void LTC6804_stcomm(ltc_config *config, uint8_t len); diff --git a/general/include/m24c32.h b/general/include/m24c32.h index 7cecb5c..173f376 100644 --- a/general/include/m24c32.h +++ b/general/include/m24c32.h @@ -5,16 +5,16 @@ #include #include -#define M24C32_I2C_ADDR 0x50 +#define M24C32_I2C_ADDR 0x50 #define M24C32_PAGE_SIZE 32 extern I2C_HandleTypeDef *i2c_handle; HAL_StatusTypeDef eeprom_write(uint16_t mem_address, uint8_t *data, - uint16_t size); + uint16_t size); HAL_StatusTypeDef eeprom_read(uint16_t mem_address, uint8_t *data, - uint16_t size); + uint16_t size); HAL_StatusTypeDef eeprom_delete(uint16_t mem_address, uint16_t size); diff --git a/general/include/max7314.h b/general/include/max7314.h index 37a1101..18585e3 100644 --- a/general/include/max7314.h +++ b/general/include/max7314.h @@ -7,16 +7,15 @@ #include typedef enum { - MAX7314_PINS_0_TO_7 = 0, - MAX7314_PINS_8_TO_15 = 1 + MAX7314_PINS_0_TO_7 = 0, + MAX7314_PINS_8_TO_15 = 1 } max7314_pin_regs_t; typedef struct { + I2C_HandleTypeDef *i2c_handle; - I2C_HandleTypeDef *i2c_handle; - - /* i2c device address */ - uint16_t dev_addr; + /* i2c device address */ + uint16_t dev_addr; } max7314_t; @@ -37,7 +36,7 @@ HAL_StatusTypeDef max7314_set_global_intensity(max7314_t *max, uint8_t level); * @brief Set pin to be an input or an output pin */ HAL_StatusTypeDef max7314_set_pin_mode(max7314_t *max, uint8_t pin, - uint8_t mode); + uint8_t mode); HAL_StatusTypeDef max7314_set_pin_modes(max7314_t *max, uint8_t *pin_configs); @@ -55,12 +54,12 @@ HAL_StatusTypeDef max7314_read_pin(max7314_t *max, uint8_t pin, bool *state); * @brief Turn an output pin on or off */ HAL_StatusTypeDef max7314_set_pin_state(max7314_t *max, uint8_t pin, - bool state); + bool state); /** * @brief Read the state of an output pin */ HAL_StatusTypeDef max7314_read_pin_state(max7314_t *max, uint8_t pin, - bool *state); + bool *state); #endif // MAX7314_H diff --git a/general/include/mcp23008.h b/general/include/mcp23008.h index 5a95e2e..ec1110b 100644 --- a/general/include/mcp23008.h +++ b/general/include/mcp23008.h @@ -6,8 +6,8 @@ typedef int (*write_ptr)(uint8_t addr, const uint8_t *data, uint8_t len); typedef int (*read_ptr)(uint8_t addr, uint8_t *data, uint8_t len); typedef struct { - write_ptr write; - read_ptr read; + write_ptr write; + read_ptr read; } mcp23008_t; int mcp23008_init(mcp23008_t *obj, write_ptr write, read_ptr read); diff --git a/general/include/pca9539.h b/general/include/pca9539.h index 1c31343..72a392a 100644 --- a/general/include/pca9539.h +++ b/general/include/pca9539.h @@ -27,40 +27,40 @@ PCA 9539 16 bit GPIO expander. Datasheet: /// POLARITY: Inversion state, 1=Inverted 0=Uninverted /// DIRECTION: Input/Output selection 1=Input 0=Output -#define PCA_INPUT_0_REG 0x00 -#define PCA_INPUT_1_REG 0x01 -#define PCA_OUTPUT_0_REG 0x02 -#define PCA_OUTPUT_1_REG 0x03 -#define PCA_POLARITY_0_REG 0x04 -#define PCA_POLARITY_1_REG 0x05 +#define PCA_INPUT_0_REG 0x00 +#define PCA_INPUT_1_REG 0x01 +#define PCA_OUTPUT_0_REG 0x02 +#define PCA_OUTPUT_1_REG 0x03 +#define PCA_POLARITY_0_REG 0x04 +#define PCA_POLARITY_1_REG 0x05 #define PCA_DIRECTION_0_REG 0x06 #define PCA_DIRECTION_1_REG 0x07 typedef struct { - I2C_HandleTypeDef *i2c_handle; - uint16_t dev_addr; + I2C_HandleTypeDef *i2c_handle; + uint16_t dev_addr; } pca9539_t; /// Init PCA9539, a 16 bit I2C GPIO expander void pca9539_init(pca9539_t *pca, I2C_HandleTypeDef *i2c_handle, - uint8_t dev_addr); + uint8_t dev_addr); /// @brief Read all pins on a bus, for example using reg_type input to get /// incoming logic level HAL_StatusTypeDef pca9539_read_reg(pca9539_t *pca, uint8_t reg_type, - uint8_t *buf); + uint8_t *buf); /// @brief Read a specific pin on a bus, do not iterate over this, use read_pins /// instead HAL_StatusTypeDef pca9539_read_pin(pca9539_t *pca, uint8_t reg_type, - uint8_t pin, uint8_t *buf); + uint8_t pin, uint8_t *buf); /// @brief Write all pins on a bus, for example using reg_type OUTPUT to set /// logic level or DIRECTION to set as output HAL_StatusTypeDef pca9539_write_reg(pca9539_t *pca, uint8_t reg_type, - uint8_t buf); + uint8_t buf); /// @brief Write a specific pin on a bus, do not iterate over this, use /// write_pins instead HAL_StatusTypeDef pca9539_write_pin(pca9539_t *pca, uint8_t reg_type, - uint8_t pin, uint8_t buf); + uint8_t pin, uint8_t buf); #endif \ No newline at end of file diff --git a/general/include/pi4ioe.h b/general/include/pi4ioe.h index c3e515b..3043bdd 100644 --- a/general/include/pi4ioe.h +++ b/general/include/pi4ioe.h @@ -13,8 +13,8 @@ #include typedef struct { - I2C_HandleTypeDef *i2c_handle; - uint8_t port_config; + I2C_HandleTypeDef *i2c_handle; + uint8_t port_config; } pi4ioe_t; @@ -38,7 +38,7 @@ HAL_StatusTypeDef pi4ioe_init(pi4ioe_t *gpio, I2C_HandleTypeDef *hi2c); * @return HAL_StatusTypeDef */ HAL_StatusTypeDef pi4ioe_write(uint8_t device, uint8_t val, - I2C_HandleTypeDef *i2c_handle); + I2C_HandleTypeDef *i2c_handle); /** * @brief Reads from the PI4IOE5V9535ZDEX GPIO Expander diff --git a/general/include/sht30.h b/general/include/sht30.h index 89ca192..6bef273 100644 --- a/general/include/sht30.h +++ b/general/include/sht30.h @@ -10,19 +10,20 @@ * --Datasheet * */ -#define SHT30_I2C_ADDR 0x44 << 1u /* If ADDR (pin2) is connected to VDD, 0x45 \ +#define SHT30_I2C_ADDR \ + 0x44 << 1u /* If ADDR (pin2) is connected to VDD, 0x45 \ */ typedef enum { - SHT3X_COMMAND_MEASURE_HIGHREP_STRETCH = 0x2c06, - SHT3X_COMMAND_CLEAR_STATUS = 0x3041, - SHT3X_COMMAND_SOFT_RESET = 0x30A2, - SHT3X_COMMAND_HEATER_ENABLE = 0x306d, - SHT3X_COMMAND_HEATER_DISABLE = 0x3066, - SHT3X_COMMAND_READ_STATUS = 0xf32d, - SHT3X_COMMAND_FETCH_DATA = 0xe000, - SHT3X_COMMAND_MEASURE_HIGHREP_10HZ = 0x2737, - SHT3X_COMMAND_MEASURE_LOWREP_10HZ = 0x272a + SHT3X_COMMAND_MEASURE_HIGHREP_STRETCH = 0x2c06, + SHT3X_COMMAND_CLEAR_STATUS = 0x3041, + SHT3X_COMMAND_SOFT_RESET = 0x30A2, + SHT3X_COMMAND_HEATER_ENABLE = 0x306d, + SHT3X_COMMAND_HEATER_DISABLE = 0x3066, + SHT3X_COMMAND_READ_STATUS = 0xf32d, + SHT3X_COMMAND_FETCH_DATA = 0xe000, + SHT3X_COMMAND_MEASURE_HIGHREP_10HZ = 0x2737, + SHT3X_COMMAND_MEASURE_LOWREP_10HZ = 0x272a } sht3x_command_t; /* @@ -37,11 +38,11 @@ typedef enum { #define SHT30_START_CMD_NCS 0x2400 typedef struct { - I2C_HandleTypeDef *i2c_handle; - uint16_t status_reg; - uint16_t temp; - uint16_t humidity; - bool is_heater_enabled; + I2C_HandleTypeDef *i2c_handle; + uint16_t status_reg; + uint16_t temp; + uint16_t humidity; + bool is_heater_enabled; } sht30_t; /** @@ -69,4 +70,4 @@ HAL_StatusTypeDef sht30_toggle_heater(sht30_t *sht30, bool enable); */ HAL_StatusTypeDef sht30_get_temp_humid(sht30_t *sht30); -#endif \ No newline at end of file +#endif diff --git a/general/src/LTC4015.c b/general/src/LTC4015.c index 45c9a09..09920e1 100644 --- a/general/src/LTC4015.c +++ b/general/src/LTC4015.c @@ -8,59 +8,62 @@ #include "LTC4015.h" -HAL_StatusTypeDef LTC4015_Init(LTC4015_T *dev, I2C_HandleTypeDef *i2cHandle) { - dev->i2cHandle = i2cHandle; +int LTC4015_Init(LTC4015_T *dev, Read_Ptr read, Write_Ptr write) +{ + dev->read = read; + dev->write = write; - // Gets the value from the Charging state register - LtC4015_read(dev, LTC4015_CHGSTATE, dev->CHGdata); + //Gets the value from the Charging state register + LtC4015_read(dev, LTC4015_CHGSTATE, &dev->chargeFaults); } -HAL_StatusTypeDef LTC4015_read(LTC4015_T *dev, uint16_t reg, uint16_t *data){ - return HAL_I2C_Mem_Read(dev -> i2c_handle, LTC4015_ADDR_68, reg, - I2C_MEMADD_SIZE_8BIT, data, 1, HAL_MAX_DELAY) - +int LTC4015_read(LTC4015_T *dev, uint16_t reg, uint16_t *data) +{ + return dev->read(LTC4015_ADDR_68, reg, 0x00000001U, data, 1); } -HAL_StatusTypeDef LTC4015_write(LTC4015_T *dev, uint16_t reg, uint16_t data){ - return HAL_I2C_Mem_Write(dev->i2c_handle, LTC4015_ADDR_68, reg, - I2C_MEMADD_SIZE_8BIT, data, 1, HAL_MAX_DELAY)} +int LTC4015_write(LTC4015_T *dev, uint16_t reg, uint16_t data) +{ + return dev->write(LTC4015_ADDR_68, reg, 0x00000001U, data, 1); +} -HAL_StatusTypeDef LTC4015_Qcounter(LTC4015_T *dev, uint16_t prescaler, - uint16_t highAlert, uint16_t lowAlert) { - // Increases integration time, at which QCOUNT is updated - LTC4015_write(dev, QCOUNT_PRESCALE_FACTOR, prescaler); +int LTC4015_Qcounter(LTC4015_T *dev, uint16_t prescaler, uint16_t highAlert, + uint16_t lowAlert) +{ + //Increases integration time, at which QCOUNT is updated + LTC4015_write(dev, QCOUNT_PRESCALE_FACTOR, prescaler); - // Sets the High amount for the QCOUNT before error is flagged - LTC4015_write(dev, QCOUNT_HI_ALERT_LIMIT, highAlert); - LTC4015_write(dev, EN_LIMIT_ALERTS, - 0x1000); // Enable bit is in 12th bit postion + //Sets the High amount for the QCOUNT before error is flagged + LTC4015_write(dev, QCOUNT_HI_ALERT_LIMIT, highAlert); + LTC4015_write(dev, EN_LIMIT_ALERTS, + 0x1000); //Enable bit is in 12th bit postion - // Sets the low amount for the QCOUNT before error is flagged - LTC4015_write(dev, QCOUNT_LO_ALERT_LIMIT, lowAlert); - LTC4015_write(dev, EN_LIMIT_ALERTS, - 0x2000); // Enable bit is in 13th bit postion + //Sets the low amount for the QCOUNT before error is flagged + LTC4015_write(dev, QCOUNT_LO_ALERT_LIMIT, lowAlert); + LTC4015_write(dev, EN_LIMIT_ALERTS, + 0x2000); //Enable bit is in 13th bit postion - LTC4015_write(dev, CONFIG_BITS, 0x0008); // enable QCOUNT, in bit postion 2 - LTC4015_read(dev, LIMIT_ALERTS, dev->limitAlerts); - LTC4015_read(dev, QCOUNT, dev->qcount); + LTC4015_write(dev, CONFIG_BITS, + 0x0008); //enable QCOUNT, in bit postion 2 + LTC4015_read(dev, LIMIT_ALERTS, dev->limitAlerts); + LTC4015_read(dev, QCOUNT, dev->qcount); - // This all could be put into a while loop if you want to continually check - // for errors - LTC4015_write( - dev, CONFIG_BITS, - (CONFIG_BITS ^ 0x1000)); // should re-enable charging if was disabled - // Sees if the alerts are being flagged, and then will return the QCOUNT - if (LIMIT_ALERTS | 0x1000 == 0x1000) { - LTC4015_write( - dev, EN_LIMIT_ALERTS, - (EN_LIMIT_ALERTS ^ - 0x1000)); // Should just reset the enable but touch nothing else - LTC4015_write(dev, CONFIG_BITS, 0x1000); // suspends charger - return (QCOUNT, highAlert) // Need away to tell its being flagged, but not - // really sure what to return - } else if (LIMIT_ALERTS | 0x2000 == 0x2000) { - LTC4015_write(dev, EN_LIMIT_ALERTS, EN_LIMIT_ALERTS ^ 0x2000); - LTC4015_write(dev, CONFIG_BITS, 0x1000); // suspends charger - return (QCOUNT, lowAlert) // sames issue as above - } + //This all could be put into a while loop if you want to continually check for errors + LTC4015_write(dev, CONFIG_BITS, + (CONFIG_BITS ^ + 0x1000)); //should re-enable charging if was disabled + //Sees if the alerts are being flagged, and then will return the QCOUNT + if (LIMIT_ALERTS | 0x1000 == 0x1000) { + LTC4015_write( + dev, EN_LIMIT_ALERTS, + (EN_LIMIT_ALERTS ^ + 0x1000)); //Should just reset the enable but touch nothing else + LTC4015_write(dev, CONFIG_BITS, 0x1000); //suspends charger + return (QCOUNT, + highAlert); //Need away to tell its being flagged, but not really sure what to return + } else if (LIMIT_ALERTS | 0x2000 == 0x2000) { + LTC4015_write(dev, EN_LIMIT_ALERTS, EN_LIMIT_ALERTS ^ 0x2000); + LTC4015_write(dev, CONFIG_BITS, 0x1000); //suspends charger + return (QCOUNT, lowAlert); //sames issue as above + } } \ No newline at end of file diff --git a/general/src/ads131m04.c b/general/src/ads131m04.c index 3dd6adf..693579e 100644 --- a/general/src/ads131m04.c +++ b/general/src/ads131m04.c @@ -3,12 +3,12 @@ #include #include -#define NULL_CMD 0x0 -#define RESET_CMD 0x11 +#define NULL_CMD 0x0 +#define RESET_CMD 0x11 #define STANDBY_CMD 0x22 -#define WAKEUP_CMD 0x33 -#define LOCK_CMD 0x555 -#define UNLOCK_CMD 0x655 +#define WAKEUP_CMD 0x33 +#define LOCK_CMD 0x555 +#define UNLOCK_CMD 0x655 /* Private Function Prototypes*/ /* Method to abstract writing to a register, will use SPI commands under the @@ -23,83 +23,89 @@ static void ads131m04_send_command(ads131_t *adc, uint16_t cmd); /* Method to initialize communication over SPI and configure the ADC into * Continuous Conversion Mode*/ void ads131m04_init(ads131_t *adc, SPI_HandleTypeDef *hspi, GPIO_TypeDef *hgpio, - uint8_t cs_pin) { - adc->spi = hspi; - adc->gpio = hgpio; - adc->cs_pin = cs_pin; + uint8_t cs_pin) +{ + adc->spi = hspi; + adc->gpio = hgpio; + adc->cs_pin = cs_pin; - HAL_GPIO_WritePin(adc->gpio, adc->cs_pin, GPIO_PIN_SET); + HAL_GPIO_WritePin(adc->gpio, adc->cs_pin, GPIO_PIN_SET); - // Channel 0 has Gain default set to level 1, which is what we want for this - // application We can try out different configurations later if we need to, - // but it seems like the defaults work + // Channel 0 has Gain default set to level 1, which is what we want for this + // application We can try out different configurations later if we need to, + // but it seems like the defaults work } /* Method to abstract writing to a register, will use SPI commands under the * hood, value is MSB aligned */ -static void ads131m04_write_reg(ads131_t *adc, uint8_t reg, uint16_t value) { - // Ensure register address is within 6-bit range - reg &= 0x3F; - - // Set the number of registers we're writing to to 1 for now - uint8_t num_registers = 1; - - // Construct SPI word - uint16_t spi_word = 0; - spi_word |= (0x3000); // 011 in bits 13-15 - spi_word |= (reg << 7); // Register address (bits 7-12) - spi_word |= (num_registers - 1); // Number of registers (bits 0-6) - - // Send command to write to the specified register immediately followed by - // sending the value we want to write to that register - HAL_GPIO_WritePin(adc->gpio, adc->cs_pin, GPIO_PIN_RESET); - HAL_SPI_Transmit(adc->spi, &spi_word, 1, HAL_MAX_DELAY); - HAL_SPI_Transmit(adc->spi, &value, 1, HAL_MAX_DELAY); - HAL_GPIO_WritePin(adc->gpio, adc->cs_pin, GPIO_PIN_SET); +static void ads131m04_write_reg(ads131_t *adc, uint8_t reg, uint16_t value) +{ + // Ensure register address is within 6-bit range + reg &= 0x3F; + + // Set the number of registers we're writing to to 1 for now + uint8_t num_registers = 1; + + // Construct SPI word + uint16_t spi_word = 0; + spi_word |= (0x3000); // 011 in bits 13-15 + spi_word |= (reg << 7); // Register address (bits 7-12) + spi_word |= (num_registers - 1); // Number of registers (bits 0-6) + + // Send command to write to the specified register immediately followed by + // sending the value we want to write to that register + HAL_GPIO_WritePin(adc->gpio, adc->cs_pin, GPIO_PIN_RESET); + HAL_SPI_Transmit(adc->spi, &spi_word, 1, HAL_MAX_DELAY); + HAL_SPI_Transmit(adc->spi, &value, 1, HAL_MAX_DELAY); + HAL_GPIO_WritePin(adc->gpio, adc->cs_pin, GPIO_PIN_SET); } /* Method to abstract reading from a register, will use SPI commands under the * hood to do */ -static uint16_t ads131m04_read_reg(ads131_t *adc, uint8_t reg) { - // Ensure register address is within 6-bit range - reg &= 0x3F; - // Read one register at a time for now - uint8_t num_registers = 0; +static uint16_t ads131m04_read_reg(ads131_t *adc, uint8_t reg) +{ + // Ensure register address is within 6-bit range + reg &= 0x3F; + // Read one register at a time for now + uint8_t num_registers = 0; - // Construct SPI word - uint16_t spi_word = 0; - spi_word |= (0x5000); // 101 in bits 13-15 - spi_word |= (reg << 7); // Register address (bits 7-12) - spi_word |= (num_registers - 1); // Number of registers (bits 0-6) + // Construct SPI word + uint16_t spi_word = 0; + spi_word |= (0x5000); // 101 in bits 13-15 + spi_word |= (reg << 7); // Register address (bits 7-12) + spi_word |= (num_registers - 1); // Number of registers (bits 0-6) - HAL_GPIO_WritePin(adc->gpio, adc->cs_pin, GPIO_PIN_RESET); - HAL_SPI_Transmit(adc->spi, &spi_word, 1, HAL_MAX_DELAY); - HAL_GPIO_WritePin(adc->gpio, adc->cs_pin, GPIO_PIN_SET); + HAL_GPIO_WritePin(adc->gpio, adc->cs_pin, GPIO_PIN_RESET); + HAL_SPI_Transmit(adc->spi, &spi_word, 1, HAL_MAX_DELAY); + HAL_GPIO_WritePin(adc->gpio, adc->cs_pin, GPIO_PIN_SET); - uint16_t res = 0; + uint16_t res = 0; - if (HAL_SPI_Receive(adc->spi, (uint16_t *)&res, 1, 10) != HAL_OK) - return 1; + if (HAL_SPI_Receive(adc->spi, (uint16_t *)&res, 1, 10) != HAL_OK) + return 1; - return res; + return res; } /* Method to read values out of the ADC, should be called immediately after the * DRDY interrupt is triggered */ -HAL_StatusTypeDef ads131m04_read_adc(ads131_t *adc, uint32_t *adc_values) { - HAL_StatusTypeDef ret; - uint8_t data[6 * 3]; // Array to store SPI data (6 words * 3 bytes per word) - - // Read SPI data - HAL_GPIO_WritePin(adc->gpio, adc->cs_pin, GPIO_PIN_RESET); - ret = HAL_SPI_Receive(adc->spi, data, 6 * 3, HAL_MAX_DELAY); - HAL_GPIO_WritePin(adc->gpio, adc->cs_pin, GPIO_PIN_SET); - - // Process received data into ADC values - for (int i = 0; i < 4; i++) { - adc_values[i] = (data[(i + 1) * 3] << 16) | (data[(i + 1) * 3 + 1] << 8) | - data[(i + 1) * 3 + 2]; - } - - return ret; +HAL_StatusTypeDef ads131m04_read_adc(ads131_t *adc, uint32_t *adc_values) +{ + HAL_StatusTypeDef ret; + uint8_t data[6 * + 3]; // Array to store SPI data (6 words * 3 bytes per word) + + // Read SPI data + HAL_GPIO_WritePin(adc->gpio, adc->cs_pin, GPIO_PIN_RESET); + ret = HAL_SPI_Receive(adc->spi, data, 6 * 3, HAL_MAX_DELAY); + HAL_GPIO_WritePin(adc->gpio, adc->cs_pin, GPIO_PIN_SET); + + // Process received data into ADC values + for (int i = 0; i < 4; i++) { + adc_values[i] = (data[(i + 1) * 3] << 16) | + (data[(i + 1) * 3 + 1] << 8) | + data[(i + 1) * 3 + 2]; + } + + return ret; } diff --git a/general/src/lsm6dso.c b/general/src/lsm6dso.c index 178a6dd..7a75283 100644 --- a/general/src/lsm6dso.c +++ b/general/src/lsm6dso.c @@ -9,171 +9,185 @@ #include "lsm6dso.h" #define REG_RESOLUTION 32768 /* Half the range of a 16 bit signed integer */ -#define ACCEL_RANGE \ - 4 /* The range of values in g's returned from accelerometer */ + +#define ACCEL_RANGE \ + 4 /* The range of values in g's returned from accelerometer */ #define GYRO_RANGE 1000 /* The range of values from the gyro in dps */ -static inline HAL_StatusTypeDef lsm6dso_read_reg(lsm6dso_t *imu, uint8_t *data, - uint8_t reg) { - return HAL_I2C_Mem_Read(imu->i2c_handle, LSM6DSO_I2C_ADDRESS, reg, - I2C_MEMADD_SIZE_8BIT, data, 1, HAL_MAX_DELAY); +static inline int lsm6dso_read_reg(lsm6dso_t *imu, uint8_t *data, uint8_t reg) +{ + return imu->read_reg(data, reg, 1); +} + +static inline int lsm6dso_read_mult_reg(lsm6dso_t *imu, uint8_t *data, + uint8_t reg, uint8_t length) +{ + return imu->read_reg(data, reg, length); } -static inline HAL_StatusTypeDef lsm6dso_read_mult_reg(lsm6dso_t *imu, - uint8_t *data, - uint8_t reg, - uint8_t length) { - return HAL_I2C_Mem_Read(imu->i2c_handle, LSM6DSO_I2C_ADDRESS, reg, - I2C_MEMADD_SIZE_8BIT, data, length, HAL_MAX_DELAY); +static inline int lsm6dso_write_reg(lsm6dso_t *imu, uint8_t *data, uint8_t reg) +{ + return imu->write_reg(data, reg, 1); } -static inline HAL_StatusTypeDef lsm6dso_write_reg(lsm6dso_t *imu, uint8_t reg, - uint8_t *data) { - return HAL_I2C_Mem_Write(imu->i2c_handle, LSM6DSO_I2C_ADDRESS, reg, - I2C_MEMADD_SIZE_8BIT, data, 1, HAL_MAX_DELAY); +static inline int lsm6dso_write_mult_reg(lsm6dso_t *imu, uint8_t *data, + uint8_t reg, uint8_t length) +{ + return imu->write_reg(data, reg, length); } -static int16_t accel_data_convert(int16_t raw_accel) { - int8_t msb, lsb; - int16_t val; - msb = (raw_accel & 0x00FF) << 8; - lsb = (raw_accel & 0xFF00) >> 8; - val = msb | lsb; +static int16_t accel_data_convert(int16_t raw_accel) +{ + int8_t msb, lsb; + int16_t val; + msb = (raw_accel & 0x00FF) << 8; + lsb = (raw_accel & 0xFF00) >> 8; + val = msb | lsb; - return (int16_t)(((int32_t)val * ACCEL_RANGE * 1000) / REG_RESOLUTION); + return (int16_t)(((int32_t)val * ACCEL_RANGE * 1000) / REG_RESOLUTION); } -static int16_t gyro_data_convert(int16_t gyro_accel) { - int8_t msb, lsb; - int16_t val; - msb = (gyro_accel & 0x00FF) << 8; - lsb = (gyro_accel & 0xFF00) >> 8; - val = msb | lsb; - return (int16_t)(((int32_t)val * GYRO_RANGE * 100) / REG_RESOLUTION); +static int16_t gyro_data_convert(int16_t gyro_accel) +{ + int8_t msb, lsb; + int16_t val; + msb = (gyro_accel & 0x00FF) << 8; + lsb = (gyro_accel & 0xFF00) >> 8; + val = msb | lsb; + return (int16_t)(((int32_t)val * GYRO_RANGE * 100) / REG_RESOLUTION); } -static HAL_StatusTypeDef lsm6dso_ping_imu(lsm6dso_t *imu) { - uint8_t reg_data; - HAL_StatusTypeDef status; +static int lsm6dso_ping_imu(lsm6dso_t *imu) +{ + uint8_t reg_data; + int status; - status = lsm6dso_read_reg(imu, ®_data, LSM6DSO_REG_DEVICE_ID); - if (status != HAL_OK) - return status; + status = lsm6dso_read_reg(imu, ®_data, LSM6DSO_REG_DEVICE_ID); + if (status != 0) + return status; - if (reg_data != 0x6C) - return HAL_ERROR; + if (reg_data != 0x6C) + return -1; - return HAL_OK; + return 0; } -HAL_StatusTypeDef lsm6dso_set_accel_cfg(lsm6dso_t *imu, int8_t odr_sel, - int8_t fs_sel, int8_t lp_f2_enable) { - uint8_t config = - (((odr_sel << 4) | (fs_sel << 2) | (lp_f2_enable << 1)) << 1); - imu->accel_config = config; +int lsm6dso_set_accel_cfg(lsm6dso_t *imu, int8_t odr_sel, int8_t fs_sel, + int8_t lp_f2_enable) +{ + uint8_t config = + (((odr_sel << 4) | (fs_sel << 2) | (lp_f2_enable << 1)) << 1); + imu->accel_config = config; - return lsm6dso_write_reg(imu, LSM6DSO_REG_ACCEL_CTRL, &imu->accel_config); + return lsm6dso_write_reg(imu, &imu->accel_config, + LSM6DSO_REG_ACCEL_CTRL); } -HAL_StatusTypeDef lsm6dso_set_gyro_cfg(lsm6dso_t *imu, int8_t odr_sel, - int8_t fs_sel, int8_t fs_125) { - uint8_t config = (((odr_sel << 4) | (fs_sel << 2) | (fs_125 << 1)) << 1); - imu->gyro_config = config; +int lsm6dso_set_gyro_cfg(lsm6dso_t *imu, int8_t odr_sel, int8_t fs_sel, + int8_t fs_125) +{ + uint8_t config = + (((odr_sel << 4) | (fs_sel << 2) | (fs_125 << 1)) << 1); + imu->gyro_config = config; - return lsm6dso_write_reg(imu, LSM6DSO_REG_GYRO_CTRL, &imu->gyro_config); + return lsm6dso_write_reg(imu, &imu->gyro_config, LSM6DSO_REG_GYRO_CTRL); } -HAL_StatusTypeDef lsm6dso_init(lsm6dso_t *imu, I2C_HandleTypeDef *i2c_handle) { - HAL_StatusTypeDef status; +int lsm6dso_init(lsm6dso_t *imu, I2C_Read read_func, I2C_Write write_func) +{ + int status; - imu->i2c_handle = i2c_handle; + imu->accel_data[LSM6DSO_X_AXIS] = 0; + imu->accel_data[LSM6DSO_Y_AXIS] = 0; + imu->accel_data[LSM6DSO_Z_AXIS] = 0; - imu->accel_data[LSM6DSO_X_AXIS] = 0; - imu->accel_data[LSM6DSO_Y_AXIS] = 0; - imu->accel_data[LSM6DSO_Z_AXIS] = 0; + imu->gyro_data[LSM6DSO_X_AXIS] = 0; + imu->gyro_data[LSM6DSO_Y_AXIS] = 0; + imu->gyro_data[LSM6DSO_Z_AXIS] = 0; - imu->gyro_data[LSM6DSO_X_AXIS] = 0; - imu->gyro_data[LSM6DSO_Y_AXIS] = 0; - imu->gyro_data[LSM6DSO_Z_AXIS] = 0; + imu->read_reg = read_func; + imu->write_reg = write_func; - /* Quick check to make sure I2C is working */ - status = lsm6dso_ping_imu(imu); - if (status != HAL_OK) - return status; + /* Quick check to make sure I2C is working */ + status = lsm6dso_ping_imu(imu); + if (status != 0) + return status; - /* - Configure IMU to default params - Refer to datasheet pages 56-57 - */ - status = lsm6dso_set_accel_cfg(imu, 0x08, 0x02, 0x01); - if (status != HAL_OK) - return status; + /* + Configure IMU to default params + Refer to datasheet pages 56-57 + */ + status = lsm6dso_set_accel_cfg(imu, 0x08, 0x02, 0x01); + if (status != 0) + return status; - status = lsm6dso_set_gyro_cfg(imu, 0x08, 0x02, 0x00); - if (status != HAL_OK) - return status; + status = lsm6dso_set_gyro_cfg(imu, 0x08, 0x02, 0x00); + if (status != 0) + return status; - return HAL_OK; + return 0; } -HAL_StatusTypeDef lsm6dso_read_accel(lsm6dso_t *imu) { - union { - uint8_t buf[2]; - int16_t data; - } accel_x_raw, accel_y_raw, accel_z_raw; - HAL_StatusTypeDef status; - - /* Getting raw data from registers */ - status = lsm6dso_read_mult_reg(imu, accel_x_raw.buf, - LSM6DSO_REG_ACCEL_X_AXIS_L, 2); - if (status != HAL_OK) - return status; - - status = lsm6dso_read_mult_reg(imu, accel_y_raw.buf, - LSM6DSO_REG_ACCEL_Y_AXIS_L, 2); - if (status != HAL_OK) - return status; - - status = lsm6dso_read_mult_reg(imu, accel_z_raw.buf, - LSM6DSO_REG_ACCEL_Z_AXIS_L, 2); - if (status != HAL_OK) - return status; - - /* Setting imu struct values to converted measurements */ - imu->accel_data[LSM6DSO_X_AXIS] = accel_data_convert(accel_x_raw.data); - imu->accel_data[LSM6DSO_Y_AXIS] = accel_data_convert(accel_y_raw.data); - imu->accel_data[LSM6DSO_Z_AXIS] = accel_data_convert(accel_z_raw.data); - - return HAL_OK; +int lsm6dso_read_accel(lsm6dso_t *imu) +{ + union { + uint8_t buf[2]; + int16_t data; + } accel_x_raw, accel_y_raw, accel_z_raw; + int status; + + /* Getting raw data from registers */ + status = lsm6dso_read_mult_reg(imu, accel_x_raw.buf, + LSM6DSO_REG_ACCEL_X_AXIS_L, 2); + if (status != 0) + return status; + + status = lsm6dso_read_mult_reg(imu, accel_y_raw.buf, + LSM6DSO_REG_ACCEL_Y_AXIS_L, 2); + if (status != 0) + return status; + + status = lsm6dso_read_mult_reg(imu, accel_z_raw.buf, + LSM6DSO_REG_ACCEL_Z_AXIS_L, 2); + if (status != 0) + return status; + + /* Setting imu struct values to converted measurements */ + imu->accel_data[LSM6DSO_X_AXIS] = accel_data_convert(accel_x_raw.data); + imu->accel_data[LSM6DSO_Y_AXIS] = accel_data_convert(accel_y_raw.data); + imu->accel_data[LSM6DSO_Z_AXIS] = accel_data_convert(accel_z_raw.data); + + return 0; } -HAL_StatusTypeDef lsm6dso_read_gyro(lsm6dso_t *imu) { - union { - uint8_t buf[2]; - int16_t data; - } gyro_x_raw, gyro_y_raw, gyro_z_raw; - HAL_StatusTypeDef status; - - /* Aquire raw data from registers */ - status = - lsm6dso_read_mult_reg(imu, gyro_x_raw.buf, LSM6DSO_REG_GYRO_X_AXIS_L, 2); - if (status != HAL_OK) - return status; - - status = - lsm6dso_read_mult_reg(imu, gyro_y_raw.buf, LSM6DSO_REG_GYRO_Y_AXIS_L, 2); - if (status != HAL_OK) - return status; - - status = - lsm6dso_read_mult_reg(imu, gyro_z_raw.buf, LSM6DSO_REG_GYRO_Z_AXIS_L, 2); - if (status != HAL_OK) - return status; - - /* Setting imu struct values to converted measurements */ - imu->gyro_data[LSM6DSO_X_AXIS] = gyro_data_convert(gyro_x_raw.data); - imu->gyro_data[LSM6DSO_Y_AXIS] = gyro_data_convert(gyro_y_raw.data); - imu->gyro_data[LSM6DSO_Z_AXIS] = gyro_data_convert(gyro_z_raw.data); - - return HAL_OK; +int lsm6dso_read_gyro(lsm6dso_t *imu) +{ + union { + uint8_t buf[2]; + int16_t data; + } gyro_x_raw, gyro_y_raw, gyro_z_raw; + int status; + + /* Aquire raw data from registers */ + status = lsm6dso_read_mult_reg(imu, gyro_x_raw.buf, + LSM6DSO_REG_GYRO_X_AXIS_L, 2); + if (status != 0) + return status; + + status = lsm6dso_read_mult_reg(imu, gyro_y_raw.buf, + LSM6DSO_REG_GYRO_Y_AXIS_L, 2); + if (status != 0) + return status; + + status = lsm6dso_read_mult_reg(imu, gyro_z_raw.buf, + LSM6DSO_REG_GYRO_Z_AXIS_L, 2); + if (status != 0) + return status; + + /* Setting imu struct values to converted measurements */ + imu->gyro_data[LSM6DSO_X_AXIS] = gyro_data_convert(gyro_x_raw.data); + imu->gyro_data[LSM6DSO_Y_AXIS] = gyro_data_convert(gyro_y_raw.data); + imu->gyro_data[LSM6DSO_Z_AXIS] = gyro_data_convert(gyro_z_raw.data); + + return 0; } diff --git a/general/src/ltc68041.c b/general/src/ltc68041.c index e643c02..66eee4a 100644 --- a/general/src/ltc68041.c +++ b/general/src/ltc68041.c @@ -82,16 +82,16 @@ uint8_t ADAX[2]; //!< GPIO conversion command. /* private function prototypes */ void LTC6804_rdcv_reg(ltc_config *config, uint8_t reg, uint8_t total_ic, - uint8_t *data); + uint8_t *data); void wakeup_idle(ltc_config *config); void wakeup_sleep(ltc_config *config); uint16_t pec15_calc(uint8_t len, uint8_t *data); void write_68(ltc_config *config, uint8_t total_ic, uint8_t tx_cmd[2], - uint8_t data[]); + uint8_t data[]); void LTC6804_rdaux_reg(ltc_config *config, uint8_t reg, uint8_t total_ic, - uint8_t *data); + uint8_t *data); int8_t read_68(ltc_config *config, uint8_t total_ic, uint8_t tx_cmd[2], - uint8_t *rx_data); + uint8_t *rx_data); /*! \brief This function will initialize all 6804 variables and the SPI port. @@ -102,15 +102,16 @@ int8_t read_68(ltc_config *config, uint8_t total_ic, uint8_t tx_cmd[2], */ void LTC6804_initialize(ltc_config *conf, SPI_HandleTypeDef *hspi, - GPIO_TypeDef *hgpio, uint8_t cs_pin) { - conf->spi = hspi; - conf->gpio = hgpio; - conf->cs_pin = cs_pin; + GPIO_TypeDef *hgpio, uint8_t cs_pin) +{ + conf->spi = hspi; + conf->gpio = hgpio; + conf->cs_pin = cs_pin; - HAL_GPIO_WritePin(conf->gpio, conf->cs_pin, GPIO_PIN_SET); + HAL_GPIO_WritePin(conf->gpio, conf->cs_pin, GPIO_PIN_SET); - // TODO make sure shepherd app configures ADC with these settings: - set_adc(MD_FILTERED, DCP_DISABLED, CELL_CH_ALL, AUX_CH_ALL); + // TODO make sure shepherd app configures ADC with these settings: + set_adc(MD_FILTERED, DCP_DISABLED, CELL_CH_ALL, AUX_CH_ALL); } /*!******************************************************************************************************************* @@ -136,22 +137,23 @@ MD[2] | 1 | 1 | DCP | 0 | CH[2] | CH[1] | CH[0] | |ADAX: | 0 | 0 | 0 | 0 | 0 | 1 | 0 | MD[1] | MD[2] | 1 | 1 | DCP | 0 | CHG[2]| CHG[1]| CHG[0]| ******************************************************************************************************************/ -void set_adc(uint8_t MD, // ADC Mode - uint8_t DCP, // Discharge Permit - uint8_t CH, // Cell Channels to be measured - uint8_t CHG // GPIO Channels to be measured -) { - uint8_t md_bits; - - md_bits = (MD & 0x02) >> 1; - ADCV[0] = md_bits + 0x02; - md_bits = (MD & 0x01) << 7; - ADCV[1] = md_bits + 0x60 + (DCP << 4) + CH; - - md_bits = (MD & 0x02) >> 1; - ADAX[0] = md_bits + 0x04; - md_bits = (MD & 0x01) << 7; - ADAX[1] = md_bits + 0x60 + CHG; +void set_adc(uint8_t MD, // ADC Mode + uint8_t DCP, // Discharge Permit + uint8_t CH, // Cell Channels to be measured + uint8_t CHG // GPIO Channels to be measured +) +{ + uint8_t md_bits; + + md_bits = (MD & 0x02) >> 1; + ADCV[0] = md_bits + 0x02; + md_bits = (MD & 0x01) << 7; + ADCV[1] = md_bits + 0x60 + (DCP << 4) + CH; + + md_bits = (MD & 0x02) >> 1; + ADAX[0] = md_bits + 0x04; + md_bits = (MD & 0x01) << 7; + ADAX[1] = md_bits + 0x60 + CHG; } /*!********************************************************************************************* @@ -174,28 +176,29 @@ Command Code: |ADCV: | 0 | 0 | 0 | 0 | 0 | 0 | 1 | MD[1] | MD[2] | 1 | 1 | DCP | 0 | CH[2] | CH[1] | CH[0] | ***********************************************************************************************/ -void LTC6804_adcv(ltc_config *config) { - - uint8_t cmd[4]; - uint16_t cmd_pec; - - // 1 - cmd[0] = ADCV[0]; - cmd[1] = ADCV[1]; - - // 2 - cmd_pec = pec15_calc(2, ADCV); - cmd[2] = (uint8_t)(cmd_pec >> 8); - cmd[3] = (uint8_t)(cmd_pec); - - // 3 - wakeup_idle(config); // This will guarantee that the LTC6804 isoSPI port is - // awake. This command can be removed. - - // 4 - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); - HAL_SPI_Transmit(config->spi, cmd, 4, HAL_MAX_DELAY); - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); +void LTC6804_adcv(ltc_config *config) +{ + uint8_t cmd[4]; + uint16_t cmd_pec; + + // 1 + cmd[0] = ADCV[0]; + cmd[1] = ADCV[1]; + + // 2 + cmd_pec = pec15_calc(2, ADCV); + cmd[2] = (uint8_t)(cmd_pec >> 8); + cmd[3] = (uint8_t)(cmd_pec); + + // 3 + wakeup_idle( + config); // This will guarantee that the LTC6804 isoSPI port is + // awake. This command can be removed. + + // 4 + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); + HAL_SPI_Transmit(config->spi, cmd, 4, HAL_MAX_DELAY); + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); } /* LTC6804_adcv Function sequence: @@ -227,21 +230,23 @@ Command Code: |ADAX: | 0 | 0 | 0 | 0 | 0 | 1 | 0 | MD[1] | MD[2] | 1 | 1 | DCP | 0 | CHG[2]| CHG[1]| CHG[0]| *********************************************************************************************************/ -void LTC6804_adax(ltc_config *config) { - uint8_t cmd[4]; - uint16_t cmd_pec; - - cmd[0] = ADAX[0]; - cmd[1] = ADAX[1]; - cmd_pec = pec15_calc(2, ADAX); - cmd[2] = (uint8_t)(cmd_pec >> 8); - cmd[3] = (uint8_t)(cmd_pec); - - wakeup_idle(config); // This will guarantee that the LTC6804 isoSPI port is - // awake. This command can be removed. - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); - HAL_SPI_Transmit(config->spi, cmd, 4, HAL_MAX_DELAY); - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); +void LTC6804_adax(ltc_config *config) +{ + uint8_t cmd[4]; + uint16_t cmd_pec; + + cmd[0] = ADAX[0]; + cmd[1] = ADAX[1]; + cmd_pec = pec15_calc(2, ADAX); + cmd[2] = (uint8_t)(cmd_pec >> 8); + cmd[3] = (uint8_t)(cmd_pec); + + wakeup_idle( + config); // This will guarantee that the LTC6804 isoSPI port is + // awake. This command can be removed. + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); + HAL_SPI_Transmit(config->spi, cmd, 4, HAL_MAX_DELAY); + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); } /* LTC6804_adax Function sequence: @@ -295,127 +300,149 @@ void LTC6804_adax(ltc_config *config) { *************************************************/ uint8_t LTC6804_rdcv(ltc_config *config, - uint8_t reg, // Controls which cell voltage register is read back. - uint8_t total_ic, // the number of ICs in the system - uint16_t cell_codes[][12] // Array of the parsed cell codes -) { - - const uint8_t NUM_RX_BYT = 8; - const uint8_t BYT_IN_REG = 6; - const uint8_t CELL_IN_REG = 3; - - uint8_t *cell_data; - uint8_t pec_error = 0; - uint16_t parsed_cell; - uint16_t received_pec; - uint16_t data_pec; - uint8_t data_counter = 0; // data counter - cell_data = (uint8_t *)malloc((NUM_RX_BYT * total_ic) * sizeof(uint8_t)); - // 1.a - if (reg == 0) { - // a.i - for (uint8_t cell_reg = 1; cell_reg < 5; - cell_reg++) // executes once for each of the LTC6804 cell voltage - // registers - { - data_counter = 0; - LTC6804_rdcv_reg(config, cell_reg, total_ic, - cell_data); // Reads a single Cell voltage register - - for (uint8_t current_ic = 0; current_ic < total_ic; - current_ic++) // executes for every LTC6804 in the daisy chain - { - // current_ic is used as the IC counter - - // a.ii - for (uint8_t current_cell = 0; current_cell < CELL_IN_REG; - current_cell++) // This loop parses the read back data into cell - // voltages, it - { - // loops once for each of the 3 cell voltage codes in the register - - parsed_cell = - cell_data[data_counter] + (cell_data[data_counter + 1] - << 8); // Each cell code is received as - // two bytes and is combined to - // create the parsed cell voltage code - - cell_codes[current_ic][current_cell + - ((cell_reg - 1) * CELL_IN_REG)] = parsed_cell; - data_counter = - data_counter + - 2; // Because cell voltage codes are two bytes the data counter - // must increment by two for each parsed cell code - } - // a.iii - received_pec = - (cell_data[data_counter] << 8) + - cell_data[data_counter + 1]; // The received PEC for the current_ic - // is transmitted as the 7th and 8th - // after the 6 cell voltage data bytes - data_pec = pec15_calc(BYT_IN_REG, &cell_data[current_ic * NUM_RX_BYT]); - if (received_pec != data_pec) { - pec_error = -1; // The pec_error variable is simply set negative if - // any PEC errors - // are detected in the serial data - } - data_counter = data_counter + 2; // Because the transmitted PEC code is - // 2 bytes long the data_counter - // must be incremented by 2 bytes to point to the next ICs cell voltage - // data - } - } - } - // 1.b - else { - // b.i - LTC6804_rdcv_reg(config, reg, total_ic, cell_data); - for (uint8_t current_ic = 0; current_ic < total_ic; - current_ic++) // executes for every LTC6804 in the daisy chain - { - // current_ic is used as the IC counter - // b.ii - for (uint8_t current_cell = 0; current_cell < CELL_IN_REG; - current_cell++) // This loop parses the read back data into cell - // voltages, it - { - // loops once for each of the 3 cell voltage codes in the register - - parsed_cell = - cell_data[data_counter] + - (cell_data[data_counter + 1] << 8); // Each cell code is received as - // two bytes and is combined to - // create the parsed cell voltage code - - cell_codes[current_ic][current_cell + ((reg - 1) * CELL_IN_REG)] = - 0x0000FFFF & parsed_cell; - data_counter = - data_counter + - 2; // Because cell voltage codes are two bytes the data counter - // must increment by two for each parsed cell code - } - // b.iii - received_pec = - (cell_data[data_counter] << 8) + - cell_data[data_counter + 1]; // The received PEC for the current_ic is - // transmitted as the 7th and 8th - // after the 6 cell voltage data bytes - data_pec = pec15_calc(BYT_IN_REG, &cell_data[current_ic * NUM_RX_BYT]); - if (received_pec != data_pec) { - pec_error = -1; // The pec_error variable is simply set negative if any - // PEC errors - // are detected in the serial data - } - data_counter = data_counter + 2; // Because the transmitted PEC code is 2 - // bytes long the data_counter - // must be incremented by 2 bytes to point to the next ICs cell voltage - // data - } - } - - // 2 - free(cell_data); - return (pec_error); + uint8_t reg, // Controls which cell voltage register is read back. + uint8_t total_ic, // the number of ICs in the system + uint16_t cell_codes[][12] // Array of the parsed cell codes +) +{ + const uint8_t NUM_RX_BYT = 8; + const uint8_t BYT_IN_REG = 6; + const uint8_t CELL_IN_REG = 3; + + uint8_t *cell_data; + uint8_t pec_error = 0; + uint16_t parsed_cell; + uint16_t received_pec; + uint16_t data_pec; + uint8_t data_counter = 0; // data counter + cell_data = + (uint8_t *)malloc((NUM_RX_BYT * total_ic) * sizeof(uint8_t)); + // 1.a + if (reg == 0) { + // a.i + for (uint8_t cell_reg = 1; cell_reg < 5; + cell_reg++) // executes once for each of the LTC6804 cell voltage + // registers + { + data_counter = 0; + LTC6804_rdcv_reg( + config, cell_reg, total_ic, + cell_data); // Reads a single Cell voltage register + + for (uint8_t current_ic = 0; current_ic < total_ic; + current_ic++) // executes for every LTC6804 in the daisy chain + { + // current_ic is used as the IC counter + + // a.ii + for (uint8_t current_cell = 0; + current_cell < CELL_IN_REG; + current_cell++) // This loop parses the read back data into cell + // voltages, it + { + // loops once for each of the 3 cell voltage codes in the register + + parsed_cell = + cell_data[data_counter] + + (cell_data[data_counter + 1] + << 8); // Each cell code is received as + // two bytes and is combined to + // create the parsed cell voltage code + + cell_codes[current_ic][current_cell + + ((cell_reg - 1) * + CELL_IN_REG)] = + parsed_cell; + data_counter = + data_counter + + 2; // Because cell voltage codes are two bytes the data counter + // must increment by two for each parsed cell code + } + // a.iii + received_pec = + (cell_data[data_counter] << 8) + + cell_data[data_counter + + 1]; // The received PEC for the current_ic + // is transmitted as the 7th and 8th + // after the 6 cell voltage data bytes + data_pec = pec15_calc( + BYT_IN_REG, + &cell_data[current_ic * NUM_RX_BYT]); + if (received_pec != data_pec) { + pec_error = + -1; // The pec_error variable is simply set negative if + // any PEC errors + // are detected in the serial data + } + data_counter = + data_counter + + 2; // Because the transmitted PEC code is + // 2 bytes long the data_counter + // must be incremented by 2 bytes to point to the next ICs cell voltage + // data + } + } + } + // 1.b + else { + // b.i + LTC6804_rdcv_reg(config, reg, total_ic, cell_data); + for (uint8_t current_ic = 0; current_ic < total_ic; + current_ic++) // executes for every LTC6804 in the daisy chain + { + // current_ic is used as the IC counter + // b.ii + for (uint8_t current_cell = 0; + current_cell < CELL_IN_REG; + current_cell++) // This loop parses the read back data into cell + // voltages, it + { + // loops once for each of the 3 cell voltage codes in the register + + parsed_cell = + cell_data[data_counter] + + (cell_data[data_counter + 1] + << 8); // Each cell code is received as + // two bytes and is combined to + // create the parsed cell voltage code + + cell_codes[current_ic] + [current_cell + + ((reg - 1) * CELL_IN_REG)] = + 0x0000FFFF & parsed_cell; + data_counter = + data_counter + + 2; // Because cell voltage codes are two bytes the data counter + // must increment by two for each parsed cell code + } + // b.iii + received_pec = + (cell_data[data_counter] << 8) + + cell_data[data_counter + + 1]; // The received PEC for the current_ic is + // transmitted as the 7th and 8th + // after the 6 cell voltage data bytes + data_pec = + pec15_calc(BYT_IN_REG, + &cell_data[current_ic * NUM_RX_BYT]); + if (received_pec != data_pec) { + pec_error = + -1; // The pec_error variable is simply set negative if any + // PEC errors + // are detected in the serial data + } + data_counter = + data_counter + + 2; // Because the transmitted PEC code is 2 + // bytes long the data_counter + // must be incremented by 2 bytes to point to the next ICs cell voltage + // data + } + } + + // 2 + free(cell_data); + return (pec_error); } /* LTC6804_rdcv Sequence @@ -471,49 +498,51 @@ LTC6804_rdcv(ltc_config *config, *************************************************/ void LTC6804_rdcv_reg( - ltc_config *config, - uint8_t reg, // Determines which cell voltage register is read back - uint8_t total_ic, // the number of ICs in the - uint8_t *data // An array of the unparsed cell codes -) { - const uint8_t REG_LEN = - 8; // number of bytes in each ICs register + 2 bytes for the PEC - uint8_t cmd[4]; - uint16_t cmd_pec; - - // 1 - if (reg == 1) // 1: RDCVA - { - cmd[1] = 0x04; - cmd[0] = 0x00; - } else if (reg == 2) // 2: RDCVB - { - cmd[1] = 0x06; - cmd[0] = 0x00; - } else if (reg == 3) // 3: RDCVC - { - cmd[1] = 0x08; - cmd[0] = 0x00; - } else if (reg == 4) // 4: RDCVD - { - cmd[1] = 0x0A; - cmd[0] = 0x00; - } - - // 2 - cmd_pec = pec15_calc(2, cmd); - cmd[2] = (uint8_t)(cmd_pec >> 8); - cmd[3] = (uint8_t)(cmd_pec); - - // 3 - wakeup_idle(config); // This will guarantee that the LTC6804 isoSPI port is - // awake. This command can be removed. - - // 4 - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); - HAL_SPI_Transmit(config->spi, cmd, 4, HAL_MAX_DELAY); - HAL_SPI_Receive(config->spi, data, (REG_LEN * total_ic), HAL_MAX_DELAY); - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); + ltc_config *config, + uint8_t reg, // Determines which cell voltage register is read back + uint8_t total_ic, // the number of ICs in the + uint8_t *data // An array of the unparsed cell codes +) +{ + const uint8_t REG_LEN = + 8; // number of bytes in each ICs register + 2 bytes for the PEC + uint8_t cmd[4]; + uint16_t cmd_pec; + + // 1 + if (reg == 1) // 1: RDCVA + { + cmd[1] = 0x04; + cmd[0] = 0x00; + } else if (reg == 2) // 2: RDCVB + { + cmd[1] = 0x06; + cmd[0] = 0x00; + } else if (reg == 3) // 3: RDCVC + { + cmd[1] = 0x08; + cmd[0] = 0x00; + } else if (reg == 4) // 4: RDCVD + { + cmd[1] = 0x0A; + cmd[0] = 0x00; + } + + // 2 + cmd_pec = pec15_calc(2, cmd); + cmd[2] = (uint8_t)(cmd_pec >> 8); + cmd[3] = (uint8_t)(cmd_pec); + + // 3 + wakeup_idle( + config); // This will guarantee that the LTC6804 isoSPI port is + // awake. This command can be removed. + + // 4 + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); + HAL_SPI_Transmit(config->spi, cmd, 4, HAL_MAX_DELAY); + HAL_SPI_Receive(config->spi, data, (REG_LEN * total_ic), HAL_MAX_DELAY); + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); } /* LTC6804_rdcv_reg Function Process: @@ -560,145 +589,174 @@ void LTC6804_rdcv_reg( -1: PEC error detected, retry read *************************************************/ int8_t LTC6804_rdaux( - ltc_config *config, - uint8_t reg, // Determines which GPIO voltage register is read back. - uint8_t total_ic, // the number of ICs in the system - uint16_t aux_codes[] - [6] // A two dimensional array of the gpio voltage codes. -) { - const uint8_t NUM_RX_BYT = 8; - const uint8_t BYT_IN_REG = 6; - const uint8_t GPIO_IN_REG = 3; - - uint8_t *data; - uint8_t data_counter = 0; - int8_t pec_error = 1; - uint8_t retries = 0; - uint16_t parsed_aux; - uint16_t received_pec; - uint16_t data_pec; - data = (uint8_t *)malloc((NUM_RX_BYT * total_ic) * sizeof(uint8_t)); - // 1.a - if (reg == 0) { - // a.i - for (uint8_t gpio_reg = 1; gpio_reg < 3; - gpio_reg++) // executes once for each of the LTC6804 aux voltage - // registers - { - if (pec_error != -1) - pec_error = 1; - retries = 0; - - while (retries < LTC_MAX_RETRIES && (pec_error == -1 || pec_error == 1)) { - data_counter = 0; - LTC6804_rdaux_reg(config, gpio_reg, total_ic, - data); // Reads the raw auxiliary register data into - // the data[] array - - for (uint8_t current_ic = 0; current_ic < total_ic; - current_ic++) // executes for every LTC6804 in the daisy chain - { - // current_ic is used as the IC counter - - // a.ii - for (uint8_t current_gpio = 0; current_gpio < GPIO_IN_REG; - current_gpio++) // This loop parses the read back data into GPIO - // voltages, it - { - // loops once for each of the 3 gpio voltage codes in the register - - parsed_aux = - data[data_counter] + - (data[data_counter + 1] << 8); // Each gpio codes is received as - // two bytes and is combined to - // create the parsed gpio voltage code - - aux_codes[current_ic][current_gpio + - ((gpio_reg - 1) * GPIO_IN_REG)] = parsed_aux; - data_counter = - data_counter + - 2; // Because gpio voltage codes are two bytes the data counter - // must increment by two for each parsed gpio voltage code - } - // a.iii - received_pec = - (data[data_counter] << 8) + - data[data_counter + 1]; // The received PEC for the current_ic is - // transmitted as the 7th and 8th - // after the 6 gpio voltage data bytes - data_pec = pec15_calc(BYT_IN_REG, &data[current_ic * NUM_RX_BYT]); - if (received_pec == data_pec) { - pec_error = 0; // The pec_error variable is simply set negative if - // any PEC errors - // are detected in the received serial data - } else if (received_pec != data_pec) { - if (retries == LTC_MAX_RETRIES) { - aux_codes[current_ic][gpio_reg - 1] = LTC_BAD_READ; - aux_codes[current_ic][gpio_reg] = LTC_BAD_READ; - } - pec_error = -1; - } - - retries++; - - data_counter = data_counter + 2; // Because the transmitted PEC code - // is 2 bytes long the data_counter - // must be incremented by 2 bytes to point to the next ICs gpio - // voltage data - } - } - } - } else { - while (retries < LTC_MAX_RETRIES && pec_error == -1) { - // b.i - LTC6804_rdaux_reg(config, reg, total_ic, data); - for (int current_ic = 0; current_ic < total_ic; - current_ic++) // executes for every LTC6804 in the daisy chain - { - // current_ic is used as an IC counter - - // b.ii - for (int current_gpio = 0; current_gpio < GPIO_IN_REG; - current_gpio++) // This loop parses the read back data. Loops - { - // once for each aux voltage in the register - - parsed_aux = - (data[data_counter] + - (data[data_counter + 1] << 8)); // Each gpio codes is received as - // two bytes and is combined to - // create the parsed gpio voltage code - aux_codes[current_ic][current_gpio + ((reg - 1) * GPIO_IN_REG)] = - parsed_aux; - data_counter = - data_counter + - 2; // Because gpio voltage codes are two bytes the data counter - // must increment by two for each parsed gpio voltage code - } - // b.iii - received_pec = - (data[data_counter] << 8) + - data[data_counter + 1]; // The received PEC for the current_ic is - // transmitted as the 7th and 8th - // after the 6 gpio voltage data bytes - data_pec = pec15_calc(BYT_IN_REG, &data[current_ic * NUM_RX_BYT]); - if (received_pec != data_pec) { - pec_error = -1; // The pec_error variable is simply set negative if - // any PEC errors - // are detected in the received serial data - } else { - pec_error = 0; - } - - data_counter = data_counter + 2; // Because the transmitted PEC code is - // 2 bytes long the data_counter - // must be incremented by 2 bytes to point to the next ICs gpio voltage - // data - } - } - } - free(data); - return (pec_error); + ltc_config *config, + uint8_t reg, // Determines which GPIO voltage register is read back. + uint8_t total_ic, // the number of ICs in the system + uint16_t aux_codes[][6] // A two dimensional array of the gpio voltage codes. +) +{ + const uint8_t NUM_RX_BYT = 8; + const uint8_t BYT_IN_REG = 6; + const uint8_t GPIO_IN_REG = 3; + + uint8_t *data; + uint8_t data_counter = 0; + int8_t pec_error = 1; + uint8_t retries = 0; + uint16_t parsed_aux; + uint16_t received_pec; + uint16_t data_pec; + data = (uint8_t *)malloc((NUM_RX_BYT * total_ic) * sizeof(uint8_t)); + // 1.a + if (reg == 0) { + // a.i + for (uint8_t gpio_reg = 1; gpio_reg < 3; + gpio_reg++) // executes once for each of the LTC6804 aux voltage + // registers + { + if (pec_error != -1) + pec_error = 1; + retries = 0; + + while (retries < LTC_MAX_RETRIES && + (pec_error == -1 || pec_error == 1)) { + data_counter = 0; + LTC6804_rdaux_reg( + config, gpio_reg, total_ic, + data); // Reads the raw auxiliary register data into + // the data[] array + + for (uint8_t current_ic = 0; + current_ic < total_ic; + current_ic++) // executes for every LTC6804 in the daisy chain + { + // current_ic is used as the IC counter + + // a.ii + for (uint8_t current_gpio = 0; + current_gpio < GPIO_IN_REG; + current_gpio++) // This loop parses the read back data into GPIO + // voltages, it + { + // loops once for each of the 3 gpio voltage codes in the register + + parsed_aux = + data[data_counter] + + (data[data_counter + 1] + << 8); // Each gpio codes is received as + // two bytes and is combined to + // create the parsed gpio voltage code + + aux_codes[current_ic] + [current_gpio + + ((gpio_reg - 1) * + GPIO_IN_REG)] = + parsed_aux; + data_counter = + data_counter + + 2; // Because gpio voltage codes are two bytes the data counter + // must increment by two for each parsed gpio voltage code + } + // a.iii + received_pec = + (data[data_counter] << 8) + + data[data_counter + + 1]; // The received PEC for the current_ic is + // transmitted as the 7th and 8th + // after the 6 gpio voltage data bytes + data_pec = pec15_calc( + BYT_IN_REG, + &data[current_ic * NUM_RX_BYT]); + if (received_pec == data_pec) { + pec_error = + 0; // The pec_error variable is simply set negative if + // any PEC errors + // are detected in the received serial data + } else if (received_pec != data_pec) { + if (retries == + LTC_MAX_RETRIES) { + aux_codes[current_ic] + [gpio_reg - + 1] = LTC_BAD_READ; + aux_codes[current_ic] + [gpio_reg] = + LTC_BAD_READ; + } + pec_error = -1; + } + + retries++; + + data_counter = + data_counter + + 2; // Because the transmitted PEC code + // is 2 bytes long the data_counter + // must be incremented by 2 bytes to point to the next ICs gpio + // voltage data + } + } + } + } else { + while (retries < LTC_MAX_RETRIES && pec_error == -1) { + // b.i + LTC6804_rdaux_reg(config, reg, total_ic, data); + for (int current_ic = 0; current_ic < total_ic; + current_ic++) // executes for every LTC6804 in the daisy chain + { + // current_ic is used as an IC counter + + // b.ii + for (int current_gpio = 0; + current_gpio < GPIO_IN_REG; + current_gpio++) // This loop parses the read back data. Loops + { + // once for each aux voltage in the register + + parsed_aux = + (data[data_counter] + + (data[data_counter + 1] + << 8)); // Each gpio codes is received as + // two bytes and is combined to + // create the parsed gpio voltage code + aux_codes[current_ic] + [current_gpio + + ((reg - 1) * GPIO_IN_REG)] = + parsed_aux; + data_counter = + data_counter + + 2; // Because gpio voltage codes are two bytes the data counter + // must increment by two for each parsed gpio voltage code + } + // b.iii + received_pec = + (data[data_counter] << 8) + + data[data_counter + + 1]; // The received PEC for the current_ic is + // transmitted as the 7th and 8th + // after the 6 gpio voltage data bytes + data_pec = pec15_calc( + BYT_IN_REG, + &data[current_ic * NUM_RX_BYT]); + if (received_pec != data_pec) { + pec_error = + -1; // The pec_error variable is simply set negative if + // any PEC errors + // are detected in the received serial data + } else { + pec_error = 0; + } + + data_counter = + data_counter + + 2; // Because the transmitted PEC code is + // 2 bytes long the data_counter + // must be incremented by 2 bytes to point to the next ICs gpio voltage + // data + } + } + } + free(data); + return (pec_error); } /* LTC6804_rdaux Sequence @@ -749,43 +807,45 @@ int8_t LTC6804_rdaux( *************************************************/ void LTC6804_rdaux_reg( - ltc_config *config, - uint8_t reg, // Determines which GPIO voltage register is read back - uint8_t total_ic, // The number of ICs in the system - uint8_t *data // Array of the unparsed auxiliary codes -) { - const uint8_t REG_LEN = - 8; // number of bytes in the register + 2 bytes for the PEC - uint8_t cmd[4]; - uint16_t cmd_pec; - - // 1 - if (reg == 1) // Read back auxiliary group A - { - cmd[1] = 0x0C; - cmd[0] = 0x00; - } else if (reg == 2) // Read back auxiliary group B - { - cmd[1] = 0x0e; - cmd[0] = 0x00; - } else // Read back auxiliary group A - { - cmd[1] = 0x0C; - cmd[0] = 0x00; - } - // 2 - cmd_pec = pec15_calc(2, cmd); - cmd[2] = (uint8_t)(cmd_pec >> 8); - cmd[3] = (uint8_t)(cmd_pec); - - // 3 - wakeup_idle(config); // This will guarantee that the LTC6804 isoSPI port is - // awake, this command can be removed. - // 4 - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); - HAL_SPI_Transmit(config->spi, cmd, 4, HAL_MAX_DELAY); - HAL_SPI_Receive(config->spi, data, (REG_LEN * total_ic), HAL_MAX_DELAY); - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); + ltc_config *config, + uint8_t reg, // Determines which GPIO voltage register is read back + uint8_t total_ic, // The number of ICs in the system + uint8_t *data // Array of the unparsed auxiliary codes +) +{ + const uint8_t REG_LEN = + 8; // number of bytes in the register + 2 bytes for the PEC + uint8_t cmd[4]; + uint16_t cmd_pec; + + // 1 + if (reg == 1) // Read back auxiliary group A + { + cmd[1] = 0x0C; + cmd[0] = 0x00; + } else if (reg == 2) // Read back auxiliary group B + { + cmd[1] = 0x0e; + cmd[0] = 0x00; + } else // Read back auxiliary group A + { + cmd[1] = 0x0C; + cmd[0] = 0x00; + } + // 2 + cmd_pec = pec15_calc(2, cmd); + cmd[2] = (uint8_t)(cmd_pec >> 8); + cmd[3] = (uint8_t)(cmd_pec); + + // 3 + wakeup_idle( + config); // This will guarantee that the LTC6804 isoSPI port is + // awake, this command can be removed. + // 4 + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); + HAL_SPI_Transmit(config->spi, cmd, 4, HAL_MAX_DELAY); + HAL_SPI_Receive(config->spi, data, (REG_LEN * total_ic), HAL_MAX_DELAY); + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); } /* LTC6804_rdaux_reg Function Process: @@ -812,30 +872,32 @@ void LTC6804_rdaux_reg( |CLRCELL: | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 | ************************************************************/ -void LTC6804_clrcell(ltc_config *config) { - uint8_t cmd[4]; - uint16_t cmd_pec; - - // 1 - cmd[0] = 0x07; - cmd[1] = 0x11; - - // 2 - cmd_pec = pec15_calc(2, cmd); - cmd[2] = (uint8_t)(cmd_pec >> 8); - cmd[3] = (uint8_t)(cmd_pec); - - // 3 - wakeup_idle(config); // This will guarantee that the LTC6804 isoSPI port is - // awake. This command can be removed. - - // 4 - - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); - HAL_SPI_Transmit(config->spi, cmd, 4, HAL_MAX_DELAY); - // NOTE: prev iteration had write + read, but didnt read anything? unless im - // missing something no point in reading - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); +void LTC6804_clrcell(ltc_config *config) +{ + uint8_t cmd[4]; + uint16_t cmd_pec; + + // 1 + cmd[0] = 0x07; + cmd[1] = 0x11; + + // 2 + cmd_pec = pec15_calc(2, cmd); + cmd[2] = (uint8_t)(cmd_pec >> 8); + cmd[3] = (uint8_t)(cmd_pec); + + // 3 + wakeup_idle( + config); // This will guarantee that the LTC6804 isoSPI port is + // awake. This command can be removed. + + // 4 + + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); + HAL_SPI_Transmit(config->spi, cmd, 4, HAL_MAX_DELAY); + // NOTE: prev iteration had write + read, but didnt read anything? unless im + // missing something no point in reading + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); } /* @@ -865,28 +927,30 @@ void LTC6804_clrcell(ltc_config *config) { |CLRAUX: | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 1 | 0 | 0 | 2 | 0 | ***************************************************************/ -void LTC6804_clraux(ltc_config *config) { - uint8_t cmd[4]; - uint16_t cmd_pec; - - // 1 - cmd[0] = 0x07; - cmd[1] = 0x12; - - // 2 - cmd_pec = pec15_calc(2, cmd); - cmd[2] = (uint8_t)(cmd_pec >> 8); - cmd[3] = (uint8_t)(cmd_pec); - - // 3 - wakeup_idle(config); // This will guarantee that the LTC6804 isoSPI port is - // awake.This command can be removed. - // 4 - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); - HAL_SPI_Transmit(config->spi, cmd, 4, HAL_MAX_DELAY); - // NOTE: prev iteration had write + read, but didnt read anything? unless im - // missing something no point in reading - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); +void LTC6804_clraux(ltc_config *config) +{ + uint8_t cmd[4]; + uint16_t cmd_pec; + + // 1 + cmd[0] = 0x07; + cmd[1] = 0x12; + + // 2 + cmd_pec = pec15_calc(2, cmd); + cmd[2] = (uint8_t)(cmd_pec >> 8); + cmd[3] = (uint8_t)(cmd_pec); + + // 3 + wakeup_idle( + config); // This will guarantee that the LTC6804 isoSPI port is + // awake.This command can be removed. + // 4 + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); + HAL_SPI_Transmit(config->spi, cmd, 4, HAL_MAX_DELAY); + // NOTE: prev iteration had write + read, but didnt read anything? unless im + // missing something no point in reading + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); } /* LTC6804_clraux Function sequence: @@ -932,64 +996,68 @@ void LTC6804_clraux(ltc_config *config) { | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | ********************************************************/ void LTC6804_wrcfg( - ltc_config *config, - uint8_t total_ic, // The number of ICs being written to - uint8_t data_config[][6] // A two dimensional array of the configuration - // data that will be written -) { - const uint8_t BYTES_IN_REG = 6; - const uint8_t CMD_LEN = 4 + (8 * total_ic); - uint8_t *cmd; - uint16_t cfg_pec; - uint8_t cmd_index; // command counter - - cmd = (uint8_t *)malloc(CMD_LEN * sizeof(uint8_t)); - - // 1 - cmd[0] = 0x00; - cmd[1] = 0x01; - cmd[2] = 0x3d; - cmd[3] = 0x6e; - - // 2 - cmd_index = 4; - for (uint8_t current_ic = total_ic; current_ic > 0; - current_ic--) // executes for each LTC6804 in daisy chain, this loops - // starts with - { - // the last IC on the stack. The first configuration written is - // received by the last IC in the daisy chain - - for (uint8_t current_byte = 0; current_byte < BYTES_IN_REG; - current_byte++) // executes for each of the 6 bytes in the CFGR - // register - { - // current_byte is the byte counter - - cmd[cmd_index] = - data_config[current_ic - 1][current_byte]; // adding the config data - // to the array to be sent - cmd_index = cmd_index + 1; - } - // 3 - cfg_pec = (uint16_t)pec15_calc( - BYTES_IN_REG, - &data_config[current_ic - 1][0]); // calculating the PEC for each ICs - // configuration register data - cmd[cmd_index] = (uint8_t)(cfg_pec >> 8); - cmd[cmd_index + 1] = (uint8_t)cfg_pec; - cmd_index = cmd_index + 2; - } - - // 4 - wakeup_idle(config); // This will guarantee that the LTC6804 isoSPI port is - // awake.This command can be removed. - // 5 - - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); - HAL_SPI_Transmit(config->spi, cmd, CMD_LEN, HAL_MAX_DELAY); - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); - free(cmd); + ltc_config *config, + uint8_t total_ic, // The number of ICs being written to + uint8_t data_config[][6] // A two dimensional array of the configuration + // data that will be written +) +{ + const uint8_t BYTES_IN_REG = 6; + const uint8_t CMD_LEN = 4 + (8 * total_ic); + uint8_t *cmd; + uint16_t cfg_pec; + uint8_t cmd_index; // command counter + + cmd = (uint8_t *)malloc(CMD_LEN * sizeof(uint8_t)); + + // 1 + cmd[0] = 0x00; + cmd[1] = 0x01; + cmd[2] = 0x3d; + cmd[3] = 0x6e; + + // 2 + cmd_index = 4; + for (uint8_t current_ic = total_ic; current_ic > 0; + current_ic--) // executes for each LTC6804 in daisy chain, this loops + // starts with + { + // the last IC on the stack. The first configuration written is + // received by the last IC in the daisy chain + + for (uint8_t current_byte = 0; current_byte < BYTES_IN_REG; + current_byte++) // executes for each of the 6 bytes in the CFGR + // register + { + // current_byte is the byte counter + + cmd[cmd_index] = + data_config[current_ic - 1] + [current_byte]; // adding the config data + // to the array to be sent + cmd_index = cmd_index + 1; + } + // 3 + cfg_pec = (uint16_t)pec15_calc( + BYTES_IN_REG, + &data_config[current_ic - 1] + [0]); // calculating the PEC for each ICs + // configuration register data + cmd[cmd_index] = (uint8_t)(cfg_pec >> 8); + cmd[cmd_index + 1] = (uint8_t)cfg_pec; + cmd_index = cmd_index + 2; + } + + // 4 + wakeup_idle( + config); // This will guarantee that the LTC6804 isoSPI port is + // awake.This command can be removed. + // 5 + + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); + HAL_SPI_Transmit(config->spi, cmd, CMD_LEN, HAL_MAX_DELAY); + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); + free(cmd); } /* WRCFG Sequence: @@ -1040,65 +1108,69 @@ Command Code: ********************************************************/ int8_t LTC6804_rdcfg(ltc_config *config, - uint8_t total_ic, // Number of ICs in the system - uint8_t r_config[][8] // A two dimensional array that the function - // stores the read configuration data. -) { - const uint8_t BYTES_IN_REG = 8; - - uint8_t cmd[4]; - uint8_t *rx_data; - int8_t pec_error = -1; - uint16_t data_pec; - uint16_t received_pec; - uint8_t retries = 0; - - rx_data = (uint8_t *)malloc((8 * total_ic) * sizeof(uint8_t)); - - // 1 - cmd[0] = 0x00; - cmd[1] = 0x02; - cmd[2] = 0x2b; - cmd[3] = 0x0A; - - while (retries < LTC_MAX_RETRIES && pec_error == -1) { - // 2 - wakeup_idle(config); // This will guarantee that the LTC6804 isoSPI port is - // awake. This command can be removed. - // 3 - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); - HAL_SPI_Transmit(config->spi, cmd, 4, HAL_MAX_DELAY); - HAL_SPI_Receive(config->spi, rx_data, (BYTES_IN_REG * total_ic), - HAL_MAX_DELAY); - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); - // Read the configuration data of all ICs on the daisy chain into - // rx_data[] array - for (uint8_t current_ic = 0; current_ic < total_ic; - current_ic++) // executes for each LTC6804 in the daisy chain and packs - // the data - { - // into the r_config array as well as check the received Config data - // for any bit errors - // 4.a - for (uint8_t current_byte = 0; current_byte < BYTES_IN_REG; - current_byte++) { - r_config[current_ic][current_byte] = - rx_data[current_byte + (current_ic * BYTES_IN_REG)]; - } - // 4.b - received_pec = (r_config[current_ic][6] << 8) + r_config[current_ic][7]; - data_pec = pec15_calc(6, &r_config[current_ic][0]); - if (received_pec != data_pec) { - pec_error = -1; - } else { - pec_error = 0; - } - } - retries++; - } - free(rx_data); - // 5 - return (pec_error); + uint8_t total_ic, // Number of ICs in the system + uint8_t r_config[][8] // A two dimensional array that the function + // stores the read configuration data. +) +{ + const uint8_t BYTES_IN_REG = 8; + + uint8_t cmd[4]; + uint8_t *rx_data; + int8_t pec_error = -1; + uint16_t data_pec; + uint16_t received_pec; + uint8_t retries = 0; + + rx_data = (uint8_t *)malloc((8 * total_ic) * sizeof(uint8_t)); + + // 1 + cmd[0] = 0x00; + cmd[1] = 0x02; + cmd[2] = 0x2b; + cmd[3] = 0x0A; + + while (retries < LTC_MAX_RETRIES && pec_error == -1) { + // 2 + wakeup_idle( + config); // This will guarantee that the LTC6804 isoSPI port is + // awake. This command can be removed. + // 3 + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); + HAL_SPI_Transmit(config->spi, cmd, 4, HAL_MAX_DELAY); + HAL_SPI_Receive(config->spi, rx_data, (BYTES_IN_REG * total_ic), + HAL_MAX_DELAY); + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); + // Read the configuration data of all ICs on the daisy chain into + // rx_data[] array + for (uint8_t current_ic = 0; current_ic < total_ic; + current_ic++) // executes for each LTC6804 in the daisy chain and packs + // the data + { + // into the r_config array as well as check the received Config data + // for any bit errors + // 4.a + for (uint8_t current_byte = 0; + current_byte < BYTES_IN_REG; current_byte++) { + r_config[current_ic][current_byte] = + rx_data[current_byte + + (current_ic * BYTES_IN_REG)]; + } + // 4.b + received_pec = (r_config[current_ic][6] << 8) + + r_config[current_ic][7]; + data_pec = pec15_calc(6, &r_config[current_ic][0]); + if (received_pec != data_pec) { + pec_error = -1; + } else { + pec_error = 0; + } + } + retries++; + } + free(rx_data); + // 5 + return (pec_error); } /* RDCFG Sequence: @@ -1118,11 +1190,12 @@ LTC6804_rdcfg(ltc_config *config, \brief Wake isoSPI up from idle state Generic wakeup commannd to wake isoSPI up out of idle *****************************************************/ -void wakeup_idle(ltc_config *config) { - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); - // delayMicroseconds(2); // Guarantees the isoSPI will be in ready mode - ADD - // BACK IF NEEDED - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); +void wakeup_idle(ltc_config *config) +{ + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); + // delayMicroseconds(2); // Guarantees the isoSPI will be in ready mode - ADD + // BACK IF NEEDED + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); } /*!**************************************************** @@ -1130,10 +1203,11 @@ void wakeup_idle(ltc_config *config) { Generic wakeup commannd to wake the LTC6804 from sleep *****************************************************/ -void wakeup_sleep(ltc_config *config) { - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); - // delay(1); // Guarantees the LTC6804 will be in standby - ADD BACK IF NEEDED - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); +void wakeup_sleep(ltc_config *config) +{ + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); + // delay(1); // Guarantees the LTC6804 will be in standby - ADD BACK IF NEEDED + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); } /*!********************************************************** \brief calaculates and returns the CRC15 @@ -1148,180 +1222,190 @@ from @returns The calculated pec15 as an unsigned int ***********************************************************/ uint16_t -pec15_calc(uint8_t len, // Number of bytes that will be used to calculate a PEC - uint8_t *data // Array of data that will be used to calculate a PEC -) { - uint16_t remainder, addr; - - remainder = 16; // initialize the PEC - for (uint8_t i = 0; i < len; i++) // loops for each byte in data array - { - addr = ((remainder >> 7) ^ data[i]) & 0xff; // calculate PEC table address - remainder = (remainder << 8) ^ crc15Table[addr]; - } - return (remainder * 2); // The CRC15 has a 0 in the LSB so the remainder must - // be multiplied by 2 +pec15_calc(uint8_t len, // Number of bytes that will be used to calculate a PEC + uint8_t *data // Array of data that will be used to calculate a PEC +) +{ + uint16_t remainder, addr; + + remainder = 16; // initialize the PEC + for (uint8_t i = 0; i < len; i++) // loops for each byte in data array + { + addr = ((remainder >> 7) ^ data[i]) & + 0xff; // calculate PEC table address + remainder = (remainder << 8) ^ crc15Table[addr]; + } + return (remainder * + 2); // The CRC15 has a 0 in the LSB so the remainder must + // be multiplied by 2 } void write_68(ltc_config *config, - uint8_t total_ic, // Number of ICs to be written to - uint8_t tx_cmd[2], // The command to be transmitted - uint8_t data[] // Payload Data -) { - const uint8_t BYTES_IN_REG = 6; - const uint8_t CMD_LEN = 4 + (8 * total_ic); - uint8_t *cmd; - uint16_t data_pec; - uint16_t cmd_pec; - uint8_t cmd_index; - - cmd = (uint8_t *)malloc(CMD_LEN * sizeof(uint8_t)); - cmd[0] = tx_cmd[0]; - cmd[1] = tx_cmd[1]; - cmd_pec = pec15_calc(2, cmd); - cmd[2] = (uint8_t)(cmd_pec >> 8); - cmd[3] = (uint8_t)(cmd_pec); - - cmd_index = 4; - for (uint8_t current_ic = total_ic; current_ic > 0; - current_ic--) // Executes for each LTC681x, this loops starts with the - // last IC on the stack. - { // The first configuration written is received by the last IC in the daisy - // chain - for (uint8_t current_byte = 0; current_byte < BYTES_IN_REG; - current_byte++) { - cmd[cmd_index] = data[((current_ic - 1) * 6) + current_byte]; - cmd_index = cmd_index + 1; - } - - data_pec = (uint16_t)pec15_calc( - BYTES_IN_REG, - &data[(current_ic - 1) * 6]); // Calculating the PEC for each ICs - // configuration register data - cmd[cmd_index] = (uint8_t)(data_pec >> 8); - cmd[cmd_index + 1] = (uint8_t)data_pec; - cmd_index = cmd_index + 2; - } - - wakeup_idle(config); - - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); - HAL_SPI_Transmit(config->spi, cmd, CMD_LEN, HAL_MAX_DELAY); - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); - - free(cmd); + uint8_t total_ic, // Number of ICs to be written to + uint8_t tx_cmd[2], // The command to be transmitted + uint8_t data[] // Payload Data +) +{ + const uint8_t BYTES_IN_REG = 6; + const uint8_t CMD_LEN = 4 + (8 * total_ic); + uint8_t *cmd; + uint16_t data_pec; + uint16_t cmd_pec; + uint8_t cmd_index; + + cmd = (uint8_t *)malloc(CMD_LEN * sizeof(uint8_t)); + cmd[0] = tx_cmd[0]; + cmd[1] = tx_cmd[1]; + cmd_pec = pec15_calc(2, cmd); + cmd[2] = (uint8_t)(cmd_pec >> 8); + cmd[3] = (uint8_t)(cmd_pec); + + cmd_index = 4; + for (uint8_t current_ic = total_ic; current_ic > 0; + current_ic--) // Executes for each LTC681x, this loops starts with the + // last IC on the stack. + { // The first configuration written is received by the last IC in the daisy + // chain + for (uint8_t current_byte = 0; current_byte < BYTES_IN_REG; + current_byte++) { + cmd[cmd_index] = + data[((current_ic - 1) * 6) + current_byte]; + cmd_index = cmd_index + 1; + } + + data_pec = (uint16_t)pec15_calc( + BYTES_IN_REG, + &data[(current_ic - 1) * + 6]); // Calculating the PEC for each ICs + // configuration register data + cmd[cmd_index] = (uint8_t)(data_pec >> 8); + cmd[cmd_index + 1] = (uint8_t)data_pec; + cmd_index = cmd_index + 2; + } + + wakeup_idle(config); + + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); + HAL_SPI_Transmit(config->spi, cmd, CMD_LEN, HAL_MAX_DELAY); + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); + + free(cmd); } void LTC6804_wrcomm(ltc_config *config, uint8_t total_ic, - uint8_t writeData[][6]) { - uint8_t cmd[2] = {0x07, 0x21}; - uint8_t write_buffer[256]; - uint8_t write_count = 0; - for (uint8_t chip = 0; chip < total_ic; chip++) { - for (uint8_t data = 0; data < 6; data++) { - write_buffer[write_count] = writeData[chip][data]; - write_count++; - } - } - write_68(config, total_ic, cmd, write_buffer); + uint8_t writeData[][6]) +{ + uint8_t cmd[2] = { 0x07, 0x21 }; + uint8_t write_buffer[256]; + uint8_t write_count = 0; + for (uint8_t chip = 0; chip < total_ic; chip++) { + for (uint8_t data = 0; data < 6; data++) { + write_buffer[write_count] = writeData[chip][data]; + write_count++; + } + } + write_68(config, total_ic, cmd, write_buffer); } int8_t LTC6804_rdcomm( - ltc_config *config, - uint8_t total_ic, // Number of ICs in the system - uint8_t readData[][6] // A two dimensional array that stores the read data -) { - uint8_t cmd[2] = {0x07, 0x22}; - uint8_t read_buffer[256]; - int8_t pec_error = -1; - uint16_t data_pec; - uint16_t calc_pec; - uint8_t c_ic = 0; - uint8_t retries = 0; - - while (retries < LTC_MAX_RETRIES && pec_error == -1) { - printf("RETRYING...\n"); - pec_error = read_68(config, total_ic, cmd, read_buffer); - retries++; - } - - for (uint8_t current_ic = 0; current_ic < total_ic; current_ic++) { - - for (int byte = 0; byte < 6; byte++) { - readData[current_ic][byte] = read_buffer[byte + (8 * current_ic)]; - } - } - return pec_error; // todo : PEC Error + ltc_config *config, + uint8_t total_ic, // Number of ICs in the system + uint8_t readData[][6] // A two dimensional array that stores the read data +) +{ + uint8_t cmd[2] = { 0x07, 0x22 }; + uint8_t read_buffer[256]; + int8_t pec_error = -1; + uint16_t data_pec; + uint16_t calc_pec; + uint8_t c_ic = 0; + uint8_t retries = 0; + + while (retries < LTC_MAX_RETRIES && pec_error == -1) { + printf("RETRYING...\n"); + pec_error = read_68(config, total_ic, cmd, read_buffer); + retries++; + } + + for (uint8_t current_ic = 0; current_ic < total_ic; current_ic++) { + for (int byte = 0; byte < 6; byte++) { + readData[current_ic][byte] = + read_buffer[byte + (8 * current_ic)]; + } + } + return pec_error; // todo : PEC Error } /* Generic function to write 68xx commands and read data. Function calculated * PEC for tx_cmd data */ int8_t read_68(ltc_config *config, - uint8_t total_ic, // Number of ICs in the system - uint8_t tx_cmd[2], // The command to be transmitted - uint8_t *rx_data // Data to be read -) { - const uint8_t BYTES_IN_REG = 8; - uint8_t cmd[4]; - uint8_t data[256]; - int8_t pec_error = 0; - uint16_t cmd_pec; - uint16_t data_pec; - uint16_t received_pec; - - cmd[0] = tx_cmd[0]; - cmd[1] = tx_cmd[1]; - cmd_pec = pec15_calc(2, cmd); - cmd[2] = (uint8_t)(cmd_pec >> 8); - cmd[3] = (uint8_t)(cmd_pec); - - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); - HAL_SPI_Transmit(config->spi, cmd, 4, HAL_MAX_DELAY); - HAL_SPI_Receive(config->spi, data, (BYTES_IN_REG * total_ic), HAL_MAX_DELAY); - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); - - for (uint8_t current_ic = 0; current_ic < total_ic; - current_ic++) // Executes for each LTC681x in the daisy chain and packs - // the data - { // into the rx_data array as well as check the received data for any bit - // errors - for (uint8_t current_byte = 0; current_byte < BYTES_IN_REG; - current_byte++) { - rx_data[(current_ic * 8) + current_byte] = - data[current_byte + (current_ic * BYTES_IN_REG)]; - } - - received_pec = - (rx_data[(current_ic * 8) + 6] << 8) + rx_data[(current_ic * 8) + 7]; - data_pec = pec15_calc(6, &rx_data[current_ic * 8]); - - if (received_pec != data_pec) { - printf("PEC FAULT"); - pec_error = -1; - } - } - - return (pec_error); + uint8_t total_ic, // Number of ICs in the system + uint8_t tx_cmd[2], // The command to be transmitted + uint8_t *rx_data // Data to be read +) +{ + const uint8_t BYTES_IN_REG = 8; + uint8_t cmd[4]; + uint8_t data[256]; + int8_t pec_error = 0; + uint16_t cmd_pec; + uint16_t data_pec; + uint16_t received_pec; + + cmd[0] = tx_cmd[0]; + cmd[1] = tx_cmd[1]; + cmd_pec = pec15_calc(2, cmd); + cmd[2] = (uint8_t)(cmd_pec >> 8); + cmd[3] = (uint8_t)(cmd_pec); + + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); + HAL_SPI_Transmit(config->spi, cmd, 4, HAL_MAX_DELAY); + HAL_SPI_Receive(config->spi, data, (BYTES_IN_REG * total_ic), + HAL_MAX_DELAY); + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); + + for (uint8_t current_ic = 0; current_ic < total_ic; + current_ic++) // Executes for each LTC681x in the daisy chain and packs + // the data + { // into the rx_data array as well as check the received data for any bit + // errors + for (uint8_t current_byte = 0; current_byte < BYTES_IN_REG; + current_byte++) { + rx_data[(current_ic * 8) + current_byte] = + data[current_byte + (current_ic * BYTES_IN_REG)]; + } + + received_pec = (rx_data[(current_ic * 8) + 6] << 8) + + rx_data[(current_ic * 8) + 7]; + data_pec = pec15_calc(6, &rx_data[current_ic * 8]); + + if (received_pec != data_pec) { + printf("PEC FAULT"); + pec_error = -1; + } + } + + return (pec_error); } void LTC6804_stcomm(ltc_config *config, - uint8_t len) // Length of data to be transmitted + uint8_t len) // Length of data to be transmitted { - uint8_t cmd[4]; - uint16_t cmd_pec; - - cmd[0] = 0x07; - cmd[1] = 0x23; - cmd_pec = pec15_calc(2, cmd); - cmd[2] = (uint8_t)(cmd_pec >> 8); - cmd[3] = (uint8_t)(cmd_pec); - - wakeup_idle(config); - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); - HAL_SPI_Transmit(config->spi, cmd, 4, HAL_MAX_DELAY); - int16_t def_cmd = 0xff; - for (int i = 0; i < len * 3; i++) { - HAL_SPI_Transmit(config->spi, &def_cmd, 1, HAL_MAX_DELAY); - } - HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); + uint8_t cmd[4]; + uint16_t cmd_pec; + + cmd[0] = 0x07; + cmd[1] = 0x23; + cmd_pec = pec15_calc(2, cmd); + cmd[2] = (uint8_t)(cmd_pec >> 8); + cmd[3] = (uint8_t)(cmd_pec); + + wakeup_idle(config); + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_RESET); + HAL_SPI_Transmit(config->spi, cmd, 4, HAL_MAX_DELAY); + int16_t def_cmd = 0xff; + for (int i = 0; i < len * 3; i++) { + HAL_SPI_Transmit(config->spi, &def_cmd, 1, HAL_MAX_DELAY); + } + HAL_GPIO_WritePin(config->gpio, config->cs_pin, GPIO_PIN_SET); } diff --git a/general/src/m24c32.c b/general/src/m24c32.c index 4970323..c4a925c 100644 --- a/general/src/m24c32.c +++ b/general/src/m24c32.c @@ -1,63 +1,69 @@ #include "m24c32.h" -uint16_t check_size(uint16_t size) { - if (size < M24C32_PAGE_SIZE) - return size; - else - return M24C32_PAGE_SIZE; +uint16_t check_size(uint16_t size) +{ + if (size < M24C32_PAGE_SIZE) + return size; + else + return M24C32_PAGE_SIZE; } HAL_StatusTypeDef eeprom_write(uint16_t mem_address, uint8_t *data, - uint16_t size) { - HAL_StatusTypeDef status; + uint16_t size) +{ + HAL_StatusTypeDef status; - for (int bytes_written = 0; bytes_written < size; bytes_written += 32) { - uint16_t write_size = check_size(size - bytes_written); + for (int bytes_written = 0; bytes_written < size; bytes_written += 32) { + uint16_t write_size = check_size(size - bytes_written); - status = HAL_I2C_Mem_Write(i2c_handle, M24C32_I2C_ADDR, - mem_address + bytes_written, 2, - &data[bytes_written], write_size, 1000); - if (status) - return status; - } + status = HAL_I2C_Mem_Write(i2c_handle, M24C32_I2C_ADDR, + mem_address + bytes_written, 2, + &data[bytes_written], write_size, + 1000); + if (status) + return status; + } - return HAL_OK; + return HAL_OK; } HAL_StatusTypeDef eeprom_read(uint16_t mem_address, uint8_t *data, - uint16_t size) { - HAL_StatusTypeDef status; + uint16_t size) +{ + HAL_StatusTypeDef status; - for (int bytes_read = 0; bytes_read < size; bytes_read += 32) { - uint16_t read_size = check_size(size - bytes_read); + for (int bytes_read = 0; bytes_read < size; bytes_read += 32) { + uint16_t read_size = check_size(size - bytes_read); - status = - HAL_I2C_Mem_Read(i2c_handle, M24C32_I2C_ADDR, mem_address + bytes_read, - 2, &data[bytes_read], read_size, 1000); - if (status) - return status; - } + status = HAL_I2C_Mem_Read(i2c_handle, M24C32_I2C_ADDR, + mem_address + bytes_read, 2, + &data[bytes_read], read_size, 1000); + if (status) + return status; + } - return HAL_OK; + return HAL_OK; } -HAL_StatusTypeDef eeprom_delete(uint16_t mem_address, uint16_t size) { - HAL_StatusTypeDef status; +HAL_StatusTypeDef eeprom_delete(uint16_t mem_address, uint16_t size) +{ + HAL_StatusTypeDef status; - // Create a list of zeroes that will be written to the EEPROM - uint8_t data[size]; - memset(data, 0, size); + // Create a list of zeroes that will be written to the EEPROM + uint8_t data[size]; + memset(data, 0, size); - for (int bytes_deleted = 0; bytes_deleted < size; bytes_deleted += 32) { - uint16_t delete_size = check_size(size - bytes_deleted); + for (int bytes_deleted = 0; bytes_deleted < size; bytes_deleted += 32) { + uint16_t delete_size = check_size(size - bytes_deleted); - // Write 0 to memory addresses - status = HAL_I2C_Mem_Write(i2c_handle, M24C32_I2C_ADDR, - mem_address + bytes_deleted, 2, - &data[bytes_deleted], delete_size, 1000); - if (status) - return status; - } + // Write 0 to memory addresses + status = HAL_I2C_Mem_Write(i2c_handle, M24C32_I2C_ADDR, + mem_address + bytes_deleted, 2, + &data[bytes_deleted], delete_size, + 1000); + if (status) + return status; + } - return HAL_OK; + return HAL_OK; } \ No newline at end of file diff --git a/general/src/max7314.c b/general/src/max7314.c index 08fc59b..2d00b5a 100644 --- a/general/src/max7314.c +++ b/general/src/max7314.c @@ -1,159 +1,171 @@ #include "max7314.h" -#define MAX7314_INPUT_PORTS_0_TO_7 0x00 -#define MAX7314_INPUT_PORTS_8_TO_15 0x01 -#define MAX7314_PHASE_0_OUTPUTS_0_7 0x02 +#define MAX7314_INPUT_PORTS_0_TO_7 0x00 +#define MAX7314_INPUT_PORTS_8_TO_15 0x01 +#define MAX7314_PHASE_0_OUTPUTS_0_7 0x02 #define MAX7314_PHASE_0_OUTPUTS_8_15 0x03 -#define MAX7314_PORT_CONFIG_0_TO_7 0x06 -#define MAX7314_PORT_CONFIG_8_TO_15 0x07 -#define MAX7314_MASTER_INTENSITY 0x0E -#define MAX7314_CONFIG_REG 0x0F -#define FIRST_OUTPUT_REGISTER 0x10 +#define MAX7314_PORT_CONFIG_0_TO_7 0x06 +#define MAX7314_PORT_CONFIG_8_TO_15 0x07 +#define MAX7314_MASTER_INTENSITY 0x0E +#define MAX7314_CONFIG_REG 0x0F +#define FIRST_OUTPUT_REGISTER 0x10 -#define REG_SIZE 1 // byte +#define REG_SIZE 1 // byte #define REG_SIZE_BITS 8 // bit -#define TIMEOUT 2000 +#define TIMEOUT 2000 -HAL_StatusTypeDef read_reg(max7314_t *max, uint16_t address, uint8_t *data) { - return HAL_I2C_Mem_Read(max->i2c_handle, max->dev_addr, address, - I2C_MEMADD_SIZE_8BIT, data, REG_SIZE, TIMEOUT); +HAL_StatusTypeDef read_reg(max7314_t *max, uint16_t address, uint8_t *data) +{ + return HAL_I2C_Mem_Read(max->i2c_handle, max->dev_addr, address, + I2C_MEMADD_SIZE_8BIT, data, REG_SIZE, TIMEOUT); } -HAL_StatusTypeDef write_reg(max7314_t *max, uint16_t address, uint8_t *data) { - return HAL_I2C_Mem_Write(max->i2c_handle, max->dev_addr, address, - I2C_MEMADD_SIZE_8BIT, data, REG_SIZE, TIMEOUT); +HAL_StatusTypeDef write_reg(max7314_t *max, uint16_t address, uint8_t *data) +{ + return HAL_I2C_Mem_Write(max->i2c_handle, max->dev_addr, address, + I2C_MEMADD_SIZE_8BIT, data, REG_SIZE, TIMEOUT); } -HAL_StatusTypeDef write_word(max7314_t *max, uint16_t address, uint8_t *data) { - return HAL_I2C_Mem_Write(max->i2c_handle, max->dev_addr, address, - I2C_MEMADD_SIZE_8BIT, data, REG_SIZE * 2, TIMEOUT); +HAL_StatusTypeDef write_word(max7314_t *max, uint16_t address, uint8_t *data) +{ + return HAL_I2C_Mem_Write(max->i2c_handle, max->dev_addr, address, + I2C_MEMADD_SIZE_8BIT, data, REG_SIZE * 2, + TIMEOUT); } -void max7314_init(max7314_t *max, I2C_HandleTypeDef *i2c_handle) { - max->i2c_handle = i2c_handle; - max->dev_addr = max->dev_addr - << 1u; /* shifted one to the left cuz STM says so */ +void max7314_init(max7314_t *max, I2C_HandleTypeDef *i2c_handle) +{ + max->i2c_handle = i2c_handle; + max->dev_addr = max->dev_addr + << 1u; /* shifted one to the left cuz STM says so */ - uint8_t turn_off = 0b11110000; - write_reg(max, MAX7314_PHASE_0_OUTPUTS_0_7, &turn_off); + uint8_t turn_off = 0b11110000; + write_reg(max, MAX7314_PHASE_0_OUTPUTS_0_7, &turn_off); } -HAL_StatusTypeDef max7314_set_global_intensity(max7314_t *max, uint8_t level) { +HAL_StatusTypeDef max7314_set_global_intensity(max7314_t *max, uint8_t level) +{ + HAL_StatusTypeDef status; + uint8_t master_intensity; - HAL_StatusTypeDef status; - uint8_t master_intensity; + if (level == 0) { + master_intensity = 0x00; + } else { + master_intensity = 0xFF; + } - if (level == 0) { - master_intensity = 0x00; - } else { - master_intensity = 0xFF; - } + status = write_reg(max, MAX7314_MASTER_INTENSITY, &master_intensity); + if (status != HAL_OK) { + return status; + } - status = write_reg(max, MAX7314_MASTER_INTENSITY, &master_intensity); - if (status != HAL_OK) { - return status; - } - - return HAL_OK; + return HAL_OK; } -HAL_StatusTypeDef max7314_write_config(max7314_t *max, uint8_t *config) { - return write_reg(max, MAX7314_CONFIG_REG, config); +HAL_StatusTypeDef max7314_write_config(max7314_t *max, uint8_t *config) +{ + return write_reg(max, MAX7314_CONFIG_REG, config); } HAL_StatusTypeDef max7314_set_pin_mode(max7314_t *max, uint8_t pin, - uint8_t mode) { - uint8_t conf_data; - HAL_StatusTypeDef status; - - if (pin < 7) { - /* Read current port configuration */ - status = read_reg(max, MAX7314_PHASE_0_OUTPUTS_0_7, &conf_data); - if (status != HAL_OK) - return status; - - /* Change port configuration of desired pin. Bit manip sets one bit to mode. + uint8_t mode) +{ + uint8_t conf_data; + HAL_StatusTypeDef status; + + if (pin < 7) { + /* Read current port configuration */ + status = read_reg(max, MAX7314_PHASE_0_OUTPUTS_0_7, &conf_data); + if (status != HAL_OK) + return status; + + /* Change port configuration of desired pin. Bit manip sets one bit to mode. */ - conf_data = (conf_data & ~(1u << pin)) | (mode << pin); - status = write_reg(max, MAX7314_PHASE_0_OUTPUTS_0_7, &conf_data); - if (status != HAL_OK) - return status; - - } else { - /* Same as above but for different register */ - status = read_reg(max, MAX7314_PHASE_0_OUTPUTS_8_15, &conf_data); - if (status != HAL_OK) - return status; - - conf_data = (conf_data & ~(1u << (pin - REG_SIZE_BITS))) | - (mode << (pin - REG_SIZE_BITS)); - status = write_reg(max, MAX7314_PHASE_0_OUTPUTS_8_15, &conf_data); - if (status != HAL_OK) - return status; - } - - return HAL_OK; + conf_data = (conf_data & ~(1u << pin)) | (mode << pin); + status = + write_reg(max, MAX7314_PHASE_0_OUTPUTS_0_7, &conf_data); + if (status != HAL_OK) + return status; + + } else { + /* Same as above but for different register */ + status = + read_reg(max, MAX7314_PHASE_0_OUTPUTS_8_15, &conf_data); + if (status != HAL_OK) + return status; + + conf_data = (conf_data & ~(1u << (pin - REG_SIZE_BITS))) | + (mode << (pin - REG_SIZE_BITS)); + status = write_reg(max, MAX7314_PHASE_0_OUTPUTS_8_15, + &conf_data); + if (status != HAL_OK) + return status; + } + + return HAL_OK; } -HAL_StatusTypeDef max7314_set_pin_modes(max7314_t *max, uint8_t *pin_configs) { - return write_word(max, MAX7314_PORT_CONFIG_0_TO_7, pin_configs); +HAL_StatusTypeDef max7314_set_pin_modes(max7314_t *max, uint8_t *pin_configs) +{ + return write_word(max, MAX7314_PORT_CONFIG_0_TO_7, pin_configs); } -HAL_StatusTypeDef max7314_read_pin(max7314_t *max, uint8_t pin, bool *state) { - uint8_t pin_data; - HAL_StatusTypeDef status; +HAL_StatusTypeDef max7314_read_pin(max7314_t *max, uint8_t pin, bool *state) +{ + uint8_t pin_data; + HAL_StatusTypeDef status; - if (pin < 8) { - /* similar to set_pin_mode */ - status = read_reg(max, MAX7314_INPUT_PORTS_0_TO_7, &pin_data); - if (status != HAL_OK) - return status; + if (pin < 8) { + /* similar to set_pin_mode */ + status = read_reg(max, MAX7314_INPUT_PORTS_0_TO_7, &pin_data); + if (status != HAL_OK) + return status; - *state = (pin_data & (0b1 << pin)) > 0; - } else { - status = read_reg(max, MAX7314_INPUT_PORTS_8_TO_15, &pin_data); - if (status != HAL_OK) - return status; + *state = (pin_data & (0b1 << pin)) > 0; + } else { + status = read_reg(max, MAX7314_INPUT_PORTS_8_TO_15, &pin_data); + if (status != HAL_OK) + return status; - *state = (pin_data & (0b1 << (pin - REG_SIZE_BITS))) > 0; - } + *state = (pin_data & (0b1 << (pin - REG_SIZE_BITS))) > 0; + } - return HAL_OK; + return HAL_OK; } /* PHASE 0 OUTPUT BIT 1: PIN HIGH NOT PULLED DOWN */ /* PHASE 0 OUTPUT BIT 0: PIN LOW PULLED DOWN */ -HAL_StatusTypeDef max7314_set_pin_state(max7314_t *max, uint8_t pin, - bool state) { - uint8_t pin_data; - HAL_StatusTypeDef status; - uint8_t reg = MAX7314_PHASE_0_OUTPUTS_0_7; - uint8_t pin_state; - - if (pin > 7) { - reg += 1; - } - - if (state) { - pin_state = 1; - } else { - pin_state = 0; - } - - status = read_reg(max, reg, &pin_data); - if (status != HAL_OK) - return status; - - /* Clear bit at position, then set it to state*/ - if (pin < 8) { - pin_data = (pin_data & ~(1u << pin)) | (pin_state << pin); - } else { - pin_data = (pin_data & ~(1u << (pin - REG_SIZE_BITS))) | - (pin_state << (pin - REG_SIZE_BITS)); - } - - // /* Write to register containing the desired pin */ - status = write_reg(max, reg, &pin_data); - - return HAL_OK; +HAL_StatusTypeDef max7314_set_pin_state(max7314_t *max, uint8_t pin, bool state) +{ + uint8_t pin_data; + HAL_StatusTypeDef status; + uint8_t reg = MAX7314_PHASE_0_OUTPUTS_0_7; + uint8_t pin_state; + + if (pin > 7) { + reg += 1; + } + + if (state) { + pin_state = 1; + } else { + pin_state = 0; + } + + status = read_reg(max, reg, &pin_data); + if (status != HAL_OK) + return status; + + /* Clear bit at position, then set it to state*/ + if (pin < 8) { + pin_data = (pin_data & ~(1u << pin)) | (pin_state << pin); + } else { + pin_data = (pin_data & ~(1u << (pin - REG_SIZE_BITS))) | + (pin_state << (pin - REG_SIZE_BITS)); + } + + // /* Write to register containing the desired pin */ + status = write_reg(max, reg, &pin_data); + + return HAL_OK; } diff --git a/general/src/mcp23008.c b/general/src/mcp23008.c index e823dc5..0e63ea6 100644 --- a/general/src/mcp23008.c +++ b/general/src/mcp23008.c @@ -8,28 +8,28 @@ #include "mcp23008.h" -#define MCP23008_I2C_ADDR 0x20 -#define IO_CONFIG_REG 0x00 -#define IO_CONFIG_OUTPUT 0x00 /* = 0000 0000, all output */ -#define IO_CONFIG_INPUT 0xFF /* = 1111 1111, all input */ -#define INPUT_REG 0x09 +#define MCP23008_I2C_ADDR 0x20 +#define IO_CONFIG_REG 0x00 +#define IO_CONFIG_OUTPUT 0x00 /* = 0000 0000, all output */ +#define IO_CONFIG_INPUT 0xFF /* = 1111 1111, all input */ +#define INPUT_REG 0x09 int mcp23008_init(mcp23008_t *obj, write_ptr write_func, read_ptr read_func) { - obj->write = write_func; - obj->read = read_func; + obj->write = write_func; + obj->read = read_func; - uint8_t buf[2] = {IO_CONFIG_REG, IO_CONFIG_OUTPUT}; - return obj->write(MCP23008_I2C_ADDR, buf, 2); + uint8_t buf[2] = { IO_CONFIG_REG, IO_CONFIG_OUTPUT }; + return obj->write(MCP23008_I2C_ADDR, buf, 2); } int mcp23008_write_reg(mcp23008_t *obj, uint8_t reg, uint8_t val) { - uint8_t buf[2] = {reg, val}; - return obj->write(MCP23008_I2C_ADDR, buf, 2); + uint8_t buf[2] = { reg, val }; + return obj->write(MCP23008_I2C_ADDR, buf, 2); } int mcp23008_read_reg(mcp23008_t *obj, uint8_t reg, uint8_t *val) { - return obj->read(MCP23008_I2C_ADDR, val, 1); + return obj->read(MCP23008_I2C_ADDR, val, 1); } \ No newline at end of file diff --git a/general/src/pca9539.c b/general/src/pca9539.c index 3fb340e..6e62f2f 100644 --- a/general/src/pca9539.c +++ b/general/src/pca9539.c @@ -4,68 +4,70 @@ #define REG_SIZE_BITS 8 -HAL_StatusTypeDef pca_write_reg(pca9539_t *pca, uint16_t address, - uint8_t *data) { - // ensure shifting left one, HAL adds the write bit - return HAL_I2C_Mem_Write(pca->i2c_handle, pca->dev_addr, address, - I2C_MEMADD_SIZE_8BIT, data, 1, HAL_MAX_DELAY); +HAL_StatusTypeDef pca_write_reg(pca9539_t *pca, uint16_t address, uint8_t *data) +{ + // ensure shifting left one, HAL adds the write bit + return HAL_I2C_Mem_Write(pca->i2c_handle, pca->dev_addr, address, + I2C_MEMADD_SIZE_8BIT, data, 1, HAL_MAX_DELAY); } -HAL_StatusTypeDef pca_read_reg(pca9539_t *pca, uint16_t address, - uint8_t *data) { - - return HAL_I2C_Mem_Read(pca->i2c_handle, pca->dev_addr, address, - I2C_MEMADD_SIZE_8BIT, data, 1, HAL_MAX_DELAY); +HAL_StatusTypeDef pca_read_reg(pca9539_t *pca, uint16_t address, uint8_t *data) +{ + return HAL_I2C_Mem_Read(pca->i2c_handle, pca->dev_addr, address, + I2C_MEMADD_SIZE_8BIT, data, 1, HAL_MAX_DELAY); } void pca9539_init(pca9539_t *pca, I2C_HandleTypeDef *i2c_handle, - uint8_t dev_addr) { - pca->i2c_handle = i2c_handle; - pca->dev_addr = dev_addr << 1u; /* shifted one to the left cuz STM says so */ + uint8_t dev_addr) +{ + pca->i2c_handle = i2c_handle; + pca->dev_addr = dev_addr + << 1u; /* shifted one to the left cuz STM says so */ } HAL_StatusTypeDef pca9539_read_reg(pca9539_t *pca, uint8_t reg_type, - uint8_t *buf) { - - HAL_StatusTypeDef status = pca_read_reg(pca, reg_type, buf); - if (status) { - return status; - } - - return status; + uint8_t *buf) +{ + HAL_StatusTypeDef status = pca_read_reg(pca, reg_type, buf); + if (status) { + return status; + } + + return status; } HAL_StatusTypeDef pca9539_read_pin(pca9539_t *pca, uint8_t reg_type, - uint8_t pin, uint8_t *buf) { - uint8_t data; - HAL_StatusTypeDef status = pca_read_reg(pca, reg_type, &data); - if (status) { - return status; - } + uint8_t pin, uint8_t *buf) +{ + uint8_t data; + HAL_StatusTypeDef status = pca_read_reg(pca, reg_type, &data); + if (status) { + return status; + } - *buf = (data & (1 << pin)) > 0; + *buf = (data & (1 << pin)) > 0; - return status; + return status; } HAL_StatusTypeDef pca9539_write_reg(pca9539_t *pca, uint8_t reg_type, - uint8_t buf) { - - return pca_write_reg(pca, reg_type, &buf); + uint8_t buf) +{ + return pca_write_reg(pca, reg_type, &buf); } HAL_StatusTypeDef pca9539_write_pin(pca9539_t *pca, uint8_t reg_type, - uint8_t pin, uint8_t buf) { - - uint8_t data; - uint8_t data_new; + uint8_t pin, uint8_t buf) +{ + uint8_t data; + uint8_t data_new; - HAL_StatusTypeDef status = pca_read_reg(pca, reg_type, &data); - if (status) { - return status; - } + HAL_StatusTypeDef status = pca_read_reg(pca, reg_type, &data); + if (status) { + return status; + } - data_new = (data & ~(1u << pin)) | (buf << pin); + data_new = (data & ~(1u << pin)) | (buf << pin); - return pca_write_reg(pca, reg_type, &data_new); + return pca_write_reg(pca, reg_type, &data_new); } diff --git a/general/src/pi4ioe.c b/general/src/pi4ioe.c index 4fad4af..0199eb2 100644 --- a/general/src/pi4ioe.c +++ b/general/src/pi4ioe.c @@ -11,60 +11,61 @@ // and remove this comment the values should be correct though, just the order // is wrong -#define PI4IOE_I2C_ADDR \ - 0x20 //? @hamza does HAL driver handle shifting for read/write bit - //automatically? if not should be added here +#define PI4IOE_I2C_ADDR 0x20 #define IO_CONFIG_REG 0x06 #define IO_CONFIG_BUF 0x10 /* = 0001 0000, bit 4 = TSMS = input */ -#define INPUT0_REG 0x00 -#define INPUT1_REG 0x01 -#define OUTPUT0_REG 0x02 -#define OUTPUT1_REG 0x03 +#define INPUT0_REG 0x00 +#define INPUT1_REG 0x01 +#define OUTPUT0_REG 0x02 +#define OUTPUT1_REG 0x03 uint8_t oreg_1_data; uint8_t oreg_2_data; -HAL_StatusTypeDef pi4ioe_init(pi4ioe_t *gpio, I2C_HandleTypeDef *i2c_handle) { - gpio->i2c_handle = i2c_handle; - gpio->port_config = IO_CONFIG_BUF; +HAL_StatusTypeDef pi4ioe_init(pi4ioe_t *gpio, I2C_HandleTypeDef *i2c_handle) +{ + gpio->i2c_handle = i2c_handle; + gpio->port_config = IO_CONFIG_BUF; - oreg_1_data = 0x00; - oreg_2_data = 0x00; + oreg_1_data = 0x00; + oreg_2_data = 0x00; - uint8_t buf[2] = {IO_CONFIG_REG, IO_CONFIG_BUF}; + uint8_t buf[2] = { IO_CONFIG_REG, IO_CONFIG_BUF }; - /* write to config reg setting TSMS to input, rest to output */ - return HAL_I2C_Master_Transmit(i2c_handle, PI4IOE_I2C_ADDR, buf, 2, - HAL_MAX_DELAY); + /* write to config reg setting TSMS to input, rest to output */ + return HAL_I2C_Master_Transmit(i2c_handle, PI4IOE_I2C_ADDR, buf, 2, + HAL_MAX_DELAY); } HAL_StatusTypeDef pi4ioe_write(uint8_t device, uint8_t val, - I2C_HandleTypeDef *i2c_handle) { + I2C_HandleTypeDef *i2c_handle) +{ + uint8_t reg; + uint8_t *oreg_data; - uint8_t reg; - uint8_t *oreg_data; + if (device > 7) { + reg = OUTPUT1_REG; + oreg_data = &oreg_1_data; + } else { + reg = OUTPUT0_REG; + oreg_data = &oreg_2_data; + } - if (device > 7) { - reg = OUTPUT1_REG; - oreg_data = &oreg_1_data; - } else { - reg = OUTPUT0_REG; - oreg_data = &oreg_2_data; - } + *oreg_data |= val << device; - *oreg_data |= val << device; + uint8_t buf[2] = { reg, *oreg_data }; - uint8_t buf[2] = {reg, *oreg_data}; - - return HAL_I2C_Master_Transmit(i2c_handle, PI4IOE_I2C_ADDR, buf, 2, - HAL_MAX_DELAY); + return HAL_I2C_Master_Transmit(i2c_handle, PI4IOE_I2C_ADDR, buf, 2, + HAL_MAX_DELAY); } -HAL_StatusTypeDef pi4ioe_read(uint8_t *buf, I2C_HandleTypeDef *i2c_handle) { - uint8_t reg = INPUT0_REG; +HAL_StatusTypeDef pi4ioe_read(uint8_t *buf, I2C_HandleTypeDef *i2c_handle) +{ + uint8_t reg = INPUT0_REG; - HAL_I2C_Master_Transmit(i2c_handle, PI4IOE_I2C_ADDR, ®, 1, HAL_MAX_DELAY); - return HAL_I2C_Master_Receive(i2c_handle, PI4IOE_I2C_ADDR, buf, 2, - HAL_MAX_DELAY); + HAL_I2C_Master_Transmit(i2c_handle, PI4IOE_I2C_ADDR, ®, 1, + HAL_MAX_DELAY); + return HAL_I2C_Master_Receive(i2c_handle, PI4IOE_I2C_ADDR, buf, 2, + HAL_MAX_DELAY); } diff --git a/general/src/sht30.c b/general/src/sht30.c index 9f69ac6..59a442c 100644 --- a/general/src/sht30.c +++ b/general/src/sht30.c @@ -2,112 +2,118 @@ #include #include -static HAL_StatusTypeDef sht30_write_reg(sht30_t *sht30, uint16_t command) { - uint8_t command_buffer[2] = {(command & 0xff00u) >> 8u, command & 0xffu}; - - if (HAL_I2C_Master_Transmit(sht30->i2c_handle, SHT30_I2C_ADDR, command_buffer, - sizeof(command_buffer), 30) != HAL_OK) { - return false; - } - - return true; +static HAL_StatusTypeDef sht30_write_reg(sht30_t *sht30, uint16_t command) +{ + uint8_t command_buffer[2] = { (command & 0xff00u) >> 8u, + command & 0xffu }; + + if (HAL_I2C_Master_Transmit(sht30->i2c_handle, SHT30_I2C_ADDR, + command_buffer, sizeof(command_buffer), + 30) != HAL_OK) { + return false; + } + + return true; } /** * @brief Calculates the CRC by using the polynomial x^8 + x^5 + x^4 + 1 * @param data: the data to use to calculate the CRC */ -static uint8_t calculate_crc(const uint8_t *data, size_t length) { - uint8_t crc = 0xff; - for (size_t i = 0; i < length; i++) { - crc ^= data[i]; - for (size_t j = 0; j < 8; j++) { - if ((crc & 0x80u) != 0) { - crc = (uint8_t)((uint8_t)(crc << 1u) ^ 0x31u); - } else { - crc <<= 1u; - } - } - } - return crc; +static uint8_t calculate_crc(const uint8_t *data, size_t length) +{ + uint8_t crc = 0xff; + for (size_t i = 0; i < length; i++) { + crc ^= data[i]; + for (size_t j = 0; j < 8; j++) { + if ((crc & 0x80u) != 0) { + crc = (uint8_t)((uint8_t)(crc << 1u) ^ 0x31u); + } else { + crc <<= 1u; + } + } + } + return crc; } -static uint16_t uint8_to_uint16(uint8_t msb, uint8_t lsb) { - return (uint16_t)((uint16_t)msb << 8u) | lsb; +static uint16_t uint8_to_uint16(uint8_t msb, uint8_t lsb) +{ + return (uint16_t)((uint16_t)msb << 8u) | lsb; } -HAL_StatusTypeDef sht30_init(sht30_t *sht30) { - HAL_StatusTypeDef status = HAL_OK; +HAL_StatusTypeDef sht30_init(sht30_t *sht30) +{ + HAL_StatusTypeDef status = HAL_OK; - uint8_t status_reg_and_checksum[3]; - if (HAL_I2C_Mem_Read(sht30->i2c_handle, SHT30_I2C_ADDR, - SHT3X_COMMAND_READ_STATUS, 2, - (uint8_t *)&status_reg_and_checksum, - sizeof(status_reg_and_checksum), 30) != HAL_OK) { - return false; - } + uint8_t status_reg_and_checksum[3]; + if (HAL_I2C_Mem_Read(sht30->i2c_handle, SHT30_I2C_ADDR, + SHT3X_COMMAND_READ_STATUS, 2, + (uint8_t *)&status_reg_and_checksum, + sizeof(status_reg_and_checksum), 30) != HAL_OK) { + return false; + } - uint8_t calculated_crc = calculate_crc(status_reg_and_checksum, 2); + uint8_t calculated_crc = calculate_crc(status_reg_and_checksum, 2); - if (calculated_crc != status_reg_and_checksum[2]) { - return false; - } + if (calculated_crc != status_reg_and_checksum[2]) { + return false; + } - return status; + return status; } -HAL_StatusTypeDef sht30_toggle_heater(sht30_t *sht30, bool enable) { - if (enable) { - return sht30_write_reg(sht30, SHT3X_COMMAND_HEATER_ENABLE); - } else { - return sht30_write_reg(sht30, SHT3X_COMMAND_HEATER_DISABLE); - } +HAL_StatusTypeDef sht30_toggle_heater(sht30_t *sht30, bool enable) +{ + if (enable) { + return sht30_write_reg(sht30, SHT3X_COMMAND_HEATER_ENABLE); + } else { + return sht30_write_reg(sht30, SHT3X_COMMAND_HEATER_DISABLE); + } } -HAL_StatusTypeDef sht30_get_temp_humid(sht30_t *sht30) { - HAL_StatusTypeDef status; +HAL_StatusTypeDef sht30_get_temp_humid(sht30_t *sht30) +{ + HAL_StatusTypeDef status; - union { - struct __attribute__((packed)) { - uint16_t - temp; // The packed attribute does not correctly arrange the bytes - uint8_t temp_crc; - uint16_t - humidity; // The packed attribute does not correctly arrange the bytes - uint8_t humidity_crc; - } raw_data; - uint8_t databuf[6]; - } data; + union { + struct __attribute__((packed)) { + uint16_t temp; // The packed attribute does not correctly arrange the bytes + uint8_t temp_crc; + uint16_t humidity; // The packed attribute does not correctly arrange the bytes + uint8_t humidity_crc; + } raw_data; + uint8_t databuf[6]; + } data; - uint16_t temp, humidity; + uint16_t temp, humidity; - sht30_write_reg(sht30, (SHT30_START_CMD_WCS)); + sht30_write_reg(sht30, (SHT30_START_CMD_WCS)); - HAL_Delay(1); + HAL_Delay(1); - status = HAL_I2C_Master_Receive(sht30->i2c_handle, SHT30_I2C_ADDR, - data.databuf, sizeof(data.databuf), 30); - if (status != HAL_OK) { - return false; - } + status = HAL_I2C_Master_Receive(sht30->i2c_handle, SHT30_I2C_ADDR, + data.databuf, sizeof(data.databuf), 30); + if (status != HAL_OK) { + return false; + } - temp = uint8_to_uint16(data.databuf[0], data.databuf[1]); + temp = uint8_to_uint16(data.databuf[0], data.databuf[1]); - if (data.raw_data.temp_crc != calculate_crc(data.databuf, 2)) { - return HAL_ERROR; - } + if (data.raw_data.temp_crc != calculate_crc(data.databuf, 2)) { + return HAL_ERROR; + } - float val = -45.0f + 175.0f * (float)temp / 65535.0f; + float val = -45.0f + 175.0f * (float)temp / 65535.0f; - sht30->temp = (uint16_t)val; + sht30->temp = (uint16_t)val; - humidity = uint8_to_uint16(data.databuf[3], data.databuf[4]); - if (data.raw_data.humidity_crc != calculate_crc(data.databuf + 3, 2)) { - return HAL_ERROR; - } + humidity = uint8_to_uint16(data.databuf[3], data.databuf[4]); + if (data.raw_data.humidity_crc != calculate_crc(data.databuf + 3, 2)) { + return HAL_ERROR; + } - humidity = (uint16_t)(100.0f * (float)humidity / 65535.0f); - sht30->humidity = humidity; + humidity = (uint16_t)(100.0f * (float)humidity / 65535.0f); + sht30->humidity = humidity; - return HAL_OK; -} \ No newline at end of file + return HAL_OK; +} diff --git a/load_alias.py b/load_alias.py deleted file mode 100644 index c98cae2..0000000 --- a/load_alias.py +++ /dev/null @@ -1,65 +0,0 @@ -import os -import platform -import sys - -def load_aliases(venv_path, aliases_file): - os_type = platform.system() - if os_type == 'Windows': - activate_path = os.path.join(venv_path, 'Scripts', 'activate') # Bash script for Git Bash on Windows - else: - activate_path = os.path.join(venv_path, 'bin', 'activate') # bash script for Unix-like systems - - try: - # Read existing aliases from the activation script - if os.path.exists(activate_path): - with open(activate_path, 'r') as activate_file: - existing_aliases = activate_file.readlines() - else: - existing_aliases = [] - - # Convert the existing aliases to a set for easy comparison - existing_aliases_set = set() - for line in existing_aliases: - if line.startswith('alias '): - alias_definition = line.strip() - alias_name = alias_definition.split('=')[0].replace('alias ', '') - existing_aliases_set.add(alias_name) - - # Read aliases from the provided aliases file - with open(aliases_file, 'r') as f: - aliases = f.readlines() - - # Prepare to write new aliases that aren't already in the activate script - new_aliases = [] - for alias in aliases: - alias_name, alias_command = alias.strip().split('=', 1) - alias_name = alias_name.strip() - alias_command = alias_command.strip('"') - - if alias_name not in existing_aliases_set: - new_aliases.append(f'alias {alias_name}="{alias_command}"\n') - - # Append new aliases to the activation script if there are any - if new_aliases: - with open(activate_path, 'a') as activate_file: - activate_file.write('\n# Aliases\n') - activate_file.writelines(new_aliases) - print(f"Added {len(new_aliases)} new alias(es) to the activation script.") - else: - print("No new aliases to add; all are already present.") - - except Exception as e: - print(f"Failed to update aliases: {e}", file=sys.stderr) - sys.exit(1) - -def main(): - current_directory = os.path.dirname(os.path.abspath(__file__)) - parent_directory = os.path.dirname(current_directory) - venv_path = os.path.join(parent_directory, 'ner-venv') - aliases_file = os.path.join(current_directory, 'aliases.txt') - - load_aliases(venv_path, aliases_file) - print("Close and reopen your terminal or the venv for changes to take effect.") - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/middleware/include/c_utils.h b/middleware/include/c_utils.h index 5f94611..832fe17 100644 --- a/middleware/include/c_utils.h +++ b/middleware/include/c_utils.h @@ -5,8 +5,8 @@ * Will retrieve the container of a certain pointer given the container type and * its pointer Trick pulled from Linux Kernel */ -#define CONTAINER_OF(ptr, type, member) \ - ((type *)((char *)(ptr) - offsetof(type, member))) +#define CONTAINER_OF(ptr, type, member) \ + ((type *)((char *)(ptr) - offsetof(type, member))) #endif /* C_UTILS */ diff --git a/middleware/include/eepromdirectory.h b/middleware/include/eepromdirectory.h index d9c44bd..8040076 100644 --- a/middleware/include/eepromdirectory.h +++ b/middleware/include/eepromdirectory.h @@ -4,13 +4,13 @@ #include struct eeprom_partition { - char *id; /* key */ - uint16_t size; /* bytes */ - uint16_t address; /* start address */ + char *id; /* key */ + uint16_t size; /* bytes */ + uint16_t address; /* start address */ }; struct eeprom_partition eeprom_data[NUM_EEPROM_ITEMS]{ - /* ____________KEY________________ _BYTES_ */ + /* ____________KEY________________ _BYTES_ */ }; diff --git a/middleware/include/i2c_utility.h b/middleware/include/i2c_utility.h index 0c87695..e47ad5d 100644 --- a/middleware/include/i2c_utility.h +++ b/middleware/include/i2c_utility.h @@ -8,12 +8,12 @@ #include #define HEX_LABELS "\t 0 1 2 3 4 5 6 7 8 9 a b c d e f\n" -#define SPACING " " // Spacing in between each printed address -#define MAX_TRIALS 3 // Max attempts to probe I2C device -#define TIMEOUT 50 // Max time until function skips -#define HEX 16 // hexadecimal for utoa function -#define BUF_ROWS 8 // Number of rows in the buffer -#define ROW_BYTES 128 // Number of bytes per row +#define SPACING " " // Spacing in between each printed address +#define MAX_TRIALS 3 // Max attempts to probe I2C device +#define TIMEOUT 50 // Max time until function skips +#define HEX 16 // hexadecimal for utoa function +#define BUF_ROWS 8 // Number of rows in the buffer +#define ROW_BYTES 128 // Number of bytes per row /** * @brief Probes all i2c addresses to check if devices are ready. @@ -27,7 +27,7 @@ * @return int */ int i2cdetect(I2C_HandleTypeDef *hi2c, char **buffer, int mode, uint8_t start, - uint8_t end); + uint8_t end); /** * @brief Reads and dumps register data at a given register address and i2c bus. @@ -40,7 +40,7 @@ int i2cdetect(I2C_HandleTypeDef *hi2c, char **buffer, int mode, uint8_t start, * @param end higher range of addresses to dump from */ int i2cdump(I2C_HandleTypeDef *hi2c, uint16_t devAddress, char **buffer, - char mode, uint8_t start, uint8_t end); + char mode, uint8_t start, uint8_t end); /** * @brief Prints the given 2D Array to serial monitor diff --git a/middleware/include/pid.h b/middleware/include/pid.h index 5793d22..ca909d5 100644 --- a/middleware/include/pid.h +++ b/middleware/include/pid.h @@ -5,16 +5,16 @@ #include typedef struct { - float kP, kI, kD; + float kP, kI, kD; - float err_tol; - float err; - float prev_err; - float prev_time; // in seconds - float min_out; - float max_out; + float err_tol; + float err; + float prev_err; + float prev_time; // in seconds + float min_out; + float max_out; - float integral_sum; + float integral_sum; } pid_t; /** @@ -29,7 +29,7 @@ typedef struct { * @return pid_t */ pid_t *pid_init(float kP, float kI, float kD, float err_tol, float min_out, - float max_out); + float max_out); /** * @brief Returns PID output given the setpoint and current state value diff --git a/middleware/include/ringbuffer.h b/middleware/include/ringbuffer.h index 4ac22c1..4961323 100644 --- a/middleware/include/ringbuffer.h +++ b/middleware/include/ringbuffer.h @@ -5,12 +5,12 @@ #include typedef struct { - void **buffer; - size_t capacity; - size_t element_size; - size_t front; - size_t rear; - size_t count; + void **buffer; + size_t capacity; + size_t element_size; + size_t front; + size_t rear; + size_t count; } ringbuffer_t; diff --git a/middleware/include/timer.h b/middleware/include/timer.h index 12fa9a0..b57a8af 100644 --- a/middleware/include/timer.h +++ b/middleware/include/timer.h @@ -5,10 +5,10 @@ #include typedef struct { - uint32_t start_time; - uint32_t end_time; - bool active; - bool completed; + uint32_t start_time; + uint32_t end_time; + bool active; + bool completed; } nertimer_t; /** diff --git a/middleware/src/c_utils.c b/middleware/src/c_utils.c index f805ec3..f0524f4 100644 --- a/middleware/src/c_utils.c +++ b/middleware/src/c_utils.c @@ -1,18 +1,20 @@ #include "c_utils.h" -void endian_swap(void *ptr, int size) { - char *p = (char *)ptr; - char tmp; - for (int i = 0; i < size / 2; i++) { - tmp = p[i]; - p[i] = p[size - i - 1]; - p[size - i - 1] = tmp; - } +void endian_swap(void *ptr, int size) +{ + char *p = (char *)ptr; + char tmp; + for (int i = 0; i < size / 2; i++) { + tmp = p[i]; + p[i] = p[size - i - 1]; + p[size - i - 1] = tmp; + } } -unsigned char reverse_bits(unsigned char b) { - b = (b & 0xF0) >> 4 | (b & 0x0F) << 4; - b = (b & 0xCC) >> 2 | (b & 0x33) << 2; - b = (b & 0xAA) >> 1 | (b & 0x55) << 1; - return b; +unsigned char reverse_bits(unsigned char b) +{ + b = (b & 0xF0) >> 4 | (b & 0x0F) << 4; + b = (b & 0xCC) >> 2 | (b & 0x33) << 2; + b = (b & 0xAA) >> 1 | (b & 0x55) << 1; + return b; } \ No newline at end of file diff --git a/middleware/src/eepromdirectory.c b/middleware/src/eepromdirectory.c index 4bcbdfe..573b96e 100644 --- a/middleware/src/eepromdirectory.c +++ b/middleware/src/eepromdirectory.c @@ -8,91 +8,99 @@ /* function definition for entering parameters of the fault coniditon passing the array of struct to the function */ -void eeprom_init(struct eeprom_partition partition_list[], int array_size) { - eeprom_data[0].address = 0; - eeprom_data[0].size = partition_list[0].size; - eeprom_data[0].id = partition_list[0].id; +void eeprom_init(struct eeprom_partition partition_list[], int array_size) +{ + eeprom_data[0].address = 0; + eeprom_data[0].size = partition_list[0].size; + eeprom_data[0].id = partition_list[0].id; - for (int i = 1; i < array_size; i++) { - eeprom_data[i].id = partition_list[i].id; - eeprom_data[i].size; + for (int i = 1; i < array_size; i++) { + eeprom_data[i].id = partition_list[i].id; + eeprom_data[i].size; - // calculating the address through the logic defined in shepherd - eeprom_data[i].address = - eeprom_data[i - 1].size + eeprom - data[i - 1].address; - } + // calculating the address through the logic defined in shepherd + eeprom_data[i].address = + eeprom_data[i - 1].size + eeprom - data[i - 1].address; + } } -uint16_t eepromGetAddress(char *key) { - /* find the index of the key in the eeprom_data array */ - int i = 0; - while (eeprom_data[i].id != NULL) { - if (eeprom_data[i].id == key) { - return eeprom_data[i].address; - } +uint16_t eepromGetAddress(char *key) +{ + /* find the index of the key in the eeprom_data array */ + int i = 0; + while (eeprom_data[i].id != NULL) { + if (eeprom_data[i].id == key) { + return eeprom_data[i].address; + } - i++; - } - return -1; + i++; + } + return -1; } -uint16_t eeprom_get_index(char *key) { - /* find the index of the key in the eeprom_data array */ - int i = 0; - while (eeprom_data[i].id != NULL) { - if (eeprom_data[i].id == key) { - return i; - } +uint16_t eeprom_get_index(char *key) +{ + /* find the index of the key in the eeprom_data array */ + int i = 0; + while (eeprom_data[i].id != NULL) { + if (eeprom_data[i].id == key) { + return i; + } - i++; - } - return -1; + i++; + } + return -1; } -char *eeprom_get_key(int index) { - /* find the key at the index in the eeprom_data array */ - int i = 0; - while (eeprom_data[i].id != NULL) { - if (eeprom_data[i].address == index) { - return eeprom_data[i].id; - } +char *eeprom_get_key(int index) +{ + /* find the key at the index in the eeprom_data array */ + int i = 0; + while (eeprom_data[i].id != NULL) { + if (eeprom_data[i].address == index) { + return eeprom_data[i].id; + } - i++; - } - return NULL; + i++; + } + return NULL; } -bool eeprom_read_data_key(char *key, void *data, uint16_t size) { - if (!data) { - return false; - } - /* read data from eeprom given key and size */ - int address = eepromGetAddress(key); - eeprom_read(address, data, size); +bool eeprom_read_data_key(char *key, void *data, uint16_t size) +{ + if (!data) { + return false; + } + /* read data from eeprom given key and size */ + int address = eepromGetAddress(key); + eeprom_read(address, data, size); } -bool eeprom_read_data_index(uint16_t address, void *data, uint16_t size) { - if (!data) { - return false; - } - /* read data from eeprom given index */ - eeprom_read(address, data, size); - // EEPROM.get(index, data); // TODO will need update with new eeprom driver +bool eeprom_read_data_index(uint16_t address, void *data, uint16_t size) +{ + if (!data) { + return false; + } + /* read data from eeprom given index */ + eeprom_read(address, data, size); + // EEPROM.get(index, data); // TODO will need update with new eeprom driver } -bool eeprom_write_data_key(char *key, void *data, uint16_t size) { - if (!data) { - return false; - } - /* write data to eeprom given key, offset, and size of data */ - int address = eepromGetAddress(key); - eeprom_write(address, data, size); +bool eeprom_write_data_key(char *key, void *data, uint16_t size) +{ + if (!data) { + return false; + } + /* write data to eeprom given key, offset, and size of data */ + int address = eepromGetAddress(key); + eeprom_write(address, data, size); } -bool eeprom_write_data_index(uint16_t address, void *data, uint16_t size) { - if (!data) { - return false; - } - /* write data to eeprom given page, offset, and size of data */ - eeprom_write(address, data, size); +bool eeprom_write_data_index(uint16_t address, void *data, uint16_t size) +{ + if (!data) { + return false; + } + /* write data to eeprom given page, offset, and size of data */ + eeprom_write(address, data, size); } diff --git a/middleware/src/i2c_utility.c b/middleware/src/i2c_utility.c index 3cb0ca9..34f60b7 100644 --- a/middleware/src/i2c_utility.c +++ b/middleware/src/i2c_utility.c @@ -1,7 +1,7 @@ #include "i2c_utility.h" -char *hex_labels[] = {"00:", "10:", "20:", "30:", "40:", "50:", "60:", "70:", - "80:", "90:", "a0:", "b0:", "c0:", "d0:", "e0:", "f0:"}; +char *hex_labels[] = { "00:", "10:", "20:", "30:", "40:", "50:", "60:", "70:", + "80:", "90:", "a0:", "b0:", "c0:", "d0:", "e0:", "f0:" }; /** * TODO: Implement modes for I2C Communication. @@ -9,60 +9,66 @@ char *hex_labels[] = {"00:", "10:", "20:", "30:", "40:", "50:", "60:", "70:", * TODO: Check for error handling */ int i2cdetect(I2C_HandleTypeDef *hi2c, char **buffer, int mode, uint8_t start, - uint8_t end) { - // Initialize the buffer and local variables - HAL_StatusTypeDef ret; - uint8_t row = 1; - char status[sizeof(uint8_t) * 8 + 1]; - - // Add to the appropriate buffer - buffer[0] = HEX_LABELS; // add labels to the first row of the buffer - - // Loop through each device address from the start to end - for (unsigned int i = 0x00U; i <= 0x70U; i += 0x10U) { - strcat(buffer[row], hex_labels[row - 1]); - for (unsigned int j = 0x00U; j < 0x10U; j += 0x01U) { - uint8_t devAddr = i + j; - // out of range reading - if (devAddr < start || devAddr > end) { - strcpy(status, SPACING); - } - // in range - else { - // Use HAL_I2C_IsDeviceReady - ret = HAL_I2C_IsDeviceReady(hi2c, (devAddr << 1), MAX_TRIALS, TIMEOUT); - - // Device status case - switch (ret) { - case HAL_BUSY: - strcpy(status, "UU"); // the bus is considered busy - break; - case HAL_OK: - utoa(devAddr, status, - HEX); // reads the hexadecimal address and turns it into a string - break; - case HAL_ERROR: - case HAL_TIMEOUT: - default: - strcpy(status, "--"); // no response from device or not found - break; - } - } - - // Add status to the buffer - strcat(buffer[row], SPACING); // spacing for string - strcat(buffer[row], status); // actual status - - // clear char array - memset(status, 0, strlen(status)); - } - // table update - strcat(buffer[row], "\n"); - row++; - } - - // Return normal status - return 0; + uint8_t end) +{ + // Initialize the buffer and local variables + HAL_StatusTypeDef ret; + uint8_t row = 1; + char status[sizeof(uint8_t) * 8 + 1]; + + // Add to the appropriate buffer + buffer[0] = HEX_LABELS; // add labels to the first row of the buffer + + // Loop through each device address from the start to end + for (unsigned int i = 0x00U; i <= 0x70U; i += 0x10U) { + strcat(buffer[row], hex_labels[row - 1]); + for (unsigned int j = 0x00U; j < 0x10U; j += 0x01U) { + uint8_t devAddr = i + j; + // out of range reading + if (devAddr < start || devAddr > end) { + strcpy(status, SPACING); + } + // in range + else { + // Use HAL_I2C_IsDeviceReady + ret = HAL_I2C_IsDeviceReady(hi2c, + (devAddr << 1), + MAX_TRIALS, + TIMEOUT); + + // Device status case + switch (ret) { + case HAL_BUSY: + strcpy(status, + "UU"); // the bus is considered busy + break; + case HAL_OK: + utoa(devAddr, status, + HEX); // reads the hexadecimal address and turns it into a string + break; + case HAL_ERROR: + case HAL_TIMEOUT: + default: + strcpy(status, + "--"); // no response from device or not found + break; + } + } + + // Add status to the buffer + strcat(buffer[row], SPACING); // spacing for string + strcat(buffer[row], status); // actual status + + // clear char array + memset(status, 0, strlen(status)); + } + // table update + strcat(buffer[row], "\n"); + row++; + } + + // Return normal status + return 0; } /** @@ -72,93 +78,99 @@ int i2cdetect(I2C_HandleTypeDef *hi2c, char **buffer, int mode, uint8_t start, * address. (NON-BLOCKING) */ int i2cdump(I2C_HandleTypeDef *hi2c, uint16_t devAddress, char **buffer, - char mode, uint8_t start, uint8_t end) { - // Prepare the buffer - int row = 0; - - // need to read from the given address of a I2C Bus. - switch (mode) { - case 'w': // A word (4 bytes or 32-bit) - buffer[row] = "\t\t0 4 8 b"; - row++; - - uint8_t data1 = 0; - for (unsigned int i = 0x00U; i <= 0xf0U; i += 0x10U) { - buffer[row] = hex_labels[row - 1]; - char data_str[sizeof(char) * 4 + 1]; - - for (unsigned int j = 0x00U; j <= 0x0fU; j += 0x04U) { - uint16_t reg = i + j; - // read memory address - if (HAL_I2C_Mem_Read(hi2c, (devAddress << 1), reg, I2C_MEMADD_SIZE_8BIT, - &data1, 4, HAL_MAX_DELAY) != HAL_OK) { - // error - return HAL_ERROR; - } - - // convert data into char text - utoa(data1, data_str, HEX); - - // display the value from the memory address - strcat(buffer[row], SPACING); - strcat(buffer[row], data_str); - - // reset the string array - memset(data_str, 0, strlen(data_str)); - } - strcat(buffer[row], "\n"); - row++; - } - break; - case 's': // A SMBus Block - break; - case 'i': // I2C Block - break; - case 'b': // Byte sized (default) - default: - // Add the labels to the first row - buffer[row] = HEX_LABELS; - row++; - - uint8_t data = 0; - for (unsigned int i = 0x00U; i <= 0xf0U; i += 0x10U) { - // add the vertical labels - buffer[row] = hex_labels[row - 1]; - char data_str[sizeof(char) * 2 + 1]; - - for (unsigned int j = 0x00U; j <= 0x0fU; j++) { - uint16_t reg = i + j; // get the memory address - // read memory address - if (HAL_I2C_Mem_Read(hi2c, (devAddress << 1), reg, I2C_MEMADD_SIZE_8BIT, - &data, 1, HAL_MAX_DELAY) != HAL_OK) { - // error - return HAL_ERROR; - } - - // Convert data buffer into the char buffer - utoa(data, data_str, HEX); - - // display the value from the memory address - strcat(buffer[row], SPACING); - strcat(buffer[row], data_str); - - // reset the string array - memset(data_str, 0, strlen(data_str)); - } - strcat(buffer[row], "\n"); - row++; - } - break; - } - // nominal return - return HAL_OK; + char mode, uint8_t start, uint8_t end) +{ + // Prepare the buffer + int row = 0; + + // need to read from the given address of a I2C Bus. + switch (mode) { + case 'w': // A word (4 bytes or 32-bit) + buffer[row] = "\t\t0 4 8 b"; + row++; + + uint8_t data1 = 0; + for (unsigned int i = 0x00U; i <= 0xf0U; i += 0x10U) { + buffer[row] = hex_labels[row - 1]; + char data_str[sizeof(char) * 4 + 1]; + + for (unsigned int j = 0x00U; j <= 0x0fU; j += 0x04U) { + uint16_t reg = i + j; + // read memory address + if (HAL_I2C_Mem_Read(hi2c, (devAddress << 1), + reg, I2C_MEMADD_SIZE_8BIT, + &data1, 4, + HAL_MAX_DELAY) != HAL_OK) { + // error + return HAL_ERROR; + } + + // convert data into char text + utoa(data1, data_str, HEX); + + // display the value from the memory address + strcat(buffer[row], SPACING); + strcat(buffer[row], data_str); + + // reset the string array + memset(data_str, 0, strlen(data_str)); + } + strcat(buffer[row], "\n"); + row++; + } + break; + case 's': // A SMBus Block + break; + case 'i': // I2C Block + break; + case 'b': // Byte sized (default) + default: + // Add the labels to the first row + buffer[row] = HEX_LABELS; + row++; + + uint8_t data = 0; + for (unsigned int i = 0x00U; i <= 0xf0U; i += 0x10U) { + // add the vertical labels + buffer[row] = hex_labels[row - 1]; + char data_str[sizeof(char) * 2 + 1]; + + for (unsigned int j = 0x00U; j <= 0x0fU; j++) { + uint16_t reg = i + j; // get the memory address + // read memory address + if (HAL_I2C_Mem_Read(hi2c, (devAddress << 1), + reg, I2C_MEMADD_SIZE_8BIT, + &data, 1, + HAL_MAX_DELAY) != HAL_OK) { + // error + return HAL_ERROR; + } + + // Convert data buffer into the char buffer + utoa(data, data_str, HEX); + + // display the value from the memory address + strcat(buffer[row], SPACING); + strcat(buffer[row], data_str); + + // reset the string array + memset(data_str, 0, strlen(data_str)); + } + strcat(buffer[row], "\n"); + row++; + } + break; + } + // nominal return + return HAL_OK; } /** * @warning serial_print max size is 128 bytes. */ -void printResult(char **buffer, int len) { - for (int i = 0; i < len; i++) { - serial_print(buffer[i]); - } +void printResult(char **buffer, int len) +{ + for (int i = 0; i < len; i++) { + serial_print(buffer[i]); + } } \ No newline at end of file diff --git a/middleware/src/pid.c b/middleware/src/pid.c index dd12112..a139544 100644 --- a/middleware/src/pid.c +++ b/middleware/src/pid.c @@ -1,63 +1,66 @@ #include "pid.h" pid_t *pid_init(float kP, float kI, float kD, float err_tol, float min_out, - float max_out) { - pid_t *pid = malloc(sizeof(pid_t)); - - pid->kP = kP; - pid->kI = kI; - pid->kD = kD; - pid->err_tol = err_tol; - pid->err = 0; - pid->prev_err = 0; - pid->min_out = min_out; - pid->max_out = max_out; - pid->prev_time = (float)HAL_GetTick() / 1000; // convert ms to s - pid->integral_sum = 0; - - return pid; + float max_out) +{ + pid_t *pid = malloc(sizeof(pid_t)); + + pid->kP = kP; + pid->kI = kI; + pid->kD = kD; + pid->err_tol = err_tol; + pid->err = 0; + pid->prev_err = 0; + pid->min_out = min_out; + pid->max_out = max_out; + pid->prev_time = (float)HAL_GetTick() / 1000; // convert ms to s + pid->integral_sum = 0; + + return pid; } -float pid_calculate(pid_t *pid, float setpoint, float measurement) { - float output = 0; - float period = 0; - - // set error - pid->err = setpoint - measurement; - - if (pid->kI > 0 || pid->kD > 0) { - float curr_time = (float)HAL_GetTick() / 1000; - period = curr_time - pid->prev_time; - pid->prev_time = curr_time; - } - - // proportional - if (pid->kP > 0) { - output += pid->kP * pid->err; - } - - // + integral - if (pid->kI > 0) { - // reimann sum - pid->integral_sum = pid->integral_sum + pid->err * period; - output += pid->kI * pid->integral_sum; - } - - // + derivative - if (pid->kD > 0) { - // change in error / change in time - float derivative = (pid->err - pid->prev_err) / period; - output += pid->kD * derivative; - pid->prev_err = pid->err; - } - - // clamped to min_out and max_out - return output < pid->min_out ? pid->min_out - : output > pid->max_out ? pid->max_out - : output; +float pid_calculate(pid_t *pid, float setpoint, float measurement) +{ + float output = 0; + float period = 0; + + // set error + pid->err = setpoint - measurement; + + if (pid->kI > 0 || pid->kD > 0) { + float curr_time = (float)HAL_GetTick() / 1000; + period = curr_time - pid->prev_time; + pid->prev_time = curr_time; + } + + // proportional + if (pid->kP > 0) { + output += pid->kP * pid->err; + } + + // + integral + if (pid->kI > 0) { + // reimann sum + pid->integral_sum = pid->integral_sum + pid->err * period; + output += pid->kI * pid->integral_sum; + } + + // + derivative + if (pid->kD > 0) { + // change in error / change in time + float derivative = (pid->err - pid->prev_err) / period; + output += pid->kD * derivative; + pid->prev_err = pid->err; + } + + // clamped to min_out and max_out + return output < pid->min_out ? pid->min_out : + output > pid->max_out ? pid->max_out : + output; } -bool pid_at_setpoint(pid_t *pid) { - // not using abs function since it converts to int - return (pid->err < 0 ? pid->err * -1.0 : pid->err) < pid->err_tol; +bool pid_at_setpoint(pid_t *pid) +{ + // not using abs function since it converts to int + return (pid->err < 0 ? pid->err * -1.0 : pid->err) < pid->err_tol; } diff --git a/middleware/src/ringbuffer.c b/middleware/src/ringbuffer.c index 2cba370..07bfc3f 100644 --- a/middleware/src/ringbuffer.c +++ b/middleware/src/ringbuffer.c @@ -2,78 +2,88 @@ #include #include -ringbuffer_t *ringbuffer_create(size_t capacity, size_t element_size) { - ringbuffer_t *rb = (ringbuffer_t *)malloc(sizeof(ringbuffer_t)); - if (!rb) { - // Handle memory allocation failure - return NULL; - } - - rb->buffer = calloc(capacity, element_size); - if (!rb->buffer) { - free(rb); - return NULL; - } - - rb->capacity = capacity; - rb->element_size = element_size; - - return rb; +ringbuffer_t *ringbuffer_create(size_t capacity, size_t element_size) +{ + ringbuffer_t *rb = (ringbuffer_t *)malloc(sizeof(ringbuffer_t)); + if (!rb) { + // Handle memory allocation failure + return NULL; + } + + rb->buffer = calloc(capacity, element_size); + if (!rb->buffer) { + free(rb); + return NULL; + } + + rb->capacity = capacity; + rb->element_size = element_size; + + return rb; } -void ringbuffer_destroy(ringbuffer_t *rb) { - // Free each dynamically allocated element - for (size_t i = 0; i < rb->count; i++) { - if (rb->buffer[(rb->front + i) % rb->capacity] != NULL) - free(rb->buffer[(rb->front + i) % rb->capacity]); - } +void ringbuffer_destroy(ringbuffer_t *rb) +{ + // Free each dynamically allocated element + for (size_t i = 0; i < rb->count; i++) { + if (rb->buffer[(rb->front + i) % rb->capacity] != NULL) + free(rb->buffer[(rb->front + i) % rb->capacity]); + } - // Free the buffer of pointers - free(rb->buffer); + // Free the buffer of pointers + free(rb->buffer); - // Free the ringbuffer_t structure - free(rb); + // Free the ringbuffer_t structure + free(rb); } -int ringbuffer_is_empty(ringbuffer_t *rb) { return rb->count == 0; } +int ringbuffer_is_empty(ringbuffer_t *rb) +{ + return rb->count == 0; +} -int ringbuffer_is_full(ringbuffer_t *rb) { return rb->count == rb->capacity; } +int ringbuffer_is_full(ringbuffer_t *rb) +{ + return rb->count == rb->capacity; +} -int ringbuffer_enqueue(ringbuffer_t *rb, void *data) { - if (ringbuffer_is_full(rb)) { - // Buffer is full, cannot enqueue - return -1; - } +int ringbuffer_enqueue(ringbuffer_t *rb, void *data) +{ + if (ringbuffer_is_full(rb)) { + // Buffer is full, cannot enqueue + return -1; + } - // Allocate memory for the new element - rb->buffer[rb->rear] = malloc(rb->element_size); - if (rb->buffer[rb->rear] == NULL) { - // Handle memory allocation failure - return -1; - } + // Allocate memory for the new element + rb->buffer[rb->rear] = malloc(rb->element_size); + if (rb->buffer[rb->rear] == NULL) { + // Handle memory allocation failure + return -1; + } - // Copy the data to the newly allocated memory - memcpy(rb->buffer[rb->rear], data, rb->element_size); + // Copy the data to the newly allocated memory + memcpy(rb->buffer[rb->rear], data, rb->element_size); - rb->rear = (rb->rear + 1) % rb->capacity; - rb->count++; + rb->rear = (rb->rear + 1) % rb->capacity; + rb->count++; - return 0; // Successful enqueue + return 0; // Successful enqueue } -void ringbuffer_dequeue(ringbuffer_t *rb, void *data) { - if (ringbuffer_is_empty(rb)) { - // Buffer is empty, cannot dequeue - data = NULL; - return; - } +void ringbuffer_dequeue(ringbuffer_t *rb, void *data) +{ + if (ringbuffer_is_empty(rb)) { + // Buffer is empty, cannot dequeue + data = NULL; + return; + } - // Copy the data from the buffer - memcpy(data, rb->buffer[rb->front], rb->element_size); + // Copy the data from the buffer + memcpy(data, rb->buffer[rb->front], rb->element_size); - // Free the memory of the dequeued element - free(rb->buffer[rb->front]); + // Free the memory of the dequeued element + free(rb->buffer[rb->front]); - rb->front = (rb->front + 1) % rb->capacity; - rb->count--; + rb->front = (rb->front + 1) % rb->capacity; + rb->count--; } \ No newline at end of file diff --git a/middleware/src/timer.c b/middleware/src/timer.c index 6853e75..efcf2b2 100644 --- a/middleware/src/timer.c +++ b/middleware/src/timer.c @@ -1,27 +1,33 @@ #include "timer.h" -void start_timer(nertimer_t *timer, uint32_t duration) { - /* this function assumes tick set to default 1 ms. Update or use +void start_timer(nertimer_t *timer, uint32_t duration) +{ + /* this function assumes tick set to default 1 ms. Update or use * HAL_GetTickFreq() if not the case */ - timer->start_time = HAL_GetTick(); - timer->end_time = timer->start_time + duration; - timer->active = true; - timer->completed = false; + timer->start_time = HAL_GetTick(); + timer->end_time = timer->start_time + duration; + timer->active = true; + timer->completed = false; } -void cancel_timer(nertimer_t *timer) { - timer->active = false; - timer->completed = false; +void cancel_timer(nertimer_t *timer) +{ + timer->active = false; + timer->completed = false; } -bool is_timer_expired(nertimer_t *timer) { - if (timer->active) { - if (HAL_GetTick() >= timer->end_time) { - timer->active = false; - timer->completed = true; - } - } - return timer->completed; +bool is_timer_expired(nertimer_t *timer) +{ + if (timer->active) { + if (HAL_GetTick() >= timer->end_time) { + timer->active = false; + timer->completed = true; + } + } + return timer->completed; } -bool is_timer_active(nertimer_t *timer) { return timer->active; } \ No newline at end of file +bool is_timer_active(nertimer_t *timer) +{ + return timer->active; +} \ No newline at end of file diff --git a/ner_environment/build_system/__init__.py b/ner_environment/build_system/__init__.py new file mode 100644 index 0000000..7fd3700 --- /dev/null +++ b/ner_environment/build_system/__init__.py @@ -0,0 +1,3 @@ + +from .build_system import app +from . import miniterm \ No newline at end of file diff --git a/ner_environment/build_system/build_system.py b/ner_environment/build_system/build_system.py new file mode 100644 index 0000000..0d13062 --- /dev/null +++ b/ner_environment/build_system/build_system.py @@ -0,0 +1,295 @@ +# ============================================================================== +# Northeastern Electric Racing Firmware Build System +# v0.1 10.07.2024 +# Original Author: Dylan Donahue +# Last Modified: 10.15.2024 by Dylan Donahue +# +# This script defines a custom build system wrapper for our combined docker and python virtual environment build system. +# Provided here is a comprehensive set of commands that allow for the complete interaction with NERs toolset. +# Each command is defined as a function and is called by the main function, and has help messages and configuration options. +# Commands can be run with the virtual environment active by prefixing the command with `ner `. +# +# See more documentation at https://nerdocs.atlassian.net/wiki/spaces/NER/pages/611516420/NER+Build+System +# +# To see a list of available commands and additional configuration options, run `ner --help` +# ============================================================================== +import typer +from rich import print +import platform +import subprocess +import sys +import os +import glob +import time +from pathlib import Path + +# custom modules for functinality that is too large to be included in this script directly +from .miniterm import main as miniterm + +# ============================================================================== +# Typer application setup +# ============================================================================== + +app = typer.Typer(help="Northeastern Electric Racing Firmware Build System", + epilog="For more information, visit https://nerdocs.atlassian.net/wiki/spaces/NER/pages/611516420/NER+Build+System", + add_completion=False) + +def unsupported_option_cb(value:bool): + if value: + print("[bold red] WARNING: the selected option is not currently implemented. This is either because is is an planned or deprecated feature") + raise typer.Exit() + +# ============================================================================== +# Build command +# ============================================================================== + +@app.command(help="Build the project with GCC ARM Toolchain and Make") +def build(profile: str = typer.Option(None, "--profile", "-p", callback=unsupported_option_cb, help="(planned) Specify the build profile (e.g., debug, release)", show_default=True), + clean: bool = typer.Option(False, "--clean", help="Clean the build directory before building", show_default=True)): + + if clean: + command = ["docker", "compose", "run", "--rm", "ner-gcc-arm", "make", "clean"] + else: + command = ["docker", "compose", "run", "--rm", "ner-gcc-arm", "make", f"-j{os.cpu_count()}"] + run_command(command, stream_output=True) + +# ============================================================================== +# Clang command +# ============================================================================== + +@app.command(help="Configure autoformatter settings") +def clang(disable: bool = typer.Option(False, "--disable","-d", help="Disable clang-format"), + enable: bool = typer.Option(False, "--enable", "-e", help="Enable clang-format"), + run: bool = typer.Option(False, "--run", "-r", help="Run clang-format")): + + if disable: + command = ["pre-commit", "uninstall"] + elif enable: + command = ["pre-commit", "install"] + elif run: + command = ["pre-commit", "run", "--all-files"] + else: + print("[bold red] Error: No valid option specified") + sys.exit(1) + + run_command(command) + +# ============================================================================== +# Debug command +# ============================================================================== + +@app.command(help="Start a debug session") +def debug(ftdi: bool = typer.Option(False, "--ftdi", help="Set this flag if the device uses an FTDI chip"), + docker: bool = typer.Option(False, "--docker", callback=unsupported_option_cb, help="(deprecated) Use OpenOCD in the container instead of locally, requires linux")): + + command = ["openocd"] + current_directory = os.getcwd() + + if ftdi: + ftdi_path = os.path.join(current_directory, "Drivers", "Embedded-Base", "ftdi_flash.cfg") + command = command + ["-f", ftdi_path] + else: + command = command + ["-f", "interface/cmsis-dap.cfg"] + + build_directory = os.path.join("build", "*.elf") + elf_files = glob.glob(build_directory) + if not elf_files: + print("[bold red] Error: No ELF file found in ./build/") + sys.exit(1) + + elf_file = os.path.basename(os.path.normpath(elf_files[0])) # Take the first ELF file found + print(f"[bold blue] Found ELF file: [/bold blue] [blue] {elf_file}") + + halt_command = command + ["-f", "flash.cfg", "-f", os.path.join(current_directory, "Drivers", "Embedded-Base", "openocd.cfg"), + "-c", "init", "-c", "reset halt"] + + ocd = subprocess.Popen(halt_command) + time.sleep(1) + + # for some reason the host docker internal thing is broken on linux despite compose being set correctly, hence this hack + # TODO: fix this properly + + gdb_uri = "host.docker.internal" + if platform.system() == "Linux" and is_wsl() == 0: + gdb_uri = "localhost" + + send_command = ["docker", "compose", "run", "--rm", "ner-gcc-arm", "arm-none-eabi-gdb", f"/home/app/build/{elf_file}", "-ex", f"target extended-remote {gdb_uri}:3333"] + + subprocess.run(send_command) + + # make terminal clearer + time.sleep(4) + print("\nKilling openocd...") + ocd.terminate() + time.sleep(1) + +# ============================================================================== +# Flash command +# ============================================================================== + +@app.command(help="Flash the firmware") +def flash(ftdi: bool = typer.Option(False, "--ftdi", help="Set this flag if the device uses an FTDI chip"), + docker: bool = typer.Option(False, "--docker", help="Use OpenOCD in the container instead of locally, requires linux")): + + command = [] + + if docker and ftdi: + print("[bold red] Cannot flash ftdi from docker") + sys.exit(1) + + if docker: + command = ["docker", "compose", "run", "--rm", "ner-gcc-arm"] + + command = command + ["openocd"] + + if ftdi: + current_directory = os.getcwd() + ftdi_path = os.path.join(current_directory, "Drivers", "Embedded-Base", "ftdi_flash.cfg") + command = command + ["-f", ftdi_path] + else: + command = command + ["-f", "interface/cmsis-dap.cfg"] + + + build_directory = os.path.join("build", "*.elf") + elf_files = glob.glob(build_directory) + if not elf_files: + print("[bold red] Error: No ELF file found in ./build/") + sys.exit(1) + + elf_file = elf_files[0] # Take the first ELF file found + print(f"[bold blue] Found ELF file: [/bold blue] [blue] {elf_file}") + + command = command + ["-f", "flash.cfg", "-c", f"program {elf_file} verify reset exit"] + + run_command(command, stream_output=True) + +# ============================================================================== +# Serial command +# ============================================================================== + +@app.command(help="Open UART terminal of conneced device") +def serial(ls: bool = typer.Option(False, "--list", help="Specify the device to connect or disconnect (e.g., /dev/ttyACM0,/dev/ttyUSB0,/dev/ttyUSB1,COM1)"), + device: str = typer.Option("", "--device", "-d", help="Specify the board to connect to")): + + if ls: + miniterm(ls=True, device=device) + else: + miniterm(device=device) + +# ============================================================================== +# Update command +# ============================================================================== + +@app.command(help="Update the ner_environment package") +def update(): + + dir = os.getcwd() + if "bedded" in dir: + command = ["pip", "install", "-e", "ner_environment"] + + else: + # app folder - go up one level to root + if os.path.exists(os.path.join(dir, "Drivers", "Embedded-Base")): + os.chdir("..") + + + # here from app or started from root + if contains_subdir(os.getcwd(), "bedded"): + command = ["pip", "install", "-e", os.path.join("Embedded-Base", "ner_environment")] + else: + print("[bold red] Error: No ner_environment found in current directory. Run from NER root, app, or Embedded-Base directories") + sys.exit(1) + + run_command(command) + +# ============================================================================== +# USBIP command +# ============================================================================== + +@app.command(help="Interact with the USB over IP system") +def usbip(connect: bool = typer.Option(False, "--connect", help="Connect to a USB device"), + disconnect: bool = typer.Option(False, "--disconnect", help="Disconnect the connected USB device"), + device: str = typer.Option(None, "--device", "-d", help="Specify the device to connect or disconnect (e.g., shepherd, cerberus)")): + + if connect: + if device is None: + print("[bold red] Error --device must be specified when using --connect") + + disconnect_usbip() # Disconnect the current USB device + + if device == "shep" or device == "shepherd": + commands = [ + ["sudo", "modprobe", "vhci_hcd"], + ["sudo", "usbip", "attach", "-r", "192.168.100.12", "-b", "1-1.4"] + ] + + elif device == "cerb" or device == "cerberus": + commands = [ + ["sudo", "modprobe", "vhci_hcd"], + ["sudo", "usbip", "attach", "-r", "192.168.100.12", "-b", "1-1.3"] + ] + + else: + print("[bold red] Error: Invalid device name") + sys.exit(1) + + run_command(commands[0]) + run_command(commands[1]) + + elif disconnect: + disconnect_usbip() + +# ============================================================================== +# Helper functions - not direct commands +# ============================================================================== + +def run_command(command, stream_output=False, exit_on_fail=True): + """Run a shell command. Optionally stream the output in real-time.""" + + if stream_output: + + process = subprocess.Popen(command, text=True) + + returncode = process.wait() + if returncode != 0: + print(f"Error: Command exited with code {returncode}", file=sys.stderr) + if exit_on_fail: + sys.exit(returncode) + + else: + try: + result = subprocess.run(command, check=True, capture_output=True, text=True) + print(result.stdout) + except subprocess.CalledProcessError as e: + print(f"Error occurred: {e}", file=sys.stderr) + print(e.stderr, file=sys.stderr) + if exit_on_fail: + sys.exit(e.returncode) + +def disconnect_usbip(): + """Disconnect the current USB device.""" + command = ["sudo", "usbip", "detach", "-p", "0"] + run_command(command, exit_on_fail=False) + +def is_wsl() -> int: + """Detects if Python is running in WSL by checking the system name.""" + if platform.system() == "Linux" and "microsoft" in platform.uname().release.lower(): + return 2 # WSL2 + return 0 # Not WSL + +def contains_subdir(base_path, search_str): + base_dir = Path(base_path) + for item in base_dir.iterdir(): + if item.is_dir() and search_str in item.name: + return True + return False + +# ============================================================================== +# Entry +# ============================================================================== + +if __name__ == "__main__": + app(prog_name="ner") + + + diff --git a/clang_restage.py b/ner_environment/build_system/clang_restage.py similarity index 100% rename from clang_restage.py rename to ner_environment/build_system/clang_restage.py diff --git a/miniterm.py b/ner_environment/build_system/miniterm.py similarity index 73% rename from miniterm.py rename to ner_environment/build_system/miniterm.py index 5e8e000..b34d4a7 100644 --- a/miniterm.py +++ b/ner_environment/build_system/miniterm.py @@ -1,4 +1,3 @@ -import os import subprocess import platform import sys @@ -43,16 +42,28 @@ def run_miniterm(device, baudrate=115200): print(f"Failed to run pyserial-miniterm: {e}", file=sys.stderr) sys.exit(1) -def main(): +def main(ls=False, device=""): # Detect the operating system and find USB devices - devices = list_usb_devices() - - if not devices: - print("No USB devices found.", file=sys.stderr) - sys.exit(1) - - # Default to the first device if available - selected_device = devices[0] + if device == "": + # reverse so FTDI is the default if present, can always be overridden + devices = list(reversed(list_usb_devices())) + + if not devices: + print("No USB devices found.", file=sys.stderr) + sys.exit(1) + + if ls: + print("Devices present:") + for i, device in enumerate(devices): + print(device) + + print("The first device will be selected if --device not specified.") + sys.exit(0) + + # Default to the first device if available + selected_device = devices[0] + else: + selected_device = device print(f"Selected USB device: {selected_device}") # Run pyserial-miniterm with the selected device diff --git a/ner_setup.py b/ner_environment/ner_setup.py similarity index 62% rename from ner_setup.py rename to ner_environment/ner_setup.py index e9c5e9b..2a7045d 100644 --- a/ner_setup.py +++ b/ner_environment/ner_setup.py @@ -9,6 +9,18 @@ except ImportError: distro = None +def is_wsl(v: str = platform.uname().release) -> int: + """ + detects if Python is running in WSL + """ + + if v.endswith("-Microsoft"): + return 1 + elif v.endswith("microsoft-standard-WSL2"): + return 2 + + return 0 + def run_command(command, check=True, shell=False): try: result = subprocess.run(command, check=check, shell=shell, text=True, capture_output=True) @@ -19,51 +31,26 @@ def run_command(command, check=True, shell=False): print(f"Command failed: {e.cmd}\nReturn code: {e.returncode}\nOutput: {e.output}\nError: {e.stderr}", file=sys.stderr) sys.exit(1) -def check_docker_and_rust(): - print("This script requires Docker and Rust to be installed.") - answer = input("Do you have Docker and Rust installed? (yes/no): ").strip().lower() +def check_docker(): + print("This script requires Docker to be installed.") + answer = input("Do you have Docker installed? (yes/no): ").strip().lower() if 'y' not in answer: sys.exit(1) os_type = platform.system() if os_type == 'Windows': - print("Windows OS detected. If on windows, you must be using bash (included with git), instead of cmd or powershell") - answer = input("Are you using bash? (yes/no): ").strip().lower() - if 'y' not in answer: - sys.exit(1) + print("Windows OS detected. If on windows, you must be using WSL. Revist the docs and reinstall. Sorry") + sys.exit(1) def docker_pull(image_url): os_type = platform.system() - if os_type=='Windows' or os_type == 'Darwin': + if is_wsl() or os_type == 'Darwin': print("Please open the Docker Desktop application before proceeding") answer =input("Is the Docker Desktop app running? (yes/no)") print("Pulling Docker image...") run_command(["docker", "pull", image_url]) print("Docker image pulled successfully.") -def load_aliases(venv_path, aliases_file): - os_type = platform.system() - if os_type == 'Windows': - activate_path = os.path.join(venv_path, 'Scripts', 'activate') # Bash script for Git Bash on Windows - else: - activate_path = os.path.join(venv_path, 'bin', 'activate') # bash script for Unix-like systems - - try: - with open(aliases_file, 'r') as f: - aliases = f.readlines() - - with open(activate_path, 'a') as activate_file: - activate_file.write('\n# Aliases\n') - for alias in aliases: - alias_name, alias_command = alias.strip().split('=', 1) - alias_command = alias_command.strip('"') - activate_file.write(f'alias {alias_name}="{alias_command}"\n') - - print("Aliases added to the activation script successfully.") - except Exception as e: - print(f"Failed to add aliases: {e}", file=sys.stderr) - sys.exit(1) - def create_venv(venv_path): try: venv.EnvBuilder(with_pip=True).create(venv_path) @@ -76,7 +63,7 @@ def run_setup(venv_python): print("Running setup.py...") try: # Run the pip install -e . command - run_command([venv_python, '-m', 'pip', 'install', '-e', '.']) + run_command([venv_python, '-m', 'pip', 'install', '-e', 'ner_environment']) except subprocess.CalledProcessError as e: print(f"Failed to run pip install -e .: {e}", file=sys.stderr) sys.exit(1) @@ -90,21 +77,25 @@ def install_precommit(venv_python): print(f"Failed to install pre-commit: {e}", file=sys.stderr) sys.exit(1) -def install_probe_rs(): +def install_openocd(): os_type = platform.system() - print("Installing probe-rs...") try: - if os_type == "Windows": - # Using bash to run PowerShell for downloading and executing the script - command = [ - "powershell", "-Command", "Invoke-RestMethod https://github.com/probe-rs/probe-rs/releases/latest/download/probe-rs-tools-installer.ps1 | Invoke-Expression"] - run_command(command, shell=False) - else: - # For Unix-like systems (Linux, macOS) - command = ["bash", "-c", "curl --proto '=https' --tlsv1.2 -LsSf https://github.com/probe-rs/probe-rs/releases/latest/download/probe-rs-tools-installer.sh | sh"] - run_command(command, shell=False) + if os_type == "Darwin": + run_command(["brew", "install", "openocd"]) + + elif os_type == "Linux": + distro_name = distro.id() + if distro_name in ["ubuntu", "debian"]: + run_command(["sudo", "apt-get", "install", "-y", "openocd"]) + elif distro_name == "fedora": + run_command(["sudo", "dnf", "install", "-y", "openocd"]) + elif distro_name == "arch": + run_command(["sudo", "pacman", "-S", "--noconfirm", "openocd"]) + else: + print("We haven't added OpenOCD install support for your distro, but if you're actually on linux, you can install it manually!") + except Exception as e: - print(f"Failed to install probe-rs: {e}", file=sys.stderr) + print(f"Failed to install OpenOCD: {e}", file=sys.stderr) sys.exit(1) def install_usbip(): @@ -128,8 +119,8 @@ def main(): print("Everyone's system is different, and if you already have something installed, or know exactly") print("what you are doing, feel free to manually go about this as needed.") - # Step 0: Check for Docker and Rust - check_docker_and_rust() + # Step 0: Check for Docker + check_docker() # Step 1: pull image answer = input("Would you like to pull the docker image? (yes/no)") @@ -140,6 +131,7 @@ def main(): os_type = platform.system() current_directory = os.path.dirname(os.path.abspath(__file__)) parent_directory = os.path.dirname(current_directory) + parent_directory = os.path.dirname(parent_directory) venv_path = os.path.join(parent_directory, 'ner-venv') @@ -148,17 +140,10 @@ def main(): if 'y' in answer: create_venv(venv_path) - answer = input("Would you like to add necesarry alias commands? (yes/no)") - if 'y' in answer: - - # Step 3: Modify activation and deactivation scripts - aliases_file = os.path.join(current_directory, 'aliases.txt') - load_aliases(venv_path, aliases_file) - answer = input("Would you like to install all python packages in the venv? (yes/no)") if 'y' in answer: # Use the venv's Python - venv_python = os.path.join(venv_path, 'Scripts', 'python') if os_type == "Windows" else os.path.join(venv_path, 'bin', 'python') + venv_python = os.path.join(venv_path, 'bin', 'python') # Step 4: run setup.py (installs requirements and entry points) run_setup(venv_python) @@ -166,13 +151,13 @@ def main(): # Step 5: Run pre-commit install install_precommit(venv_python) - answer = input("Would you like to install probe-rs? (do this manually if on a weird linux distro!) (yes/no)") + answer = input("Would you like to install openOCD? (do this manually if on a weird linux distro!) (yes/no)") if 'y' in answer: # Step 5: Install probe-rs - install_probe_rs() + install_openocd() # Step 6: Install usbip if on Linux - if os_type == "Linux": + if os_type == "Linux" and is_wsl() == 0: answer = input("Would you like to install usbip? (yes/no)") if 'y' in answer: install_usbip() diff --git a/requirements.txt b/ner_environment/requirements.txt similarity index 67% rename from requirements.txt rename to ner_environment/requirements.txt index 51af454..3ea28a0 100644 --- a/requirements.txt +++ b/ner_environment/requirements.txt @@ -1,3 +1,5 @@ distro pre-commit clang-format +pyserial +typer diff --git a/ner_environment/setup.py b/ner_environment/setup.py new file mode 100644 index 0000000..3891a80 --- /dev/null +++ b/ner_environment/setup.py @@ -0,0 +1,19 @@ +from setuptools import setup, find_packages + +# Read the contents of requirements.txt +def parse_requirements(filename): + with open(filename, 'r') as file: + return [line.strip() for line in file if line.strip() and not line.startswith('#')] + +setup( + name='ner-enviroment', + version='0.2', + packages=find_packages(include=['build_system', 'build_system.*']), + install_requires=parse_requirements('requirements.txt'), + entry_points={ + 'console_scripts': [ + 'ner=build_system:app', + 'clang_restage=build_system.clang_restage:main' + ], + }, +) diff --git a/openocd.cfg b/openocd.cfg new file mode 100644 index 0000000..12a8374 --- /dev/null +++ b/openocd.cfg @@ -0,0 +1,7 @@ +$_TARGETNAME configure -event gdb-detach { + reset run + shutdown +} + +init +reset halt diff --git a/platforms/stm32f405/include/can.h b/platforms/stm32f405/include/can.h index c318366..69fb2ea 100644 --- a/platforms/stm32f405/include/can.h +++ b/platforms/stm32f405/include/can.h @@ -14,15 +14,15 @@ */ typedef struct { - CAN_HandleTypeDef *hcan; - const uint32_t *id_list; - uint8_t id_list_len; + CAN_HandleTypeDef *hcan; + const uint32_t *id_list; + uint8_t id_list_len; } can_t; typedef struct { - uint32_t id; - uint8_t data[8]; - uint8_t len; + uint32_t id; + uint8_t data[8]; + uint8_t len; } can_msg_t; HAL_StatusTypeDef can_init(can_t *can); diff --git a/platforms/stm32f405/src/can.c b/platforms/stm32f405/src/can.c index b3f2024..cd82bb1 100644 --- a/platforms/stm32f405/src/can.c +++ b/platforms/stm32f405/src/can.c @@ -7,102 +7,106 @@ * implement in `stm32xxxx_it.c`, which STM32CubeMX generates */ -HAL_StatusTypeDef can_init(can_t *can) { - /* set up filter */ - uint16_t high_id = can->id_list[0]; - uint16_t low_id = can->id_list[0]; - - for (uint8_t i = 0; i < can->id_list_len; i++) { - if (can->id_list[i] > high_id) - high_id = can->id_list[i]; - if (can->id_list[i] < low_id) - low_id = can->id_list[i]; - } - - // uint32_t full_id = ((uint32_t)high_id << 16) | low_id; - - CAN_FilterTypeDef sFilterConfig; - - sFilterConfig.FilterBank = 0; - sFilterConfig.FilterMode = CAN_FILTERMODE_IDMASK; - sFilterConfig.FilterScale = CAN_FILTERSCALE_32BIT; - sFilterConfig.FilterIdHigh = 0x0000; - sFilterConfig.FilterIdLow = 0x0000; - sFilterConfig.FilterMaskIdHigh = 0x0000; - sFilterConfig.FilterMaskIdLow = 0x0000; - sFilterConfig.FilterFIFOAssignment = CAN_RX_FIFO0; - sFilterConfig.FilterActivation = ENABLE; - sFilterConfig.SlaveStartFilterBank = 14; - - // sFilterConfig.FilterBank = 0; /* Filter bank number - // (0 to 27 for most STM32 series) */ sFilterConfig.FilterMode = - // CAN_FILTERMODE_IDLIST; /* Identifier list mode */ - // sFilterConfig.FilterScale = CAN_FILTERSCALE_32BIT; /* 32-bit identifier - // list */ - - // sFilterConfig.FilterIdHigh = (full_id & 0xFFFF0000U) >> 5; - // sFilterConfig.FilterIdLow = (full_id & 0xFFFFU) << 5; - - // sFilterConfig.FilterMaskIdHigh = 0xFFFF << 5; /* Set to all ones for - // ID range */ sFilterConfig.FilterMaskIdLow = 0xFFFF; /* Set to - // all ones for ID range */ - - // sFilterConfig.FilterFIFOAssignment = CAN_RX_FIFO0; /* FIFO to assign the - // filter to */ sFilterConfig.FilterActivation = ENABLE; /* Enable - // the filter */ - - uint8_t err = 0; - err = HAL_CAN_ConfigFilter(can->hcan, &sFilterConfig); - if (err != HAL_OK) - return err; - - /* set up interrupt & activate CAN */ - HAL_CAN_IRQHandler(can->hcan); - - err = HAL_CAN_ActivateNotification(can->hcan, CAN_IT_RX_FIFO0_MSG_PENDING); - if (err != HAL_OK) - return err; - err = HAL_CAN_Start(can->hcan); - if (err != HAL_OK) - return err; - - return err; +HAL_StatusTypeDef can_init(can_t *can) +{ + /* set up filter */ + uint16_t high_id = can->id_list[0]; + uint16_t low_id = can->id_list[0]; + + for (uint8_t i = 0; i < can->id_list_len; i++) { + if (can->id_list[i] > high_id) + high_id = can->id_list[i]; + if (can->id_list[i] < low_id) + low_id = can->id_list[i]; + } + + // uint32_t full_id = ((uint32_t)high_id << 16) | low_id; + + CAN_FilterTypeDef sFilterConfig; + + sFilterConfig.FilterBank = 0; + sFilterConfig.FilterMode = CAN_FILTERMODE_IDMASK; + sFilterConfig.FilterScale = CAN_FILTERSCALE_32BIT; + sFilterConfig.FilterIdHigh = 0x0000; + sFilterConfig.FilterIdLow = 0x0000; + sFilterConfig.FilterMaskIdHigh = 0x0000; + sFilterConfig.FilterMaskIdLow = 0x0000; + sFilterConfig.FilterFIFOAssignment = CAN_RX_FIFO0; + sFilterConfig.FilterActivation = ENABLE; + sFilterConfig.SlaveStartFilterBank = 14; + + // sFilterConfig.FilterBank = 0; /* Filter bank number + // (0 to 27 for most STM32 series) */ sFilterConfig.FilterMode = + // CAN_FILTERMODE_IDLIST; /* Identifier list mode */ + // sFilterConfig.FilterScale = CAN_FILTERSCALE_32BIT; /* 32-bit identifier + // list */ + + // sFilterConfig.FilterIdHigh = (full_id & 0xFFFF0000U) >> 5; + // sFilterConfig.FilterIdLow = (full_id & 0xFFFFU) << 5; + + // sFilterConfig.FilterMaskIdHigh = 0xFFFF << 5; /* Set to all ones for + // ID range */ sFilterConfig.FilterMaskIdLow = 0xFFFF; /* Set to + // all ones for ID range */ + + // sFilterConfig.FilterFIFOAssignment = CAN_RX_FIFO0; /* FIFO to assign the + // filter to */ sFilterConfig.FilterActivation = ENABLE; /* Enable + // the filter */ + + uint8_t err = 0; + err = HAL_CAN_ConfigFilter(can->hcan, &sFilterConfig); + if (err != HAL_OK) + return err; + + /* set up interrupt & activate CAN */ + HAL_CAN_IRQHandler(can->hcan); + + err = HAL_CAN_ActivateNotification(can->hcan, + CAN_IT_RX_FIFO0_MSG_PENDING); + if (err != HAL_OK) + return err; + err = HAL_CAN_Start(can->hcan); + if (err != HAL_OK) + return err; + + return err; } -HAL_StatusTypeDef can_send_msg(can_t *can, can_msg_t *msg) { - CAN_TxHeaderTypeDef tx_header; - tx_header.StdId = msg->id; - tx_header.ExtId = 0; - tx_header.IDE = CAN_ID_STD; - tx_header.RTR = CAN_RTR_DATA; - tx_header.DLC = msg->len; - tx_header.TransmitGlobalTime = DISABLE; +HAL_StatusTypeDef can_send_msg(can_t *can, can_msg_t *msg) +{ + CAN_TxHeaderTypeDef tx_header; + tx_header.StdId = msg->id; + tx_header.ExtId = 0; + tx_header.IDE = CAN_ID_STD; + tx_header.RTR = CAN_RTR_DATA; + tx_header.DLC = msg->len; + tx_header.TransmitGlobalTime = DISABLE; - uint32_t tx_mailbox; - if (HAL_CAN_GetTxMailboxesFreeLevel(can->hcan) == 0) - return HAL_BUSY; + uint32_t tx_mailbox; + if (HAL_CAN_GetTxMailboxesFreeLevel(can->hcan) == 0) + return HAL_BUSY; - if (HAL_CAN_AddTxMessage(can->hcan, &tx_header, msg->data, &tx_mailbox)) - return HAL_ERROR; + if (HAL_CAN_AddTxMessage(can->hcan, &tx_header, msg->data, &tx_mailbox)) + return HAL_ERROR; - return HAL_OK; + return HAL_OK; } -HAL_StatusTypeDef can_send_extended_msg(can_t *can, can_msg_t *msg) { - CAN_TxHeaderTypeDef tx_header; - tx_header.StdId = 0; - tx_header.ExtId = msg->id; - tx_header.IDE = CAN_ID_EXT; - tx_header.RTR = CAN_RTR_DATA; - tx_header.DLC = msg->len; - tx_header.TransmitGlobalTime = DISABLE; +HAL_StatusTypeDef can_send_extended_msg(can_t *can, can_msg_t *msg) +{ + CAN_TxHeaderTypeDef tx_header; + tx_header.StdId = 0; + tx_header.ExtId = msg->id; + tx_header.IDE = CAN_ID_EXT; + tx_header.RTR = CAN_RTR_DATA; + tx_header.DLC = msg->len; + tx_header.TransmitGlobalTime = DISABLE; - uint32_t tx_mailbox; - if (HAL_CAN_GetTxMailboxesFreeLevel(can->hcan) == 0) - return HAL_BUSY; + uint32_t tx_mailbox; + if (HAL_CAN_GetTxMailboxesFreeLevel(can->hcan) == 0) + return HAL_BUSY; - if (HAL_CAN_AddTxMessage(can->hcan, &tx_header, msg->data, &tx_mailbox)) - return HAL_ERROR; + if (HAL_CAN_AddTxMessage(can->hcan, &tx_header, msg->data, &tx_mailbox)) + return HAL_ERROR; - return HAL_OK; + return HAL_OK; } diff --git a/platforms/stm32g431/include/fdcan.h b/platforms/stm32g431/include/fdcan.h index 974451e..6d4a699 100644 --- a/platforms/stm32g431/include/fdcan.h +++ b/platforms/stm32g431/include/fdcan.h @@ -11,18 +11,18 @@ typedef void (*can_callback_t)(FDCAN_HandleTypeDef *hcan); typedef struct { - FDCAN_HandleTypeDef *hcan; - const uint16_t *id_list; - uint8_t id_list_len; + FDCAN_HandleTypeDef *hcan; + const uint16_t *id_list; + uint8_t id_list_len; - /* desired behavior varies by app - so implement this at app level */ - can_callback_t callback; + /* desired behavior varies by app - so implement this at app level */ + can_callback_t callback; } can_t; typedef struct { - uint32_t id; - uint8_t data[8]; - uint8_t len; + uint32_t id; + uint8_t data[8]; + uint8_t len; } can_msg_t; HAL_StatusTypeDef can_init(can_t *can); diff --git a/platforms/stm32g431/src/fdcan.c b/platforms/stm32g431/src/fdcan.c index 17c8a19..bbc936c 100644 --- a/platforms/stm32g431/src/fdcan.c +++ b/platforms/stm32g431/src/fdcan.c @@ -5,100 +5,105 @@ /* NOTE: STM32G431 will have MAX of 3 CAN buses */ #define MAX_CAN_BUS 3 -can_t *can_struct_list[MAX_CAN_BUS] = {NULL, NULL, NULL}; - -static can_callback_t find_callback(FDCAN_HandleTypeDef *hcan) { - for (uint8_t i = 0; i < MAX_CAN_BUS; i++) { - if (hcan == can_struct_list[i]->hcan) - return can_struct_list[i]->callback; - } - return NULL; +can_t *can_struct_list[MAX_CAN_BUS] = { NULL, NULL, NULL }; + +static can_callback_t find_callback(FDCAN_HandleTypeDef *hcan) +{ + for (uint8_t i = 0; i < MAX_CAN_BUS; i++) { + if (hcan == can_struct_list[i]->hcan) + return can_struct_list[i]->callback; + } + return NULL; } /* Add a CAN interfae to be searched for during the event of a callback */ -static uint8_t add_interface(can_t *interface) { - for (uint8_t i = 0; i < MAX_CAN_BUS; i++) { - /* Interface already added */ - if (interface->hcan == can_struct_list[i]->hcan) - return -1; - - /* If empty, add interface */ - if (can_struct_list[i]->hcan == NULL) { - can_struct_list[i] = interface; - return 0; - } - } - - /* No open slots, something is wrong */ - return -2; +static uint8_t add_interface(can_t *interface) +{ + for (uint8_t i = 0; i < MAX_CAN_BUS; i++) { + /* Interface already added */ + if (interface->hcan == can_struct_list[i]->hcan) + return -1; + + /* If empty, add interface */ + if (can_struct_list[i]->hcan == NULL) { + can_struct_list[i] = interface; + return 0; + } + } + + /* No open slots, something is wrong */ + return -2; } /* Run callback function when there a new message is received */ -void HAL_FDCAN_RxFifo0Callback(FDCAN_HandleTypeDef *hcan, uint32_t RxFifo0ITs) { - /* Handle CAN reception event */ - can_callback_t callback = find_callback(hcan); - - if (callback != NULL) { - callback(hcan); - } +void HAL_FDCAN_RxFifo0Callback(FDCAN_HandleTypeDef *hcan, uint32_t RxFifo0ITs) +{ + /* Handle CAN reception event */ + can_callback_t callback = find_callback(hcan); + + if (callback != NULL) { + callback(hcan); + } } -HAL_StatusTypeDef can_init(can_t *can) { - /* set up filter */ - uint16_t high_id = can->id_list[0]; - uint16_t low_id = can->id_list[0]; - - for (uint8_t i = 0; i < can->id_list_len; i++) { - if (can->id_list[i] > high_id) - high_id = can->id_list[i]; - if (can->id_list[i] < low_id) - low_id = can->id_list[i]; - } - - uint32_t full_id = ((uint32_t)high_id << 16) | low_id; - - FDCAN_FilterTypeDef sFilterConfig; - - sFilterConfig.IdType = FDCAN_STANDARD_ID; - sFilterConfig.FilterIndex = 0; - sFilterConfig.FilterType = FDCAN_FILTER_RANGE; - sFilterConfig.FilterConfig = FDCAN_FILTER_DISABLE; - sFilterConfig.FilterID1 = 0x0; - sFilterConfig.FilterID2 = 0x7FF; - - uint8_t err = 0; - err = HAL_FDCAN_ConfigFilter(can->hcan, &sFilterConfig); - if (err != HAL_OK) - return err; - - /* set up interrupt & activate CAN */ - err = HAL_FDCAN_Start(can->hcan); - if (err != HAL_OK) - return err; - - /* Override the default callback for FDCAN_IT_LIST_RX_FIFO0 */ - // err = HAL_FDCAN_ActivateNotification(can->hcan, FDCAN_IT_LIST_RX_FIFO0); - err = add_interface(can); - - return err; +HAL_StatusTypeDef can_init(can_t *can) +{ + /* set up filter */ + uint16_t high_id = can->id_list[0]; + uint16_t low_id = can->id_list[0]; + + for (uint8_t i = 0; i < can->id_list_len; i++) { + if (can->id_list[i] > high_id) + high_id = can->id_list[i]; + if (can->id_list[i] < low_id) + low_id = can->id_list[i]; + } + + uint32_t full_id = ((uint32_t)high_id << 16) | low_id; + + FDCAN_FilterTypeDef sFilterConfig; + + sFilterConfig.IdType = FDCAN_STANDARD_ID; + sFilterConfig.FilterIndex = 0; + sFilterConfig.FilterType = FDCAN_FILTER_RANGE; + sFilterConfig.FilterConfig = FDCAN_FILTER_DISABLE; + sFilterConfig.FilterID1 = 0x0; + sFilterConfig.FilterID2 = 0x7FF; + + uint8_t err = 0; + err = HAL_FDCAN_ConfigFilter(can->hcan, &sFilterConfig); + if (err != HAL_OK) + return err; + + /* set up interrupt & activate CAN */ + err = HAL_FDCAN_Start(can->hcan); + if (err != HAL_OK) + return err; + + /* Override the default callback for FDCAN_IT_LIST_RX_FIFO0 */ + // err = HAL_FDCAN_ActivateNotification(can->hcan, FDCAN_IT_LIST_RX_FIFO0); + err = add_interface(can); + + return err; } -HAL_StatusTypeDef can_send_msg(can_t *can, can_msg_t *msg) { - FDCAN_TxHeaderTypeDef tx_header; - tx_header.Identifier = msg->id; - tx_header.IdType = FDCAN_STANDARD_ID; - tx_header.TxFrameType = FDCAN_DATA_FRAME; - tx_header.DataLength = msg->len; - tx_header.ErrorStateIndicator = FDCAN_ESI_ACTIVE; - tx_header.BitRateSwitch = FDCAN_BRS_OFF; - tx_header.FDFormat = FDCAN_CLASSIC_CAN; - - uint32_t tx_mailbox; - if (HAL_FDCAN_GetTxFifoFreeLevel(can->hcan) == 0) - return HAL_BUSY; - - if (HAL_FDCAN_AddMessageToTxFifoQ(can->hcan, &tx_header, &msg->data)) - return HAL_ERROR; - - return HAL_OK; +HAL_StatusTypeDef can_send_msg(can_t *can, can_msg_t *msg) +{ + FDCAN_TxHeaderTypeDef tx_header; + tx_header.Identifier = msg->id; + tx_header.IdType = FDCAN_STANDARD_ID; + tx_header.TxFrameType = FDCAN_DATA_FRAME; + tx_header.DataLength = msg->len; + tx_header.ErrorStateIndicator = FDCAN_ESI_ACTIVE; + tx_header.BitRateSwitch = FDCAN_BRS_OFF; + tx_header.FDFormat = FDCAN_CLASSIC_CAN; + + uint32_t tx_mailbox; + if (HAL_FDCAN_GetTxFifoFreeLevel(can->hcan) == 0) + return HAL_BUSY; + + if (HAL_FDCAN_AddMessageToTxFifoQ(can->hcan, &tx_header, &msg->data)) + return HAL_ERROR; + + return HAL_OK; } \ No newline at end of file diff --git a/setup.py b/setup.py deleted file mode 100644 index 58aa45f..0000000 --- a/setup.py +++ /dev/null @@ -1,25 +0,0 @@ -from setuptools import setup - -# Read the contents of requirements.txt -def parse_requirements(filename): - with open(filename, 'r') as file: - return [line.strip() for line in file if line.strip() and not line.startswith('#')] - -setup( - name='ner-setup', - version='0.1', - py_modules=['ner_setup', 'launchpad', 'clang_restage', 'miniterm' , 'load_alias'], - install_requires=parse_requirements('requirements.txt'), - entry_points={ - 'console_scripts': [ - 'ner_setup=ner_setup:main', # Command 'ner_setup' runs 'main' function in ner_setup.py - 'clang_restage=clang_restage:main', - 'serial=miniterm:main', - 'launchpad=launchpad:main', - 'load-alias=load_alias:main', - - ], - }, - - -) \ No newline at end of file