hide deprecated code; make USB snippet common for F0/F1/F3

This commit is contained in:
Edward Emelianov
2024-09-02 18:21:41 +03:00
parent 9166996bff
commit bdbd7d68d9
419 changed files with 3445 additions and 752 deletions

Binary file not shown.

View File

@@ -0,0 +1,151 @@
BINARY = MLX90640
BOOTPORT ?= /dev/ttyUSB0
BOOTSPEED ?= 115200
# MCU FAMILY
FAMILY ?= F1
# MCU code
MCU ?= F103x8
# density (stm32f10x.h, lines 70-84)
DENSITY ?= MD
# change this linking script depending on particular MCU model,
LDSCRIPT ?= stm32f103x8.ld
# debug
DEFS = -DEBUG
# autoincremental version & build date
VERSION_FILE = version.inc
NEXTVER := $(shell expr $$(awk '/#define BUILD_NUMBER/' $(VERSION_FILE) | tr -cd "[0-9]") + 1)
BUILDDATE := $(shell date +%Y-%m-%d)
INDEPENDENT_HEADERS=
FP_FLAGS ?= -msoft-float -mfloat-abi=soft
ASM_FLAGS ?= -mthumb -mcpu=cortex-m3 -mfix-cortex-m3-ldrd
ARCH_FLAGS = $(ASM_FLAGS) $(FP_FLAGS)
###############################################################################
# Executables
#PREFIX ?= arm-none-eabi
# gcc from arm web site
PREFIX ?= /opt/bin/arm-none-eabi
TOOLCHLIB ?= /opt/arm-none-eabi/lib
RM := rm -f
RMDIR := rmdir
CC := $(PREFIX)-gcc
# don't replace ld with gcc: the binary size would be much greater!!
LD := $(PREFIX)-ld
AR := $(PREFIX)-ar
AS := $(PREFIX)-as
SIZE := $(PREFIX)-size
OBJCOPY := $(PREFIX)-objcopy
OBJDUMP := $(PREFIX)-objdump
GDB := $(PREFIX)-gdb
STFLASH := $(shell which st-flash)
STBOOT := $(shell which stm32flash)
DFUUTIL := $(shell which dfu-util)
###############################################################################
# Source files
OBJDIR = mk
SRC := $(wildcard *.c)
OBJS := $(addprefix $(OBJDIR)/, $(SRC:%.c=%.o))
STARTUP = $(OBJDIR)/startup.o
OBJS += $(STARTUP)
# dependencies: we need them to recompile files if their headers-dependencies changed
DEPS := $(OBJS:.o=.d)
INC_DIR ?= ../inc
INCLUDE := -I$(INC_DIR)/Fx -I$(INC_DIR)/cm
LIB_DIR := $(INC_DIR)/ld
###############################################################################
# C flags
CFLAGS += -O2 -g -D__thumb2__=1 -MD
CFLAGS += -Wall -Werror -Wextra -Wshadow
CFLAGS += -fno-common -ffunction-sections -fdata-sections -fno-stack-protector
CFLAGS += $(ARCH_FLAGS)
###############################################################################
# Linker flags
LDFLAGS += -nostartfiles --static -nostdlibs --gc-sections --print-memory-usage
LDFLAGS += -L$(LIB_DIR) -L$(TOOLCHLIB)
LDFLAGS += -T$(LDSCRIPT)
###############################################################################
# Used libraries
LDLIBS += -lm -lc $(shell $(CC) $(CFLAGS) -print-libgcc-file-name)
DEFS += -DSTM32$(FAMILY) -DSTM32$(MCU) -DSTM32F10X_$(DENSITY)
ELF := $(OBJDIR)/$(BINARY).elf
LIST := $(OBJDIR)/$(BINARY).list
BIN := $(BINARY).bin
HEX := $(BINARY).hex
all: bin list size
elf: $(ELF)
bin: $(BIN)
hex: $(HEX)
list: $(LIST)
ifneq ($(MAKECMDGOALS),clean)
-include $(DEPS)
endif
$(OBJDIR):
mkdir $(OBJDIR)
$(STARTUP): $(INC_DIR)/startup/vector.c
$(CC) $(CFLAGS) $(DEFS) $(INCLUDE) -o $@ -c $<
$(VERSION_FILE): *.[ch]
@echo " Generate version: $(NEXTVER) for date $(BUILDDATE)"
@sed -i "s/#define BUILD_NUMBER.*/#define BUILD_NUMBER \"$(NEXTVER)\"/" $(VERSION_FILE)
@sed -i "s/#define BUILD_DATE.*/#define BUILD_DATE \"$(BUILDDATE)\"/" $(VERSION_FILE)
$(OBJDIR)/proto.o: proto.c $(VERSION_FILE)
$(OBJDIR)/%.o: %.c
@echo " CC $<"
$(CC) $(CFLAGS) $(DEFS) $(INCLUDE) -o $@ -c $<
$(BIN): $(ELF)
@echo " OBJCOPY $(BIN)"
$(OBJCOPY) -Obinary $(ELF) $(BIN)
$(HEX): $(ELF)
@echo " OBJCOPY $(HEX)"
$(OBJCOPY) -Oihex $(ELF) $(HEX)
$(LIST): $(ELF)
@echo " OBJDUMP $(LIST)"
$(OBJDUMP) -S $(ELF) > $(LIST)
$(ELF): $(OBJDIR) $(OBJS)
@echo " LD $(ELF)"
$(LD) $(LDFLAGS) $(OBJS) $(LDLIBS) -o $(ELF)
size: $(ELF)
$(SIZE) $(ELF)
clean:
@echo " CLEAN"
$(RM) $(OBJS) $(DEPS) $(ELF) $(HEX) $(LIST)
@rmdir $(OBJDIR) 2>/dev/null || true
flash: $(BIN)
@echo " FLASH $(BIN)"
$(STFLASH) write $(BIN) 0x8000000
boot: $(BIN)
@echo " LOAD $(BIN) through bootloader"
$(STBOOT) -b$(BOOTSPEED) $(BOOTPORT) -w $(BIN)
dfuboot: $(BIN)
@echo " LOAD $(BIN) THROUGH DFU"
$(DFUUTIL) -a0 -D $(BIN) -s 0x08000000
.PHONY: clean flash boot

View File

@@ -0,0 +1,2 @@
Working with MLX90640

View File

@@ -0,0 +1,51 @@
/*
* This file is part of the MLX90640 project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "hardware.h"
static inline void gpio_setup(){
// Enable clocks to the GPIO subsystems (PB for ADC), turn on AFIO clocking to disable SWD/JTAG
RCC->APB2ENR |= RCC_APB2ENR_IOPAEN | RCC_APB2ENR_IOPBEN | RCC_APB2ENR_IOPCEN | RCC_APB2ENR_AFIOEN;
// turn off SWJ/JTAG
// AFIO->MAPR = AFIO_MAPR_SWJ_CFG_DISABLE;
AFIO->MAPR = AFIO_MAPR_SWJ_CFG_JTAGDISABLE; // for PA15
// Set led as opendrain output
GPIOC->CRH |= CRH(13, CNF_ODOUTPUT | MODE_SLOW);
// USB pullup (PA15) - pushpull output
GPIOA->CRH = CRH(15, CNF_PPOUTPUT | MODE_SLOW);
// PB5 is powered MLX sensor (less than 23mA) - OD output
MLXPOW_OFF();
GPIOB->CRL = CRL(5, CNF_ODOUTPUT | MODE_SLOW);
}
void hw_setup(){
gpio_setup();
}
void iwdg_setup(){
uint32_t tmout = 16000000;
RCC->CSR |= RCC_CSR_LSION;
while((RCC->CSR & RCC_CSR_LSIRDY) != RCC_CSR_LSIRDY){if(--tmout == 0) break;} /* (2) */
IWDG->KR = IWDG_START;
IWDG->KR = IWDG_WRITE_ACCESS;
IWDG->PR = IWDG_PR_PR_1;
IWDG->RLR = 1250;
tmout = 16000000;
while(IWDG->SR){if(--tmout == 0) break;}
IWDG->KR = IWDG_REFRESH;
}

View File

@@ -0,0 +1,47 @@
/*
* This file is part of the MLX90640 project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __HARDWARE_H__
#define __HARDWARE_H__
#include "stm32f1.h"
// LED0 - PC13 (bluepill), blinking each second
#define LED0_port GPIOC
#define LED0_pin (1<<13)
// USB pullup (not present in bluepill, should be soldered) - PA15
#define USBPU_port GPIOA
#define USBPU_pin (1<<15)
#define MLXPOW_port GPIOB
#define MLXPOW_pin (1<<5)
#define USBPU_ON() pin_set(USBPU_port, USBPU_pin)
#define USBPU_OFF() pin_clear(USBPU_port, USBPU_pin)
#define MLXPOW_ON() pin_clear(MLXPOW_port, MLXPOW_pin)
#define MLXPOW_OFF() pin_set(MLXPOW_port, MLXPOW_pin)
#define MLXPOW_VAL() ((MLXPOW_port->IDR & MLXPOW_pin)?0:1)
#define LED_blink(x) pin_toggle(x ## _port, x ## _pin)
#define LED_on(x) pin_clear(x ## _port, x ## _pin)
#define LED_off(x) pin_set(x ## _port, x ## _pin)
void hw_setup();
void iwdg_setup();
#endif // __HARDWARE_H__

View File

@@ -0,0 +1,270 @@
/*
* This file is part of the MLX90640 project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "hardware.h"
#include "i2c.h"
/* don't run debugging info */
#ifdef EBUG
#undef EBUG
#endif
#include "strfunct.h"
extern volatile uint32_t Tms;
volatile i2c_dma_status i2cDMAr = I2C_DMA_NOTINIT;
// current addresses for read/write (should be set with i2c_set_addr7)
static uint8_t addr7r = 0, addr7w = 0;
// setup DMA receiver
static void i2c_DMAr_setup(){
/* Enable the peripheral clock DMA1 */
RCC->AHBENR |= RCC_AHBENR_DMA1EN;
DMA1_Channel7->CPAR = (uint32_t)&(I2C1->DR);
DMA1_Channel7->CCR |= DMA_CCR_MINC | DMA_CCR_TCIE;
NVIC_SetPriority(DMA1_Channel7_IRQn, 0);
NVIC_EnableIRQ(DMA1_Channel7_IRQn);
I2C1->CR2 |= I2C_CR2_DMAEN;
i2cDMAr = I2C_DMA_RELAX;
}
/*
* PB10/PB6 - I2C_SCL, PB11/PB7 - I2C_SDA or remap @ PB8 & PB9
* @param withDMA == 1 to setup DMA receiver too
*/
void i2c_setup(uint8_t withDMA){
RCC->APB2ENR |= RCC_APB2ENR_IOPBEN;
GPIOB->CRL = (GPIOB->CRL & ~(GPIO_CRL_CNF6 | GPIO_CRL_CNF7)) |
CRL(6, CNF_AFOD | MODE_NORMAL) | CRL(7, CNF_AFOD | MODE_NORMAL);
RCC->APB1ENR |= RCC_APB1ENR_I2C1EN;
I2C1->CR1 = 0; // clear all previous settings
I2C1->SR1 = 0;
RCC->APB1RSTR |= RCC_APB1RSTR_I2C1RST; // reset peripherial
RCC->APB1RSTR &= ~RCC_APB1RSTR_I2C1RST;
I2C1->CR2 = 8; // FREQR=8MHz, T=125ns
//I2C1->CR2 = 10; // FREQR=10MHz, T=100ns
I2C1->TRISE = 9; // (9-1)*125 = 1us
//I2C1->TRISE = 4; // (4-1)*100 = 300ns
I2C1->CCR = 40; // normal mode, 8MHz/2/40 = 100kHz
//I2C1->CCR = I2C_CCR_FS | 10; // fast mode, 10MHz/2/10 = 500kHz
if(withDMA) i2c_DMAr_setup();
I2C1->CR1 |= I2C_CR1_PE; // enable periph
}
void i2c_set_addr7(uint8_t addr){
addr7w = addr << 1;
addr7r = addr7w | 1;
}
// wait for event evt no more than 2 ms
#define I2C_WAIT(evt) do{ register uint32_t wait4 = Tms + 2; \
while(Tms < wait4 && !(evt)) IWDG->KR = IWDG_REFRESH; \
if(!(evt)){ret = I2C_TMOUT; goto eotr;}}while(0)
// wait for !busy
#define I2C_LINEWAIT() do{ register uint32_t wait4 = Tms + 2; \
while(Tms < wait4 && (I2C1->SR2 & I2C_SR2_BUSY)) IWDG->KR = IWDG_REFRESH; \
if(I2C1->SR2 & I2C_SR2_BUSY){I2C1->CR1 |= I2C_CR1_SWRST; return I2C_LINEBUSY;}\
}while(0)
// start writing
static i2c_status i2c_7bit_startw(){
i2c_status ret = I2C_LINEBUSY;
if(I2C1->CR1 != I2C_CR1_PE) i2c_setup(i2cDMAr != I2C_DMA_NOTINIT);
if(I2C1->SR1) I2C1->SR1 = 0; // clear NACK and other problems
(void) I2C1->SR2;
I2C_LINEWAIT();
DBG("linew");
I2C1->CR1 |= I2C_CR1_START; // generate start sequence
I2C_WAIT(I2C1->SR1 & I2C_SR1_SB); // wait for SB
DBG("SB");
(void) I2C1->SR1; // clear SB
I2C1->DR = addr7w; // set address
I2C_WAIT(I2C1->SR1 & I2C_SR1_ADDR); // wait for ADDR flag (timeout @ NACK)
DBG("ADDR");
if(I2C1->SR1 & I2C_SR1_AF){ // NACK
return I2C_NACK;
}
DBG("ACK");
(void) I2C1->SR2; // clear ADDR
ret = I2C_OK;
eotr:
return ret;
}
// send data array
i2c_status i2c_7bit_send(const uint8_t *data, int datalen, uint8_t stop){
i2c_status ret = i2c_7bit_startw();
if(ret != I2C_OK){
DBG("NACK!");
I2C1->CR1 |= I2C_CR1_STOP;
goto eotr;
}
for(int i = 0; i < datalen; ++i){
I2C1->DR = data[i];
I2C_WAIT(I2C1->SR1 & I2C_SR1_TXE);
}
DBG("GOOD");
ret = I2C_OK;
if(datalen || stop) I2C_WAIT(I2C1->SR1 & I2C_SR1_BTF);
eotr:
if(stop){
I2C1->CR1 |= I2C_CR1_STOP; // generate stop event
}else{DBG("No STOP");}
return ret;
}
i2c_status i2c_7bit_receive_onebyte(uint8_t *data, uint8_t stop){
i2c_status ret = I2C_LINEBUSY;
I2C1->CR1 |= I2C_CR1_START; // generate start sequence
I2C_WAIT(I2C1->SR1 & I2C_SR1_SB); // wait for SB
DBG("got SB");
(void) I2C1->SR1; // clear SB
I2C1->DR = addr7r; // set address
DBG("Rx addr");
I2C_WAIT(I2C1->SR1 & I2C_SR1_ADDR); // wait for ADDR flag
DBG("Rx ack");
I2C1->CR1 &= ~I2C_CR1_ACK; // clear ACK
if(I2C1->SR1 & I2C_SR1_AF){ // NACK
DBG("Rx nak");
ret = I2C_NACK;
goto eotr;
}
(void) I2C1->SR2; // clear ADDR
DBG("Rx stop");
if(stop) I2C1->CR1 |= I2C_CR1_STOP; // program STOP
I2C_WAIT(I2C1->SR1 & I2C_SR1_RXNE); // wait for RxNE
DBG("Rx OK");
*data = I2C1->DR; // read data & clear RxNE
ret = I2C_OK;
eotr:
return ret;
}
i2c_status i2c_7bit_receive_twobytes(uint8_t *data){
i2c_status ret = I2C_LINEBUSY;
I2C1->CR1 |= I2C_CR1_START | I2C_CR1_POS | I2C_CR1_ACK; // generate start sequence, set pos & ack
I2C_WAIT(I2C1->SR1 & I2C_SR1_SB); // wait for SB
DBG("2 got sb");
(void) I2C1->SR1; // clear SB
I2C1->DR = addr7r; // set address
I2C_WAIT(I2C1->SR1 & I2C_SR1_ADDR); // wait for ADDR flag
DBG("2 ADDR");
if(I2C1->SR1 & I2C_SR1_AF){ // NACK
ret = I2C_NACK;
DBG("2 NACK");
goto eotr;
}
DBG("2 ACK");
(void) I2C1->SR2; // clear ADDR
I2C1->CR1 &= ~I2C_CR1_ACK; // clear ACK
I2C_WAIT(I2C1->SR1 & I2C_SR1_BTF); // wait for BTF
DBG("2 BTF");
I2C1->CR1 |= I2C_CR1_STOP; // program STOP
*data++ = I2C1->DR; *data = I2C1->DR; // read data & clear RxNE
ret = I2C_OK;
eotr:
return ret;
}
// receive any amount of bytes
i2c_status i2c_7bit_receive(uint8_t *data, uint16_t nbytes){
if(nbytes == 0) return I2C_HWPROBLEM;
//DBG("linew");
//I2C_LINEWAIT();
I2C1->SR1 = 0; // clear previous NACK flag & other error flags
if(nbytes == 1) return i2c_7bit_receive_onebyte(data, 1);
else if(nbytes == 2) return i2c_7bit_receive_twobytes(data);
i2c_status ret = I2C_LINEBUSY;
I2C1->CR1 |= I2C_CR1_START | I2C_CR1_ACK; // generate start sequence, set pos & ack
I2C_WAIT(I2C1->SR1 & I2C_SR1_SB); // wait for SB
DBG("n got SB");
(void) I2C1->SR1; // clear SB
I2C1->DR = addr7r; // set address
I2C_WAIT(I2C1->SR1 & I2C_SR1_ADDR); // wait for ADDR flag
DBG("n send addr");
if(I2C1->SR1 & I2C_SR1_AF){ // NACK
DBG("n NACKed");
ret = I2C_NACK;
goto eotr;
}
DBG("n ACKed");
(void) I2C1->SR2; // clear ADDR
for(uint16_t x = nbytes - 3; x > 0; --x){
I2C_WAIT(I2C1->SR1 & I2C_SR1_RXNE); // wait next byte
*data++ = I2C1->DR; // get data
}
DBG("n three left");
// three bytes remain to be read
I2C_WAIT(I2C1->SR1 & I2C_SR1_RXNE); // wait dataN-2
DBG("n dataN-2");
I2C_WAIT(I2C1->SR1 & I2C_SR1_BTF); // wait for BTF
DBG("n BTF");
I2C1->CR1 &= ~I2C_CR1_ACK; // clear ACK
*data++ = I2C1->DR; // read dataN-2
I2C1->CR1 |= I2C_CR1_STOP; // program STOP
*data++ = I2C1->DR; // read dataN-1
I2C_WAIT(I2C1->SR1 & I2C_SR1_RXNE); // wait next byte
*data = I2C1->DR; // read dataN
DBG("n got it");
ret = I2C_OK;
eotr:
return ret;
}
/**
* @brief i2c_7bit_receive_DMA - receive data using DMA
* @param data - pointer to external array
* @param nbytes - data len
* @return I2C_OK when receiving started; poll end of receiving by flag i2cDMAr;
*/
i2c_status i2c_7bit_receive_DMA(uint8_t *data, uint16_t nbytes){
if(i2cDMAr == I2C_DMA_BUSY) return I2C_LINEBUSY; // previous receiving still works
if(i2cDMAr == I2C_DMA_NOTINIT) i2c_DMAr_setup();
i2c_status ret = I2C_LINEBUSY;
DBG("Conf DMA");
DMA1_Channel7->CCR &= ~DMA_CCR_EN;
DMA1_Channel7->CMAR = (uint32_t)data;
DMA1_Channel7->CNDTR = nbytes;
// now send address and start I2C receiving
//DBG("linew");
//I2C_LINEWAIT();
I2C1->SR1 = 0;
I2C1->CR1 |= I2C_CR1_START | I2C_CR1_ACK;
DBG("wait sb");
I2C_WAIT(I2C1->SR1 & I2C_SR1_SB);
(void) I2C1->SR1;
I2C1->DR = addr7r;
DBG("wait addr");
I2C_WAIT(I2C1->SR1 & I2C_SR1_ADDR);
if(I2C1->SR1 & I2C_SR1_AF) return I2C_NACK;
(void) I2C1->SR2;
DBG("start");
DMA1_Channel7->CCR |= DMA_CCR_EN;
i2cDMAr = I2C_DMA_BUSY;
ret = I2C_OK;
eotr:
return ret;
}
void dma1_channel7_isr(){
I2C1->CR1 |= I2C_CR1_STOP; // send STOP
DMA1->IFCR = DMA_IFCR_CTCIF7;
DMA1_Channel7->CCR &= ~DMA_CCR_EN;
i2cDMAr = I2C_DMA_READY;
}

View File

@@ -0,0 +1,50 @@
/*
* This file is part of the MLX90640 project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef I2C_H__
#include <stm32f1.h>
typedef enum{
I2C_OK = 0,
I2C_LINEBUSY,
I2C_TMOUT,
I2C_NOADDR,
I2C_NACK,
I2C_HWPROBLEM,
} i2c_status;
typedef enum{
I2C_DMA_NOTINIT,
I2C_DMA_RELAX,
I2C_DMA_BUSY,
I2C_DMA_READY
} i2c_dma_status;
extern volatile i2c_dma_status i2cDMAr;
void i2c_setup(uint8_t withDMA);
void i2c_set_addr7(uint8_t addr);
i2c_status i2c_7bit_send(const uint8_t *data, int datalen, uint8_t stop);
i2c_status i2c_7bit_receive_onebyte(uint8_t *data, uint8_t stop);
i2c_status i2c_7bit_receive_twobytes(uint8_t *data);
i2c_status i2c_7bit_receive(uint8_t *data, uint16_t nbytes);
i2c_status i2c_7bit_receive_DMA(uint8_t *data, uint16_t nbytes);
#define I2C_H__
#endif // I2C_H__

View File

@@ -0,0 +1,70 @@
/*
* This file is part of the MLX90640 project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "i2c.h"
#include "hardware.h"
#include "mlx90640.h"
#include "proto.h"
#include "strfunct.h"
#include "usb.h"
volatile uint32_t Tms = 0;
/* Called when systick fires */
void sys_tick_handler(void){
++Tms;
}
int main(void){
uint32_t lastT = 0;
sysreset();
StartHSE();
hw_setup();
SysTick_Config(72000);
RCC->CSR |= RCC_CSR_RMVF; // remove reset flags
USBPU_OFF();
USB_setup();
#ifndef EBUG
iwdg_setup();
#endif
USBPU_ON();
i2c_setup(TRUE);
i2c_set_addr7(MLX_DEFAULT_ADDR);
while(1){
IWDG->KR = IWDG_REFRESH; // refresh watchdog
if(lastT > Tms || Tms - lastT > 499){
LED_blink(LED0);
lastT = Tms;
}
usb_proc();
char *txt, *ans;
if((txt = get_USB())){
IWDG->KR = IWDG_REFRESH;
ans = (char*)parse_cmd(txt);
if(ans){
addtobuf(ans);
NL();
}
}
mlx90640_process();
}
return 0;
}

View File

@@ -0,0 +1,578 @@
/*
* This file is part of the MLX90640 project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <math.h>
#include "hardware.h"
#include "i2c.h"
#include "mlx90640.h"
#include "mlx90640_regs.h"
#include "strfunct.h"
#ifdef EBUG
extern volatile uint32_t Tms;
#endif
mlx90640_state mlx_state = M_ERROR;
MLX90640_params params;
#if REG_CALIBRDATA_LEN > MLX_DMA_MAXLEN || MLX_PIXARRSZ > MLX_DMA_MAXLEN
#error "MLX_DMA_MAXLEN should be >= REG_CALIBRDATA_LEN"
#endif
static uint16_t dataarray[MLX_DMA_MAXLEN]; // array for raw data from sensor
static int portionlen = 0; // data length in `dataarray`
float mlx_image[MLX_PIXNO]; // ready image
#define CREG_VAL(reg) dataarray[CREG_IDX(reg)]
#define IMD_VAL(reg) dataarray[IMD_IDX(reg)]
static uint8_t simpleimage = 0; // ==1 not to calibrate T
static uint8_t subpageno = 0; // subpage number
// reg_control values for subpage #0 and #1
static const uint16_t reg_control_val[2] = {
REG_CONTROL_CHESS | REG_CONTROL_RES18 | REG_CONTROL_REFR_2HZ | REG_CONTROL_SUBPSEL | REG_CONTROL_DATAHOLD | REG_CONTROL_SUBPEN,
REG_CONTROL_CHESS | REG_CONTROL_RES18 | REG_CONTROL_REFR_2HZ | REG_CONTROL_SUBP1 | REG_CONTROL_SUBPSEL | REG_CONTROL_DATAHOLD | REG_CONTROL_SUBPEN
};
// read register value
int read_reg(uint16_t reg, uint16_t *val){
reg = __REV16(reg);
if(I2C_OK != i2c_7bit_send((uint8_t*)&reg, 2, 0)){
DBG("Can't send address");
return FALSE;
}
uint16_t d;
i2c_status s = i2c_7bit_receive_twobytes((uint8_t*)&d);
if(I2C_OK != s){
#ifdef EBUG
DBG("Can't get info, s=");
printu(s); NL();
#endif
return FALSE;
}
*val = __REV16(d);
return TRUE;
}
// blocking read N uint16_t values starting from `reg`
// @param reg - register to read
// @param N (io) - amount of bytes to read / bytes read
// @return `dataarray` or NULL if failed
uint16_t *read_data(uint16_t reg, uint16_t *N){
uint16_t n = *N;
if(n < 1 || n > MLX_DMA_MAXLEN) return NULL;
uint16_t i, *data = dataarray;
#ifdef EBUG
SEND("Tms="); printu(Tms); newline();
#endif
for(i = 0; i < n; ++i){
if(!read_reg(reg++, data++)){
DBG("can't read");
break;
}
}
#ifdef EBUG
SEND("Tms="); printu(Tms); newline();
#endif
*N = i;
return dataarray;
}
// write register value
int write_reg(uint16_t reg, uint16_t val){
// little endian -> big endian
uint8_t _4bytes[4];
_4bytes[0] = reg >> 8;
_4bytes[1] = reg & 0xff;
_4bytes[2] = val >> 8;
_4bytes[3] = val & 0xff;
if(I2C_OK != i2c_7bit_send(_4bytes, 4, 1)) return FALSE;
return TRUE;
}
/**
* @brief read_data_dma - read big data buffer by DMA
* @param reg - starting register number
* @param N - amount of data (in 16-bit words)
* @return FALSE if can't run operation
*/
int read_data_dma(uint16_t reg, int N){
if(N < 1 || N > MLX_DMA_MAXLEN) return FALSE;
/*uint8_t _2bytes[2];
_2bytes[0] = reg >> 8; // big endian!
_2bytes[1] = reg & 0xff;*/
reg = __REV16(reg);
portionlen = N;
if(I2C_OK != i2c_7bit_send((uint8_t*)&reg, 2, 0)){
DBG("DMA: can't send address");
return FALSE;
}
if(I2C_OK != i2c_7bit_receive_DMA((uint8_t*)dataarray, N*2)) return FALSE;
return TRUE;
}
/*****************************************************************************
Calculate parameters & values
*****************************************************************************/
// calculate Vdd from vddRAM register
/*
static float getVdd(uint16_t vddRAM){
int16_t ram = (int16_t) vddRAM;
float vdd = (float)ram - params.vdd25;
return vdd / params.kVdd + 3.3f;
}*/
// fill OCC/ACC row/col arrays
static void occacc(int8_t *arr, int l, uint16_t *regstart){
int n = l >> 2; // divide by 4
int8_t *p = arr;
for(int i = 0; i < n; ++i){
register uint16_t val = *regstart++;
*p++ = (val & 0x000F) >> 0;
*p++ = (val & 0x00F0) >> 4;
*p++ = (val & 0x0F00) >> 8;
*p++ = (val ) >> 12;
}
for(int i = 0; i < l; ++i, ++arr){
if(*arr > 0x07) *arr -= 0x10;
}
}
// get all parameters' values from `dataarray`, return FALSE if something failed
static int get_parameters(){
#ifdef EBUG
SEND("0 Tms="); printu(Tms); newline();
#endif
int8_t i8;
int16_t i16;
uint16_t *pu16;
uint16_t val = CREG_VAL(REG_VDD);
i8 = (int8_t) (val >> 8);
params.kVdd = i8 << 5;
if(params.kVdd == 0) return FALSE;
i16 = val & 0xFF;
params.vdd25 = ((i16 - 0x100) << 5) - (1<<13);
val = CREG_VAL(REG_KVTPTAT);
i16 = (val & 0xFC00) >> 10;
if(i16 > 0x1F) i16 -= 0x40;
params.KvPTAT = (float)i16 / (1<<12);
i16 = (val & 0x03FF);
if(i16 > 0x1FF) i16 -= 0x400;
params.KtPTAT = (float)i16 / 8.f;
params.vPTAT25 = (int16_t) CREG_VAL(REG_PTAT);
val = CREG_VAL(REG_APTATOCCS) >> 12;
params.alphaPTAT = val / 4.f + 8.f;
params.gainEE = (int16_t)CREG_VAL(REG_GAIN);
if(params.gainEE == 0) return FALSE;
#ifdef EBUG
SEND("1 Tms="); printu(Tms); newline();
#endif
int8_t occRow[MLX_H];
int8_t occColumn[MLX_W];
occacc(occRow, MLX_H, &CREG_VAL(REG_OCCROW14));
occacc(occColumn, MLX_W, &CREG_VAL(REG_OCCCOL14));
int8_t accRow[MLX_H];
int8_t accColumn[MLX_W];
occacc(accRow, MLX_H, &CREG_VAL(REG_ACCROW14));
occacc(accColumn, MLX_W, &CREG_VAL(REG_ACCCOL14));
val = CREG_VAL(REG_APTATOCCS);
// need to do multiplication instead of bitshift, so:
float occRemScale = 1<<(val&0x0F),
occColumnScale = 1<<((val>>4)&0x0F),
occRowScale = 1<<((val>>8)&0x0F);
int16_t offavg = (int16_t) CREG_VAL(REG_OSAVG);
// even/odd column/row numbers are for starting from 1, so for starting from 0 we chould swap them:
// even - for 1,3,5,...; odd - for 0,2,4,... etc
int8_t ktaavg[4];
// 0 - odd row, odd col; 1 - odd row even col; 2 - even row, odd col; 3 - even row, even col
val = CREG_VAL(REG_KTAAVGODDCOL);
ktaavg[2] = (int8_t)(val & 0xFF); // odd col, even row -> col 0,2,..; row 1,3,..
ktaavg[0] = (int8_t)(val >> 8);; // odd col, odd row -> col 0,2,..; row 0,2,..
val = CREG_VAL(REG_KTAAVGEVENCOL);
ktaavg[3] = (int8_t)(val & 0xFF); // even col, even row -> col 1,3,..; row 1,3,..
ktaavg[1] = (int8_t)(val >> 8); // even col, odd row -> col 1,3,..; row 0,2,..
// so index of ktaavg is 2*(row&1)+(col&1)
val = CREG_VAL(REG_KTAVSCALE);
uint8_t scale1 = ((val & 0xFF)>>4) + 8, scale2 = (val&0xF);
if(scale1 == 0 || scale2 == 0) return FALSE;
float mul = (float)(1<<scale2), div = (float)(1<<scale1); // kta_scales
uint16_t a_r = CREG_VAL(REG_SENSIVITY); // alpha_ref
val = CREG_VAL(REG_SCALEACC);
float *a = params.alpha, diva = (float)(val >> 12);
diva *= (float)(1<<30); // alpha_scale
float accRowScale = 1<<((val & 0x0f00)>>8),
accColumnScale = 1<<((val & 0x00f0)>>4),
accRemScale = 1<<(val & 0x0f);
pu16 = &CREG_VAL(REG_OFFAK1);
float *kta = params.kta, *offset = params.offset;
#ifdef EBUG
SEND("2 Tms="); printu(Tms); newline();
#endif
for(int row = 0; row < MLX_H; ++row){
int idx = (row&1)<<1;
for(int col = 0; col < MLX_W; ++col){
// offset
register uint16_t rv = *pu16++;
i16 = (rv & 0xFC00) >> 10;
if(i16 > 0x1F) i16 -= 0x40;
*offset++ = (float)offavg + (float)occRow[row]*occRowScale + (float)occColumn[col]*occColumnScale + (float)i16*occRemScale;
// kta
i16 = (rv & 0xF) >> 1;
if(i16 > 0x03) i16 -= 0x08;
*kta++ = (ktaavg[idx|(col&1)] + i16*mul) / div;
// alpha
i16 = (rv & 0x3F0) >> 4;
if(i16 > 0x1F) i16 -= 0x40;
float oft = (float)a_r + accRow[row]*accRowScale + accColumn[col]*accColumnScale +i16*accRemScale;
*a++ = oft / diva;
}
}
#ifdef EBUG
SEND("3 Tms="); printu(Tms); newline();
#endif
scale1 = (CREG_VAL(REG_KTAVSCALE) >> 8) & 0xF; // kvscale
div = (float)(1<<scale1);
val = CREG_VAL(REG_KVAVG);
i16 = val >> 12; if(i16 > 0x07) i16 -= 0x10;
ktaavg[0] = i16; // odd col, odd row
i16 = (val & 0xF0) >> 4; if(i16 > 0x07) i16 -= 0x10;
ktaavg[1] = i16; // even col, odd row
i16 = (val & 0x0F00) >> 8; if(i16 > 0x07) i16 -= 0x10;
ktaavg[2] = i16; // odd col, even row
i16 = val & 0x0F; if(i16 > 0x07) i16 -= 0x10;
ktaavg[3] = i16; // even col, even row
for(int i = 0; i < 4; ++i) params.kv[i] = ktaavg[i] / div;
val = CREG_VAL(REG_CPOFF);
params.cpOffset[0] = (val & 0x03ff);
if(params.cpOffset[0] > 0x1ff) params.cpOffset[0] -= 0x400;
params.cpOffset[1] = val >> 10;
if(params.cpOffset[1] > 0x1f) params.cpOffset[1] -= 0x40;
params.cpOffset[1] += params.cpOffset[0];
val = ((CREG_VAL(REG_KTAVSCALE) & 0xF0) >> 4) + 8;
i8 = (int8_t)(CREG_VAL(REG_KVTACP) & 0xFF);
params.cpKta = (float)i8 / (1<<val);
val = (CREG_VAL(REG_KTAVSCALE) & 0x0F00) >> 8;
i16 = CREG_VAL(REG_KVTACP) >> 8;
if(i16 > 0x7F) i16 -= 0x100;
params.cpKv = (float)i16 / (1<<val);
i16 = CREG_VAL(REG_KSTATGC) & 0xFF;
if(i16 > 0x7F) i16 -= 0x100;
params.tgc = (float)i16;
params.tgc /= 32.;
#ifdef EBUG
SEND("4 Tms="); printu(Tms); newline();
#endif
val = (CREG_VAL(REG_SCALEACC)>>12); // alpha_scale_CP
i16 = CREG_VAL(REG_ALPHA)>>10; // cp_P1_P0_ratio
if(i16 > 0x1F) i16 -= 0x40;
div = (float)(1<<val);
div *= (float)(1<<27);
params.cpAlpha[0] = (float)(CREG_VAL(REG_ALPHA) & 0x03FF) / div;
div = (float)(1<<7);
params.cpAlpha[1] = params.cpAlpha[0] * (1.f + (float)i16/div);
i8 = (int8_t)(CREG_VAL(REG_KSTATGC) >> 8);
params.KsTa = (float)i8/(1<<13);
div = 1<<((CREG_VAL(REG_CT34) & 0x0F) + 8); // kstoscale
val = CREG_VAL(REG_KSTO12);
i8 = (int8_t)(val & 0xFF);
params.ksTo[0] = 273.15f * i8 / div;
i8 = (int8_t)(val >> 8);
params.ksTo[1] = 273.15f * i8 / div;
val = CREG_VAL(REG_KSTO34);
i8 = (int8_t)(val & 0xFF);
params.ksTo[2] = 273.15f * i8 / div;
i8 = (int8_t)(val >> 8);
params.ksTo[3] = 273.15f * i8 / div;
params.CT[0] = 0.f; // 0degr - between ranges 1 and 2
val = CREG_VAL(REG_CT34);
mul = ((val & 0x3000)>>12)*10.f; // step
params.CT[1] = ((val & 0xF0)>>4)*mul; // CT3 - between ranges 2 and 3
params.CT[2] = ((val & 0x0F00) >> 8)*mul + params.CT[1]; // CT4 - between ranges 3 and 4
params.alphacorr[0] = 1.f/(1.f + params.ksTo[0] * 40.f);
params.alphacorr[1] = 1.f;
params.alphacorr[2] = (1.f + params.ksTo[2] * params.CT[1]);
params.alphacorr[3] = (1.f + params.ksTo[3] * (params.CT[2] - params.CT[1])) * params.alphacorr[2];
// Don't forget to check 'outlier' flags for wide purpose
#ifdef EBUG
SEND("end Tms="); printu(Tms);
NL();
#endif
return TRUE;
}
/**
* @brief process_subpage - calculate all parameters from `dataarray` into `mlx_image`
*/
static void process_subpage(){
DBG("process_subpage()");
SEND("Tms="); printu(Tms); newline();
SEND("subpage="); printu(subpageno); newline();
(void)subpageno; (void)simpleimage;
for(int i = 0; i < MLX_W; ++i){
printi((int8_t)dataarray[i]); bufputchar(' ');
} newline();
SEND("072a="); printuhex(IMD_VAL(REG_IVDDPIX));
SEND("\n0720="); printuhex(IMD_VAL(REG_ITAPTAT));
SEND("\n0700="); printuhex(IMD_VAL(REG_ITAVBE));
SEND("\n070a="); printuhex(IMD_VAL(REG_IGAIN)); newline();
int16_t i16a = (int16_t)IMD_VAL(REG_IVDDPIX);
float dvdd = i16a - params.vdd25;
dvdd = dvdd / params.kVdd;
SEND("Vd="); float2str(dvdd+3.3f, 2); newline();
i16a = (int16_t)IMD_VAL(REG_ITAPTAT);
int16_t i16b = (int16_t)IMD_VAL(REG_ITAVBE);
float dTa = (float)i16a / (i16a * params.alphaPTAT + i16b); // vptatart
dTa *= (float)(1<<18);
dTa = (dTa / (1 + params.KvPTAT*dvdd) - params.vPTAT25);
dTa = dTa / params.KtPTAT; // without 25degr - Ta0
SEND("Ta="); float2str(dTa+25., 2); newline();
i16a = (int16_t)IMD_VAL(REG_IGAIN);
float Kgain = params.gainEE / (float)i16a;
SEND("Kgain="); float2str(Kgain, 2); newline();
// now make first approximation to image
uint16_t pixno = 0; // current pixel number - for indexing in parameters etc
for(int row = 0; row < MLX_H; ++row){
int idx = (row&1)<<1; // index for params.kv
for(int col = 0; col < MLX_W; ++col, ++pixno){
uint8_t sp = (row&1)^(col&1); // subpage of current pixel
if(sp != subpageno) continue;
register float curval = (float)((int16_t)dataarray[pixno]) * Kgain; // gain compensation
curval -= params.offset[pixno] * (1.f + params.kta[pixno]*dTa) *
(1.f + params.kv[idx|(col&1)]*dvdd); // add offset
float IRcompens = curval; // IR_compensated
curval -= params.cpOffset[subpageno] * (1.f - params.cpKta * dTa) *
(1.f + params.cpKv * dvdd); // CP
if(!simpleimage){
curval = IRcompens - params.tgc * curval; // IR gradient compens
float alphaComp = params.alpha[pixno] - params.tgc * params.cpAlpha[subpageno];
alphaComp /= 1.f + params.KsTa * dTa;
// calculate To for basic range
float Tar = dTa + 273.15f + 25.f;
Tar = Tar*Tar*Tar*Tar;
float ac3 = alphaComp*alphaComp*alphaComp;
float Sx = ac3*IRcompens + alphaComp*ac3*Tar;
Sx = params.KsTa * sqrt(sqrt(Sx));
float To = IRcompens / (alphaComp * (1.f - params.ksTo[1]) + Sx) + Tar;
curval = sqrt(sqrt(To)) - 273.15; // To
// TODO: extended
}
mlx_image[pixno] = curval;
}
}
SEND("Tms="); printu(Tms); newline();
NL();
}
// start image acquiring for next subpage
static int startima(){
DBG("startima()");
// write `overwrite` flag twice
if(!write_reg(REG_CONTROL, reg_control_val[subpageno]) ||
!write_reg(REG_STATUS, REG_STATUS_OVWEN) ||
!write_reg(REG_STATUS, REG_STATUS_OVWEN)) return FALSE;
return TRUE;
}
/**
* @brief parse_buffer - swap bytes in `dataarray` (after receiving or before transmitting data)
*
static void parse_buffer(){
uint16_t *ptr = dataarray;
DBG("parse_buffer()");
for(uint16_t i = 0; i < portionlen; ++i, ++ptr){
*ptr = __REV16(*ptr);
#if 0
printu(i);
addtobuf(" ");
printuhex(*ptr);
newline();
#endif
}
#if 0
sendbuf();
#endif
}*/
/**
* @brief mlx90640_process - main finite-state machine
*/
void mlx90640_process(){
#define chstate(s) do{errctr = 0; Tlast = Tms; mlx_state = s;}while(0)
#define chkerr() do{if(++errctr > MLX_MAXERR_COUNT){chstate(M_ERROR); DBG("-> M_ERROR");}}while(0)
#define chktmout() do{if(Tms - Tlast > MLX_TIMEOUT){chstate(M_ERROR); DBG("Timeout! -> M_ERROR"); }}while(0)
static int errctr = 0;
static uint32_t Tlast = 0;
uint16_t reg, N;
/*
uint8_t gotdata = 0;
if(i2cDMAr == I2C_DMA_READY){ // convert received data into little-endian
i2cDMAr = I2C_DMA_RELAX;
parse_buffer();
gotdata = 1;
}*/
switch(mlx_state){
case M_FIRSTSTART: // init working mode by request
if(write_reg(REG_CONTROL, reg_control_val[0])
&& read_reg(REG_CONTROL, &reg)){
SEND("REG_CTRL="); printuhex(reg); NL();
if(read_reg(REG_STATUS, &reg)){
SEND("REG_STATUS="); printuhex(reg); NL();}
/*
#define PARTD 512
if(read_data_dma(REG_CALIDATA, PARTD)){
chstate(M_READCONF);
DBG("-> M_READCONF");
}else chkerr();
*/
N = REG_CALIDATA_LEN;
if(read_data(REG_CALIDATA, &N)){
chstate(M_READCONF);
DBG("-> M_READCONF");
}else chkerr();
}else chkerr();
break;
case M_READCONF:
//if(gotdata){ // calculate calibration parameters
/* uint16_t *d = &dataarray[PARTD];
for(uint16_t r = REG_CALIDATA+PARTD; r < REG_CALIDATA + REG_CALIDATA_LEN; ++r){
if(!read_reg(r, d++)){
chstate(M_FIRSTSTART);
DBG("can't read all confdata -> M_FIRSTSTART");
return;
}
}*/
if(get_parameters()){
chstate(M_RELAX);
DBG("-> M_RELAX");
}else{ // error -> go to M_FIRSTSTART again
chstate(M_FIRSTSTART);
DBG("-> M_FIRSTSTART");
}
//}else chktmout();
break;
case M_STARTIMA:
if(startima()){
chstate(M_PROCESS);
DBG("-> M_PROCESS");
}else{
chstate(M_ERROR);
DBG("can't start subpage -> M_ERROR");
}
break;
case M_PROCESS:
if(read_reg(REG_STATUS, &reg)){
if(reg & REG_STATUS_NEWDATA){
if(subpageno != (reg & REG_STATUS_SPNO)){
chstate(M_ERROR);
DBG("wrong subpage number -> M_ERROR");
}else{ // all OK, run image reading
write_reg(REG_STATUS, 0); // clear rdy bit
/*
if(read_data_dma(REG_IMAGEDATA, PARTD)){
chstate(M_READOUT);
DBG("-> M_READOUT");
}else chkerr();
*/
N = MLX_PIXARRSZ;
if(read_data(REG_IMAGEDATA, &N)){
chstate(M_READOUT);
DBG("-> M_READOUT");
}else chkerr();
}
}else chktmout();
}else chkerr();
break;
case M_READOUT:
//if(gotdata){
/* uint16_t *d = &dataarray[PARTD];
for(uint16_t r = REG_IMAGEDATA+PARTD; r < REG_IMAGEDATA+MLX_PIXARRSZ; ++r){
if(!read_reg(r, d++)){
chstate(M_ERROR);
DBG("can't read all confdata -> M_ERROR");
return;
}
}*/
process_subpage();
subpageno = !subpageno;
DBG("Subpage ready");
chstate(M_RELAX);
/*
if(++subpageno > 1){ // image ready
subpageno = 0;
chstate(M_RELAX);
DBG("Image READY!");
}else{
chstate(M_STARTIMA);
DBG("-> M_STARTIMA");
}*/
//}else chktmout();
break;
case M_POWERON:
if(Tms - Tlast > MLX_POWON_WAIT){
if(params.kVdd == 0){ // get all parameters
chstate(M_FIRSTSTART);
DBG("M_FIRSTSTART");
}else{ // rewrite settings register
if(write_reg(REG_CONTROL, reg_control_val[0])){
chstate(M_RELAX);
DBG("-> M_RELAX");
}else chkerr();
}
}
break;
case M_POWEROFF1:
MLXPOW_OFF();
chstate(M_POWEROFF);
DBG("-> M_POWEROFF");
break;
case M_POWEROFF:
if(Tms - Tlast > MLX_POWOFF_WAIT){
MLXPOW_ON();
chstate(M_POWERON);
DBG("-> M_POWERON");
}
break;
default:
break;
}
}
void mlx90640_restart(){
DBG("restart");
mlx_state = M_POWEROFF1;
}
// if state of MLX allows, make an image else return error
// @param simple ==1 for simplest image processing (without T calibration)
int mlx90640_take_image(uint8_t simple){
simpleimage = simple;
if(mlx_state == M_ERROR){
DBG("Restart I2C");
i2c_setup(i2cDMAr != I2C_DMA_NOTINIT);
} else if(mlx_state != M_RELAX) return FALSE;
if(params.kVdd == 0){ // no parameters -> make first run
mlx_state = M_FIRSTSTART;
DBG("no params -> M_FIRSTSTART");
return TRUE;
}
//subpageno = 0;
mlx_state = M_STARTIMA;
DBG("-> M_STARTIMA");
return TRUE;
}

View File

@@ -0,0 +1,96 @@
/*
* This file is part of the MLX90640 project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef MLX90640__
#define MLX90640__
#include <stm32f1.h>
// timeout for reading operations, ms
#define MLX_TIMEOUT 1000
// counter of errors, when > max -> M_ERROR
#define MLX_MAXERR_COUNT 10
// wait after power off, ms
#define MLX_POWOFF_WAIT 500
// wait after power on, ms
#define MLX_POWON_WAIT 2000
// amount of pixels
#define MLX_W (32)
#define MLX_H (24)
#define MLX_PIXNO (MLX_W*MLX_H)
// pixels + service data
#define MLX_PIXARRSZ (MLX_PIXNO + 64)
typedef struct{
int16_t kVdd;
int16_t vdd25;
float KvPTAT;
float KtPTAT;
int16_t vPTAT25;
float alphaPTAT;
int16_t gainEE;
float tgc;
float cpKv; // K_V_CP
float cpKta; // K_Ta_CP
float KsTa;
float CT[3]; // range borders (0, 160, 320 degrC?)
float ksTo[4]; // K_S_To for each range * 273.15
float alphacorr[4]; // Alpha_corr for each range
float alpha[MLX_PIXNO]; // full - with alpha_scale
float offset[MLX_PIXNO];
float kta[MLX_PIXNO]; // full K_ta - with scale1&2
float kv[4]; // full - with scale; 0 - odd row, odd col; 1 - odd row even col; 2 - even row, odd col; 3 - even row, even col
float cpAlpha[2]; // alpha_CP_subpage 0 and 1
int16_t cpOffset[2];
} MLX90640_params;
extern MLX90640_params params;
typedef enum{
M_ERROR, // error: need to reboot sensor
M_RELAX, // base state
M_FIRSTSTART, // first start after power on
M_READCONF, // read configuration data
M_STARTIMA, // start image aquiring
M_PROCESS, // process subpage - wait for image ready
M_READOUT, // wait while subpage data be read
M_POWERON, // wait for 100ms after power is on before -> firststart
M_POWEROFF1, // turn off power
M_POWEROFF, // wait for 500ms without power
//
M_STATES_AMOUNT // amount of states
} mlx90640_state;
extern mlx90640_state mlx_state;
extern float mlx_image[MLX_PIXNO];
// default I2C address
#define MLX_DEFAULT_ADDR (0x33)
// max datalength by one read (in 16-bit values)
#define MLX_DMA_MAXLEN (832)
int read_reg(uint16_t reg, uint16_t *val);
int write_reg(uint16_t reg, uint16_t val);
uint16_t *read_data(uint16_t reg, uint16_t *N);
int read_data_dma(uint16_t reg, int N);
void mlx90640_process();
int mlx90640_take_image(uint8_t simple);
void mlx90640_restart();
#endif // MLX90640__

View File

@@ -0,0 +1,82 @@
/*
* This file is part of the MLX90640 project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef MLX90640_REGS_H__
#define MLX90640_REGS_H__
#define REG_STATUS 0x8000
#define REG_STATUS_OVWEN (1<<4)
#define REG_STATUS_NEWDATA (1<<3)
#define REG_STATUS_SPNO (1<<0)
#define REG_STATUS_SPMASK (3<<0)
#define REG_CONTROL 0x800D
#define REG_CONTROL_CHESS (1<<12)
#define REG_CONTROL_RES18 (2<<10)
#define REG_CONTROL_RESMASK (3<<10)
#define REG_CONTROL_REFR_2HZ (2<<7)
#define REG_CONTROL_SUBP1 (1<<4)
#define REG_CONTROL_SUBPMASK (3<<4)
#define REG_CONTROL_SUBPSEL (1<<3)
#define REG_CONTROL_DATAHOLD (1<<2)
#define REG_CONTROL_SUBPEN (1<<0)
// calibration data start & len
#define REG_CALIDATA 0x2410
#define REG_CALIDATA_LEN 816
#define REG_APTATOCCS 0x2410
#define REG_OSAVG 0x2411
#define REG_OCCROW14 0x2412
#define REG_OCCCOL14 0x2418
#define REG_SCALEACC 0x2420
#define REG_SENSIVITY 0x2421
#define REG_ACCROW14 0x2422
#define REG_ACCCOL14 0x2428
#define REG_GAIN 0x2430
#define REG_PTAT 0x2431
#define REG_KVTPTAT 0x2432
#define REG_VDD 0x2433
#define REG_KVAVG 0x2434
#define REG_ILCHESS 0x2435
#define REG_KTAAVGODDCOL 0x2436
#define REG_KTAAVGEVENCOL 0x2437
#define REG_KTAVSCALE 0x2438
#define REG_ALPHA 0x2439
#define REG_CPOFF 0x243A
#define REG_KVTACP 0x243B
#define REG_KSTATGC 0x243C
#define REG_KSTO12 0x243D
#define REG_KSTO34 0x243E
#define REG_CT34 0x243F
#define REG_OFFAK1 0x2440
// index of register in array (from REG_CALIDATA)
#define CREG_IDX(addr) ((addr)-REG_CALIDATA)
#define REG_IMAGEDATA 0x0400
#define REG_ITAVBE 0x0700
#define REG_ICPSP0 0x0708
#define REG_IGAIN 0x070A
#define REG_ITAPTAT 0x0720
#define REG_ICPSP1 0x0728
#define REG_IVDDPIX 0x072A
// indeg of register in array (from REG_IMAGEDATA)
#define IMD_IDX(addr) ((addr)-REG_IMAGEDATA)
#endif // MLX90640_REGS_H__

View File

@@ -0,0 +1,243 @@
/*
* This file is part of the MLX90640 project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "i2c.h"
#include "mlx90640.h"
#include "proto.h"
#include "strfunct.h"
#include "usb.h"
#include "version.inc"
extern uint32_t Tms;
static const char* _states[M_STATES_AMOUNT] = {
[M_ERROR] = "error",
[M_RELAX] = "do nothing",
[M_FIRSTSTART] = "first start",
[M_READCONF] = "read config",
[M_STARTIMA] = "start image",
[M_PROCESS] = "process subframe",
[M_READOUT] = "read subpage data",
[M_POWERON] = "wait after power on",
[M_POWEROFF1] = "turn power off",
[M_POWEROFF] = "wait without power",
};
// dump floating point array 24x32
static void dumpfarr(float *arr){
for(int row = 0; row < 24; ++row){
for(int col = 0; col < 32; ++col){
float2str(*arr++, 2); bufputchar(' ');
}
newline();
}
}
static void dumpparams(){
SEND("\nkVdd="); printi(params.kVdd);
SEND("\nvdd25="); printi(params.vdd25);
SEND("\nKvPTAT="); float2str(params.KvPTAT, 4);
SEND("\nKtPTAT="); float2str(params.KtPTAT, 4);
SEND("\nvPTAT25="); printi(params.vPTAT25);
SEND("\nalphaPTAT="); float2str(params.alphaPTAT, 2);
SEND("\ngainEE="); printi(params.gainEE);
SEND("\nPixel offset parameters:\n");
float *offset = params.offset;
for(int row = 0; row < 24; ++row){
for(int col = 0; col < 32; ++col){
float2str(*offset++, 2); bufputchar(' ');
}
newline();
}
SEND("K_talpha:\n");
dumpfarr(params.kta);
SEND("Kv: ");
for(int i = 0; i < 4; ++i){
float2str(params.kv[i], 2); bufputchar(' ');
}
SEND("\ncpOffset=");
printi(params.cpOffset[0]); SEND(", "); printi(params.cpOffset[1]);
SEND("\ncpKta="); float2str(params.cpKta, 2);
SEND("\ncpKv="); float2str(params.cpKv, 2);
SEND("\ntgc="); float2str(params.tgc, 2);
SEND("\ncpALpha="); float2str(params.cpAlpha[0], 2);
SEND(", "); float2str(params.cpAlpha[1], 2);
SEND("\nKsTa="); float2str(params.KsTa, 2);
SEND("\nAlpha:\n");
dumpfarr(params.alpha);
SEND("\nCT3="); float2str(params.CT[1], 2);
SEND("\nCT4="); float2str(params.CT[2], 2);
for(int i = 0; i < 4; ++i){
SEND("\nKsTo"); bufputchar('0'+i); bufputchar('=');
float2str(params.ksTo[i], 2);
SEND("\nalphacorr"); bufputchar('0'+i); bufputchar('=');
float2str(params.alphacorr[i], 2);
}
NL();
}
static void dumpimage(){
float *idata = mlx_image;
for(int row = 0; row < MLX_H; ++row){
for(int col = 0; col < MLX_W; ++col, ++idata){
float2str(*idata,1); bufputchar(' ');
}
newline();
}
NL();
}
const char *parse_cmd(char *buf){
int32_t Num = 0;
uint16_t r, d;
uint16_t *data;
const float pi = 3.1415927f, e = 2.7182818f;
char *ptr, cmd = *buf++;
switch(cmd){
case 'a':
if(buf != getnum(buf, &Num)){
if(Num & 0x80) return "Enter 7bit address";
i2c_set_addr7(Num);
return "Changed";
}else return "Wrong address";
break;
case 'd':
if(buf != (ptr = getnum(buf, &Num))){
r = Num;
if(ptr != getnum(ptr, &Num)){
if(Num < 1 || Num > MLX_DMA_MAXLEN) return "0<N<=832";
if(!read_data_dma(r, Num)) return("Can't read");
else return "OK";
}else return "Need amount";
}else return "Need reg";
break;
case 'E':
case 'e':
if(!mlx90640_take_image(cmd == 'e')) return "FAILED";
else return "OK";
break;
case 'f':
SEND("Float test: ");
float2str(0.f, 2); addtobuf(", ");
float2str(pi, 1); addtobuf(", ");
float2str(-e, 2); addtobuf(", ");
float2str(-pi, 3); addtobuf(", ");
float2str(e, 4); addtobuf(", ");
uint32_t uu = INF | 0x80000000;
float *f = (float*)&uu;
float2str(*f, 4); addtobuf(", ");
uu = NAN;
f = (float*)&uu;
float2str(*f, 4);
NL();
return NULL;
break;
case 'g':
if(buf != (ptr = getnum(buf, &Num))){
r = Num;
if(ptr != getnum(ptr, &Num)){
if(Num < 1 || Num > MLX_DMA_MAXLEN) return "N from 0 to 832";
uint16_t od = d = Num;
if(!(data = read_data(r, &d))){
SEND("Can't read\n");
return NULL;
}
if(d != od){
addtobuf("Got only ");
printu(d);
addtobuf(" values\n");
}
for(uint16_t i = 0; i < d; ++i){
printuhex(r + i);
addtobuf(" ");
printuhex(data[i]);
newline();
}
sendbuf();
return NULL;
}else return "Need amount";
}else return "Need reg";
break;
case 'I':
i2c_setup(TRUE);
return "I2C restarted";
break;
case 'M':
SEND("MLX state: "); SEND(_states[mlx_state]);
SEND("\npower="); printu(MLXPOW_VAL()); NL();
return NULL;
break;
case 'O':
mlx90640_restart();
return "Power off/on";
break;
case 'P':
dumpparams();
return NULL;
break;
case 'r':
if(buf != (ptr = getnum(buf, &Num))){
if(read_reg(Num, &d)){
printuhex(d); NL();
return NULL;
}else return "Can't read";
}else return "Need register address";
break;
case 'R':
USB_sendstr("Soft reset\n");
NVIC_SystemReset();
break;
case 'S':
dumpimage();
return NULL;
break;
case 'T':
SEND("Tms="); printu(Tms); NL();
return NULL;
break;
case 'w':
if(buf == (ptr = getnum(buf, &Num))) return "Need register";
r = Num;
if(ptr == getnum(ptr, &Num)) return "Need data";
if(write_reg(r, Num)) return "OK";
else return "Failed";
break;
default: // help
addtobuf(
"MLX90640 build #" BUILD_NUMBER " @" BUILD_DATE "\n\n"
"'a addr' - change MLX I2C address to `addr`\n"
"'d reg N' - read registers starting from `reg` using DMA\n"
"'Ee' - expose image: E - full, e - simple\n"
"'f' - test float printf (0.00, 3.1, -2.72, -3.142, 2.7183, -INF, NAN)\n"
"'g reg N' - read N registers starting from `reg`\n"
"'I' - restart I2C\n"
"'M' - MLX state\n"
"'O' - turn On or restart MLX sensor\n"
"'P' - dump params\n"
"'r reg' - read `reg`\n"
"'R' - software reset\n"
"'S' - show image\n"
"'T' - get Tms\n"
"'w reg dword' - write `dword` to `reg`\n"
);
NL();
return NULL;
break;
}
return NULL;
}

View File

@@ -0,0 +1,24 @@
/*
* This file is part of the MLX90640 project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef PROTO_H__
#define PROTO_H__
const char *parse_cmd(char *buf);
#endif // PROTO_H__

View File

@@ -0,0 +1,276 @@
/*
* This file is part of the MLX90640 project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "hardware.h"
#include "strfunct.h"
#include "usb.h"
#include <string.h> // strlen
// usb getline
char *get_USB(){
static char tmpbuf[IBUFSZ+1], *curptr = tmpbuf;
static int rest = IBUFSZ;
uint8_t x = USB_receive((uint8_t*)curptr);
curptr[x] = 0;
if(!x) return NULL;
if(curptr[x-1] == '\n'){
curptr[x] = 0;
curptr = tmpbuf;
rest = IBUFSZ;
return tmpbuf;
}
curptr += x; rest -= x;
if(rest <= 63){ // buffer overflow
curptr = tmpbuf;
rest = IBUFSZ;
}
return NULL;
}
static char buff[OBUFSZ+1], *bptr = buff;
static uint16_t blen = 0;
void sendbuf(){
if(blen == 0) return;
*bptr = 0;
USB_sendstr(buff);
bptr = buff;
blen = 0;
}
void bufputchar(char ch){
if(blen > OBUFSZ-1){
sendbuf();
}
*bptr++ = ch;
++blen;
}
void addtobuf(const char *txt){
if(!txt) return;
while(*txt) bufputchar(*txt++);
}
// print 32bit unsigned int
void printu(uint32_t val){
char buf[11], *bufptr = &buf[10];
*bufptr = 0;
if(!val){
*(--bufptr) = '0';
}else{
while(val){
register uint32_t o = val;
val /= 10;
*(--bufptr) = (o - 10*val) + '0';
}
}
addtobuf(bufptr);
}
void printi(int32_t val){
if(val < 0){
val = -val;
bufputchar('-');
}
printu((uint32_t)val);
}
// print 32bit unsigned int as hex
void printuhex(uint32_t val){
addtobuf("0x");
uint8_t *ptr = (uint8_t*)&val + 3;
int i, j, z = 1;
for(i = 0; i < 4; ++i, --ptr){
if(*ptr == 0){ // omit leading zeros
if(i == 3) z = 0;
if(z) continue;
}
else z = 0;
for(j = 1; j > -1; --j){
uint8_t half = (*ptr >> (4*j)) & 0x0f;
if(half < 10) bufputchar(half + '0');
else bufputchar(half - 10 + 'a');
}
}
}
char *omit_spaces(char *buf){
while(*buf){
if(*buf != ' ' && *buf != '\t') break;
++buf;
}
return buf;
}
// THERE'S NO OVERFLOW PROTECTION IN NUMBER READ PROCEDURES!
// read decimal number
static char *getdec(const char *buf, int32_t *N){
int32_t num = 0;
int positive = TRUE;
if(*buf == '-'){
positive = FALSE;
++buf;
}
while(*buf){
char c = *buf;
if(c < '0' || c > '9'){
break;
}
num *= 10;
num += c - '0';
++buf;
}
*N = (positive) ? num : -num;
return (char *)buf;
}
// read hexadecimal number (without 0x prefix!)
static char *gethex(const char *buf, int32_t *N){
uint32_t num = 0;
while(*buf){
char c = *buf;
uint8_t M = 0;
if(c >= '0' && c <= '9'){
M = '0';
}else if(c >= 'A' && c <= 'F'){
M = 'A' - 10;
}else if(c >= 'a' && c <= 'f'){
M = 'a' - 10;
}
if(M){
num <<= 4;
num += c - M;
}else{
break;
}
++buf;
}
*N = (int32_t)num;
return (char *)buf;
}
// read binary number (without 0b prefix!)
static char *getbin(const char *buf, int32_t *N){
uint32_t num = 0;
while(*buf){
char c = *buf;
if(c < '0' || c > '1'){
break;
}
num <<= 1;
if(c == '1') num |= 1;
++buf;
}
*N = (int32_t)num;
return (char *)buf;
}
/**
* @brief getnum - read uint32_t from string (dec, hex or bin: 127, 0x7f, 0b1111111)
* @param buf - buffer with number and so on
* @param N - the number read
* @return pointer to first non-number symbol in buf (if it is == buf, there's no number)
*/
char *getnum(char *txt, int32_t *N){
txt = omit_spaces(txt);
if(*txt == '0'){
if(txt[1] == 'x' || txt[1] == 'X') return gethex(txt+2, N);
if(txt[1] == 'b' || txt[1] == 'B') return getbin(txt+2, N);
}
return getdec(txt, N);
}
// be careful: if pow10 would be bigger you should change str[] size!
static const float pwr10[] = {1., 10., 100., 1000., 10000.};
static const float rounds[] = {0.5, 0.05, 0.005, 0.0005, 0.00005};
#define P10L (sizeof(pwr10)/sizeof(uint32_t) - 1)
void float2str(float x, uint8_t prec){
if(prec > P10L) prec = P10L;
static char str[16] = {0}; // -117.5494E-36\0 - 14 symbols max!
uint32_t *u = (uint32_t*)&x;
/* if(*u && (*u == (*u & DENORM))){
SEND("DENORM"); return;
}*/
switch(*u){
case INF:
SEND("INF");
return;
break;
case MINF:
SEND("-INF");
return;
break;
case NAN:
SEND("NAN");
return;
default:
break;
}
char *s = str + 14; // go to end of buffer
uint8_t minus = 0;
if(x < 0){
x = -x;
minus = 1;
}
int pow = 0; // xxxEpow
// now convert float to 1.xxxE3y
while(x > 1000.f){
x /= 1000.f;
pow += 3;
}
if(x > 0.) while(x < 1.){
x *= 1000.f;
pow -= 3;
}
// print Eyy
if(pow){
uint8_t m = 0;
if(pow < 0){pow = -pow; m = 1;}
while(pow){
register int p10 = pow/10;
*s-- = '0' + (pow - 10*p10);
pow = p10;
}
if(m) *s-- = '-';
*s-- = 'E';
}
// now our number is in [1, 1000]
uint32_t units;
if(prec){
units = (uint32_t) x;
uint32_t decimals = (uint32_t)((x-units+rounds[prec])*pwr10[prec]);
// print decimals
while(prec){
register int d10 = decimals / 10;
*s-- = '0' + (decimals - 10*d10);
decimals = d10;
--prec;
}
// decimal point
*s-- = '.';
}else{ // without decimal part
units = (uint32_t) (x + 0.5f);
}
// print main units
if(units == 0) *s-- = '0';
else while(units){
register uint32_t u10 = units / 10;
*s-- = '0' + (units - 10*u10);
units = u10;
}
if(minus) *s-- = '-';
addtobuf(s+1);
}

View File

@@ -0,0 +1,67 @@
/*
* This file is part of the MLX90640 project.
* Copyright 2022 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef STRFUNCT_H__
#define STRFUNCT_H__
#include "stm32f1.h"
#ifndef DENORM
#define DENORM (0x007FFFFF)
#endif
#ifndef NAN
#define NAN (0x7FC00000)
#endif
#ifndef INF
#define INF (0x7F800000)
#endif
#ifndef MINF
#define MINF (0xFF800000)
#endif
#define OBUFSZ (64)
#define IBUFSZ (256)
// macro for static strings
#define SEND(str) do{addtobuf(str);}while(0)
#ifdef EBUG
#define x__(a) #a
#define STR(a) x__(a)
#define DBG(str) do{addtobuf(__FILE__ " (L" STR(__LINE__) "): " str); NL();}while(0)
#else
#define DBG(str)
#endif
#define newline() do{bufputchar('\n');}while(0)
// newline & send buffer
#define NL() do{bufputchar('\n'); sendbuf();}while(0)
char *get_USB();
void addtobuf(const char *txt);
void bufputchar(char ch);
void printu(uint32_t val);
void printi(int32_t val);
void printuhex(uint32_t val);
void sendbuf();
char *omit_spaces(char *buf);
char *getnum(char *buf, int32_t *N);
void float2str(float x, uint8_t prec);
#endif // STRFUNCT_H__

View File

@@ -0,0 +1,168 @@
/*
* This file is part of the MLX90640 project.
* Copyright 2020 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "usb.h"
#include "usb_lib.h"
static volatile uint8_t tx_succesfull = 1;
static volatile uint8_t rxNE = 0;
// interrupt IN handler (never used?)
static void EP1_Handler(){
uint16_t epstatus = KEEP_DTOG(USB->EPnR[1]);
if(RX_FLAG(epstatus)) epstatus = (epstatus & ~USB_EPnR_STAT_TX) ^ USB_EPnR_STAT_RX; // set valid RX
else epstatus = epstatus & ~(USB_EPnR_STAT_TX|USB_EPnR_STAT_RX);
// clear CTR
epstatus = (epstatus & ~(USB_EPnR_CTR_RX|USB_EPnR_CTR_TX));
USB->EPnR[1] = epstatus;
}
// data IN/OUT handlers
static void transmit_Handler(){ // EP3IN
tx_succesfull = 1;
uint16_t epstatus = KEEP_DTOG_STAT(USB->EPnR[3]);
// clear CTR keep DTOGs & STATs
USB->EPnR[3] = (epstatus & ~(USB_EPnR_CTR_TX)); // clear TX ctr
}
static void receive_Handler(){ // EP2OUT
rxNE = 1;
uint16_t epstatus = KEEP_DTOG_STAT(USB->EPnR[2]);
USB->EPnR[2] = (epstatus & ~(USB_EPnR_CTR_RX)); // clear RX ctr
}
void USB_setup(){
NVIC_DisableIRQ(USB_LP_CAN1_RX0_IRQn);
NVIC_DisableIRQ(USB_HP_CAN1_TX_IRQn);
RCC->APB1ENR |= RCC_APB1ENR_USBEN;
USB->CNTR = USB_CNTR_FRES; // Force USB Reset
for(uint32_t ctr = 0; ctr < 72000; ++ctr) nop(); // wait >1ms
//uint32_t ctr = 0;
USB->CNTR = 0;
USB->BTABLE = 0;
USB->DADDR = 0;
USB->ISTR = 0;
USB->CNTR = USB_CNTR_RESETM | USB_CNTR_WKUPM; // allow only wakeup & reset interrupts
NVIC_EnableIRQ(USB_LP_CAN1_RX0_IRQn);
}
static int usbwr(const uint8_t *buf, uint16_t l){
uint32_t ctra = 1000000;
while(--ctra && tx_succesfull == 0){
IWDG->KR = IWDG_REFRESH;
}
if(tx_succesfull == 0) return 1;
tx_succesfull = 0;
EP_Write(3, buf, l);
/* ctra = 1000000;
while(--ctra && tx_succesfull == 0){
IWDG->KR = IWDG_REFRESH;
}
if(tx_succesfull == 0){usbON = 0; return 1;} // usb is OFF?
*/
return 0;
}
static uint8_t usbbuff[USB_TXBUFSZ-1]; // temporary buffer (63 - to prevent need of ZLP)
static uint8_t buflen = 0; // amount of symbols in usbbuff
// send next up to 63 bytes of data in usbbuff
static void send_next(){
if(!buflen || !tx_succesfull) return;
tx_succesfull = 0;
EP_Write(3, usbbuff, buflen);
buflen = 0;
}
// unblocking sending - just fill a buffer
void USB_send(const uint8_t *buf, uint16_t len){
if(!usbON || !len) return;
if(len > USB_TXBUFSZ-1 - buflen){
usbwr(usbbuff, buflen);
buflen = 0;
}
if(len > USB_TXBUFSZ-1){
USB_send_blk(buf, len);
return;
}
while(len--) usbbuff[buflen++] = *buf++;
}
// send zero-terminated string
void USB_sendstr(const char *str){
uint16_t l = 0;
const char *ptr = str;
while(*ptr++) ++l;
USB_send((uint8_t*)str, l);
}
// blocking sending
void USB_send_blk(const uint8_t *buf, uint16_t len){
if(!usbON || !len) return; // USB disconnected
if(buflen){
usbwr(usbbuff, buflen);
buflen = 0;
}
int needzlp = 0;
while(len){
if(len == USB_TXBUFSZ) needzlp = 1;
uint16_t s = (len > USB_TXBUFSZ) ? USB_TXBUFSZ : len;
if(usbwr(buf, s)) return;
len -= s;
buf += s;
}
if(needzlp){
usbwr(NULL, 0);
}
}
void usb_proc(){
switch(USB_Dev.USB_Status){
case USB_STATE_CONFIGURED:
// make new BULK endpoint
// Buffer have 1024 bytes, but last 256 we use for CAN bus (30.2 of RM: USB main features)
EP_Init(1, EP_TYPE_INTERRUPT, USB_EP1BUFSZ, 0, EP1_Handler); // IN1 - transmit
EP_Init(2, EP_TYPE_BULK, 0, USB_RXBUFSZ, receive_Handler); // OUT2 - receive data
EP_Init(3, EP_TYPE_BULK, USB_TXBUFSZ, 0, transmit_Handler); // IN3 - transmit data
USB_Dev.USB_Status = USB_STATE_CONNECTED;
break;
case USB_STATE_DEFAULT:
case USB_STATE_ADDRESSED:
if(usbON){
usbON = 0;
}
break;
default: // USB_STATE_CONNECTED - send next data portion
if(!usbON) return;
send_next();
}
}
/**
* @brief USB_receive
* @param buf (i) - buffer[64] for received data
* @return amount of received bytes
*/
uint8_t USB_receive(uint8_t *buf){
if(!usbON || !rxNE) return 0;
uint8_t sz = EP_Read(2, (uint16_t*)buf);
uint16_t epstatus = KEEP_DTOG(USB->EPnR[2]);
// keep stat_tx & set ACK rx
USB->EPnR[2] = (epstatus & ~(USB_EPnR_STAT_TX)) ^ USB_EPnR_STAT_RX;
rxNE = 0;
return sz;
}

View File

@@ -0,0 +1,34 @@
/*
* This file is part of the MLX90640 project.
* Copyright 2020 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __USB_H__
#define __USB_H__
#include "hardware.h"
#define BUFFSIZE (64)
void USB_setup();
void usb_proc();
void USB_send(const uint8_t *buf, uint16_t len);
void USB_sendstr(const char *str);
void USB_send_blk(const uint8_t *buf, uint16_t len);
uint8_t USB_receive(uint8_t *buf);
#endif // __USB_H__

View File

@@ -0,0 +1,102 @@
/*
* This file is part of the MLX90640 project.
* Copyright 2020 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __USB_DEFS_H__
#define __USB_DEFS_H__
#include <stm32f1.h>
// max endpoints number
#define STM32ENDPOINTS 8
/**
* Buffers size definition
**/
#define USB_BTABLE_SIZE 512
// first 64 bytes of USB_BTABLE are registers!
//#define USB_EP0_BASEADDR 64
// for USB FS EP0 buffers are from 8 to 64 bytes long (64 for PL2303)
#define USB_EP0_BUFSZ 64
// USB transmit buffer size (64 for PL2303)
#define USB_TXBUFSZ 64
// USB receive buffer size (64 for PL2303)
#define USB_RXBUFSZ 64
// EP1 - interrupt - buffer size
#define USB_EP1BUFSZ 8
#define USB_BTABLE_BASE 0x40006000
#define USB_BASE ((uint32_t)0x40005C00)
#define USB ((USB_TypeDef *) USB_BASE)
#ifdef USB_BTABLE
#undef USB_BTABLE
#endif
#define USB_BTABLE ((USB_BtableDef *)(USB_BTABLE_BASE))
#define USB_ISTR_EPID 0x0000000F
#define USB_FNR_LSOF_0 0x00000800
#define USB_FNR_lSOF_1 0x00001000
#define USB_LPMCSR_BESL_0 0x00000010
#define USB_LPMCSR_BESL_1 0x00000020
#define USB_LPMCSR_BESL_2 0x00000040
#define USB_LPMCSR_BESL_3 0x00000080
#define USB_EPnR_CTR_RX 0x00008000
#define USB_EPnR_DTOG_RX 0x00004000
#define USB_EPnR_STAT_RX 0x00003000
#define USB_EPnR_STAT_RX_0 0x00001000
#define USB_EPnR_STAT_RX_1 0x00002000
#define USB_EPnR_SETUP 0x00000800
#define USB_EPnR_EP_TYPE 0x00000600
#define USB_EPnR_EP_TYPE_0 0x00000200
#define USB_EPnR_EP_TYPE_1 0x00000400
#define USB_EPnR_EP_KIND 0x00000100
#define USB_EPnR_CTR_TX 0x00000080
#define USB_EPnR_DTOG_TX 0x00000040
#define USB_EPnR_STAT_TX 0x00000030
#define USB_EPnR_STAT_TX_0 0x00000010
#define USB_EPnR_STAT_TX_1 0x00000020
#define USB_EPnR_EA 0x0000000F
#define USB_COUNTn_RX_BLSIZE 0x00008000
#define USB_COUNTn_NUM_BLOCK 0x00007C00
#define USB_COUNTn_RX 0x0000003F
#ifdef USB_TypeDef
#define USB_TypeDef USB_TypeDef_custom
#endif
typedef struct {
__IO uint32_t EPnR[STM32ENDPOINTS];
__IO uint32_t RESERVED[STM32ENDPOINTS];
__IO uint32_t CNTR;
__IO uint32_t ISTR;
__IO uint32_t FNR;
__IO uint32_t DADDR;
__IO uint32_t BTABLE;
} USB_TypeDef;
typedef struct{
__IO uint32_t USB_ADDR_TX;
__IO uint32_t USB_COUNT_TX;
__IO uint32_t USB_ADDR_RX;
__IO uint32_t USB_COUNT_RX;
} USB_EPDATA_TypeDef;
typedef struct{
__IO USB_EPDATA_TypeDef EP[STM32ENDPOINTS];
} USB_BtableDef;
#endif // __USB_DEFS_H__

View File

@@ -0,0 +1,476 @@
/*
* This file is part of the MLX90640 project.
* Copyright 2020 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdint.h>
#include "usb_lib.h"
ep_t endpoints[STM32ENDPOINTS];
usb_dev_t USB_Dev;
static usb_LineCoding lineCoding = {115200, 0, 0, 8};
static config_pack_t setup_packet;
static uint8_t ep0databuf[EP0DATABUF_SIZE];
static uint8_t ep0dbuflen = 0;
usb_LineCoding getLineCoding(){return lineCoding;}
uint8_t usbON = 0; // device disconnected from terminal
// definition of parts common for USB_DeviceDescriptor & USB_DeviceQualifierDescriptor
#define bcdUSB_L 0x10
#define bcdUSB_H 0x01
#define bDeviceClass 0
#define bDeviceSubClass 0
#define bDeviceProtocol 0
#define bNumConfigurations 1
static const uint8_t USB_DeviceDescriptor[] = {
18, // bLength
0x01, // bDescriptorType - Device descriptor
bcdUSB_L, // bcdUSB_L - 1.10
bcdUSB_H, // bcdUSB_H
bDeviceClass, // bDeviceClass - USB_COMM
bDeviceSubClass, // bDeviceSubClass
bDeviceProtocol, // bDeviceProtocol
USB_EP0_BUFSZ, // bMaxPacketSize
0x7b, // idVendor_L PL2303: VID=0x067b, PID=0x2303
0x06, // idVendor_H
0x03, // idProduct_L
0x23, // idProduct_H
0x00, // bcdDevice_Ver_L
0x03, // bcdDevice_Ver_H
0x01, // iManufacturer
0x02, // iProduct
0x00, // iSerialNumber
bNumConfigurations // bNumConfigurations
};
static const uint8_t USB_DeviceQualifierDescriptor[] = {
10, //bLength
0x06, // bDescriptorType - Device qualifier
bcdUSB_L, // bcdUSB_L
bcdUSB_H, // bcdUSB_H
bDeviceClass, // bDeviceClass
bDeviceSubClass, // bDeviceSubClass
bDeviceProtocol, // bDeviceProtocol
USB_EP0_BUFSZ, // bMaxPacketSize0
bNumConfigurations, // bNumConfigurations
0x00 // Reserved
};
static const uint8_t USB_ConfigDescriptor[] = {
/*Configuration Descriptor*/
0x09, /* bLength: Configuration Descriptor size */
0x02, /* bDescriptorType: Configuration */
39, /* wTotalLength:no of returned bytes */
0x00,
0x01, /* bNumInterfaces: 1 interface */
0x01, /* bConfigurationValue: Configuration value */
0x00, /* iConfiguration: Index of string descriptor describing the configuration */
0xa0, /* bmAttributes - Bus powered, Remote wakeup */
0x32, /* MaxPower 100 mA */
/*---------------------------------------------------------------------------*/
/*Interface Descriptor */
0x09, /* bLength: Interface Descriptor size */
0x04, /* bDescriptorType: Interface */
0x00, /* bInterfaceNumber: Number of Interface */
0x00, /* bAlternateSetting: Alternate setting */
0x03, /* bNumEndpoints: 3 endpoints used */
0xff, /* bInterfaceClass */
0x00, /* bInterfaceSubClass */
0x00, /* bInterfaceProtocol */
0x00, /* iInterface: */
///////////////////////////////////////////////////
/*Endpoint 1 Descriptor*/
0x07, /* bLength: Endpoint Descriptor size */
0x05, /* bDescriptorType: Endpoint */
0x81, /* bEndpointAddress IN1 */
0x03, /* bmAttributes: Interrupt */
0x0a, /* wMaxPacketSize LO: */
0x00, /* wMaxPacketSize HI: */
0x01, /* bInterval: */
/*Endpoint OUT2 Descriptor*/
0x07, /* bLength: Endpoint Descriptor size */
0x05, /* bDescriptorType: Endpoint */
0x02, /* bEndpointAddress: OUT2 */
0x02, /* bmAttributes: Bulk */
(USB_RXBUFSZ & 0xff), /* wMaxPacketSize: 64 */
(USB_RXBUFSZ >> 8),
0x00, /* bInterval: ignore for Bulk transfer */
/*Endpoint IN3 Descriptor*/
0x07, /* bLength: Endpoint Descriptor size */
0x05, /* bDescriptorType: Endpoint */
0x83, /* bEndpointAddress IN3 */
0x02, /* bmAttributes: Bulk */
(USB_TXBUFSZ & 0xff), /* wMaxPacketSize: 64 */
(USB_TXBUFSZ >> 8),
0x00, /* bInterval: ignore for Bulk transfer */
};
_USB_LANG_ID_(USB_StringLangDescriptor, LANG_US);
// these descriptors are not used in PL2303 emulator!
_USB_STRING_(USB_StringSerialDescriptor, u"0");
_USB_STRING_(USB_StringManufacturingDescriptor, u"Prolific Technology Inc.");
_USB_STRING_(USB_StringProdDescriptor, u"USB-Serial Controller");
/*
* default handlers
*/
// SET_LINE_CODING
void WEAK linecoding_handler(usb_LineCoding __attribute__((unused)) *lc){
}
// SET_CONTROL_LINE_STATE
void WEAK clstate_handler(uint16_t __attribute__((unused)) val){
}
// SEND_BREAK
void WEAK break_handler(){
}
// handler of vendor requests
void WEAK vendor_handler(config_pack_t *packet){
if(packet->bmRequestType & 0x80){ // read
uint8_t c;
switch(packet->wValue){
case 0x8484:
c = 2;
break;
case 0x0080:
c = 1;
break;
case 0x8686:
c = 0xaa;
break;
default:
c = 0;
}
EP_WriteIRQ(0, &c, 1);
}else{ // write ZLP
EP_WriteIRQ(0, (uint8_t *)0, 0);
}
}
static void wr0(const uint8_t *buf, uint16_t size){
if(setup_packet.wLength < size) size = setup_packet.wLength; // shortened request
if(size < endpoints[0].txbufsz){
EP_WriteIRQ(0, buf, size);
return;
}
while(size){
uint16_t l = size;
if(l > endpoints[0].txbufsz) l = endpoints[0].txbufsz;
EP_WriteIRQ(0, buf, l);
buf += l;
size -= l;
uint8_t needzlp = (l == endpoints[0].txbufsz) ? 1 : 0;
if(size || needzlp){ // send last data buffer
uint16_t status = KEEP_DTOG(USB->EPnR[0]);
// keep DTOGs, clear CTR_RX,TX, set TX VALID, leave stat_Rx
USB->EPnR[0] = (status & ~(USB_EPnR_CTR_RX|USB_EPnR_CTR_TX|USB_EPnR_STAT_RX))
^ USB_EPnR_STAT_TX;
uint32_t ctr = 1000000;
while(--ctr && (USB->ISTR & USB_ISTR_CTR) == 0){IWDG->KR = IWDG_REFRESH;};
if((USB->ISTR & USB_ISTR_CTR) == 0){
return;
}
if(needzlp) EP_WriteIRQ(0, (uint8_t*)0, 0);
}
}
}
static inline void get_descriptor(){
switch(setup_packet.wValue){
case DEVICE_DESCRIPTOR:
wr0(USB_DeviceDescriptor, sizeof(USB_DeviceDescriptor));
break;
case CONFIGURATION_DESCRIPTOR:
wr0(USB_ConfigDescriptor, sizeof(USB_ConfigDescriptor));
break;
case STRING_LANG_DESCRIPTOR:
wr0((const uint8_t *)&USB_StringLangDescriptor, STRING_LANG_DESCRIPTOR_SIZE_BYTE);
break;
case STRING_MAN_DESCRIPTOR:
wr0((const uint8_t *)&USB_StringManufacturingDescriptor, USB_StringManufacturingDescriptor.bLength);
break;
case STRING_PROD_DESCRIPTOR:
wr0((const uint8_t *)&USB_StringProdDescriptor, USB_StringProdDescriptor.bLength);
break;
case STRING_SN_DESCRIPTOR:
wr0((const uint8_t *)&USB_StringSerialDescriptor, USB_StringSerialDescriptor.bLength);
break;
case DEVICE_QUALIFIER_DESCRIPTOR:
wr0(USB_DeviceQualifierDescriptor, USB_DeviceQualifierDescriptor[0]);
break;
default:
break;
}
}
static uint8_t configuration = 0; // reply for GET_CONFIGURATION (==1 if configured)
static inline void std_d2h_req(){
uint16_t status = 0; // bus powered
switch(setup_packet.bRequest){
case GET_DESCRIPTOR:
get_descriptor();
break;
case GET_STATUS:
EP_WriteIRQ(0, (uint8_t *)&status, 2); // send status: Bus Powered
break;
case GET_CONFIGURATION:
EP_WriteIRQ(0, &configuration, 1);
break;
default:
break;
}
}
static inline void std_h2d_req(){
switch(setup_packet.bRequest){
case SET_ADDRESS:
// new address will be assigned later - after acknowlegement or request to host
USB_Dev.USB_Addr = setup_packet.wValue;
break;
case SET_CONFIGURATION:
// Now device configured
USB_Dev.USB_Status = USB_STATE_CONFIGURED;
configuration = setup_packet.wValue;
break;
default:
break;
}
}
/*
bmRequestType: 76543210
7 direction: 0 - host->device, 1 - device->host
65 type: 0 - standard, 1 - class, 2 - vendor
4..0 getter: 0 - device, 1 - interface, 2 - endpoint, 3 - other
*/
/**
* Endpoint0 (control) handler
*/
static void EP0_Handler(){
uint16_t epstatus = USB->EPnR[0]; // EP0R on input -> return this value after modifications
uint8_t reqtype = setup_packet.bmRequestType & 0x7f;
uint8_t dev2host = (setup_packet.bmRequestType & 0x80) ? 1 : 0;
int rxflag = RX_FLAG(epstatus);
if(rxflag && SETUP_FLAG(epstatus)){
switch(reqtype){
case STANDARD_DEVICE_REQUEST_TYPE: // standard device request
if(dev2host){
std_d2h_req();
}else{
std_h2d_req();
EP_WriteIRQ(0, (uint8_t *)0, 0);
}
break;
case STANDARD_ENDPOINT_REQUEST_TYPE: // standard endpoint request
if(setup_packet.bRequest == CLEAR_FEATURE){
EP_WriteIRQ(0, (uint8_t *)0, 0);
}
break;
case VENDOR_REQUEST_TYPE:
vendor_handler(&setup_packet);
break;
case CONTROL_REQUEST_TYPE:
switch(setup_packet.bRequest){
case GET_LINE_CODING:
EP_WriteIRQ(0, (uint8_t*)&lineCoding, sizeof(lineCoding));
break;
case SET_LINE_CODING: // omit this for next stage, when data will come
break;
case SET_CONTROL_LINE_STATE:
usbON = 1;
clstate_handler(setup_packet.wValue);
break;
case SEND_BREAK:
usbON = 0;
break_handler();
break;
default:
break;
}
if(setup_packet.bRequest != GET_LINE_CODING) EP_WriteIRQ(0, (uint8_t *)0, 0); // write acknowledgement
break;
default:
EP_WriteIRQ(0, (uint8_t *)0, 0);
}
}else if(rxflag){ // got data over EP0 or host acknowlegement
if(endpoints[0].rx_cnt){
if(setup_packet.bRequest == SET_LINE_CODING){
linecoding_handler((usb_LineCoding*)ep0databuf);
}
}
} else if(TX_FLAG(epstatus)){ // package transmitted
// now we can change address after enumeration
if ((USB->DADDR & USB_DADDR_ADD) != USB_Dev.USB_Addr){
USB->DADDR = USB_DADDR_EF | USB_Dev.USB_Addr;
// change state to ADRESSED
USB_Dev.USB_Status = USB_STATE_ADDRESSED;
}
}
epstatus = KEEP_DTOG(USB->EPnR[0]);
if(rxflag) epstatus ^= USB_EPnR_STAT_TX; // start ZLP/data transmission
else epstatus &= ~USB_EPnR_STAT_TX; // or leave unchanged
// keep DTOGs, clear CTR_RX,TX, set RX VALID
USB->EPnR[0] = (epstatus & ~(USB_EPnR_CTR_RX|USB_EPnR_CTR_TX)) ^ USB_EPnR_STAT_RX;
}
static uint16_t lastaddr = LASTADDR_DEFAULT;
/**
* Endpoint initialisation
* @param number - EP num (0...7)
* @param type - EP type (EP_TYPE_BULK, EP_TYPE_CONTROL, EP_TYPE_ISO, EP_TYPE_INTERRUPT)
* @param txsz - transmission buffer size @ USB/CAN buffer
* @param rxsz - reception buffer size @ USB/CAN buffer
* @param uint16_t (*func)(ep_t *ep) - EP handler function
* @return 0 if all OK
*/
int EP_Init(uint8_t number, uint8_t type, uint16_t txsz, uint16_t rxsz, void (*func)(ep_t ep)){
if(number >= STM32ENDPOINTS) return 4; // out of configured amount
if(txsz > USB_BTABLE_SIZE || rxsz > USB_BTABLE_SIZE) return 1; // buffer too large
if(lastaddr + txsz + rxsz >= USB_BTABLE_SIZE) return 2; // out of btable
USB->EPnR[number] = (type << 9) | (number & USB_EPnR_EA);
USB->EPnR[number] ^= USB_EPnR_STAT_RX | USB_EPnR_STAT_TX_1;
if(rxsz & 1 || rxsz > 512) return 3; // wrong rx buffer size
uint16_t countrx = 0;
if(rxsz < 64) countrx = rxsz / 2;
else{
if(rxsz & 0x1f) return 3; // should be multiple of 32
countrx = 31 + rxsz / 32;
}
USB_BTABLE->EP[number].USB_ADDR_TX = lastaddr;
endpoints[number].tx_buf = (uint16_t *)(USB_BTABLE_BASE + lastaddr*2);
endpoints[number].txbufsz = txsz;
lastaddr += txsz;
USB_BTABLE->EP[number].USB_COUNT_TX = 0;
USB_BTABLE->EP[number].USB_ADDR_RX = lastaddr;
endpoints[number].rx_buf = (uint16_t *)(USB_BTABLE_BASE + lastaddr*2);
lastaddr += rxsz;
USB_BTABLE->EP[number].USB_COUNT_RX = countrx << 10;
endpoints[number].func = func;
return 0;
}
// standard IRQ handler
void usb_lp_can_rx0_isr(){
if(USB->ISTR & USB_ISTR_RESET){
usbON = 0;
// Reinit registers
USB->CNTR = USB_CNTR_RESETM | USB_CNTR_CTRM | USB_CNTR_SUSPM | USB_CNTR_WKUPM;
USB->ISTR = 0;
// Endpoint 0 - CONTROL
// ON USB LS size of EP0 may be 8 bytes, but on FS it should be 64 bytes!
lastaddr = LASTADDR_DEFAULT;
// clear address, leave only enable bit
USB->DADDR = USB_DADDR_EF;
USB_Dev.USB_Status = USB_STATE_DEFAULT;
USB->ISTR = ~USB_ISTR_RESET;
if(EP_Init(0, EP_TYPE_CONTROL, USB_EP0_BUFSZ, USB_EP0_BUFSZ, EP0_Handler)){
return;
}
}
if(USB->ISTR & USB_ISTR_CTR){
// EP number
uint8_t n = USB->ISTR & USB_ISTR_EPID;
// copy status register
uint16_t epstatus = USB->EPnR[n];
// copy received bytes amount
endpoints[n].rx_cnt = USB_BTABLE->EP[n].USB_COUNT_RX & 0x3FF; // low 10 bits is counter
// check direction
if(USB->ISTR & USB_ISTR_DIR){ // OUT interrupt - receive data, CTR_RX==1 (if CTR_TX == 1 - two pending transactions: receive following by transmit)
if(n == 0){ // control endpoint
if(epstatus & USB_EPnR_SETUP){ // setup packet -> copy data to conf_pack
EP_Read(0, (uint16_t*)&setup_packet);
ep0dbuflen = 0;
// interrupt handler will be called later
}else if(epstatus & USB_EPnR_CTR_RX){ // data packet -> push received data to ep0databuf
ep0dbuflen = endpoints[0].rx_cnt;
EP_Read(0, (uint16_t*)&ep0databuf);
}
}
}
// call EP handler
if(endpoints[n].func) endpoints[n].func(endpoints[n]);
}
if(USB->ISTR & USB_ISTR_SUSP){ // suspend -> still no connection, may sleep
usbON = 0;
USB->CNTR |= USB_CNTR_FSUSP | USB_CNTR_LP_MODE;
USB->ISTR = ~USB_ISTR_SUSP;
}
if(USB->ISTR & USB_ISTR_WKUP){ // wakeup
USB->CNTR &= ~(USB_CNTR_FSUSP | USB_CNTR_LP_MODE); // clear suspend flags
USB->ISTR = ~USB_ISTR_WKUP;
}
}
/**
* Write data to EP buffer (called from IRQ handler)
* @param number - EP number
* @param *buf - array with data
* @param size - its size
*/
void EP_WriteIRQ(uint8_t number, const uint8_t *buf, uint16_t size){
uint8_t i;
if(size > endpoints[number].txbufsz) size = endpoints[number].txbufsz;
uint16_t N2 = (size + 1) >> 1;
// the buffer is 16-bit, so we should copy data as it would be uint16_t
uint16_t *buf16 = (uint16_t *)buf;
uint32_t *out = (uint32_t *)endpoints[number].tx_buf;
for(i = 0; i < N2; ++i, ++out){
*out = buf16[i];
}
USB_BTABLE->EP[number].USB_COUNT_TX = size;
}
/**
* Write data to EP buffer (called outside IRQ handler)
* @param number - EP number
* @param *buf - array with data
* @param size - its size
*/
void EP_Write(uint8_t number, const uint8_t *buf, uint16_t size){
EP_WriteIRQ(number, buf, size);
uint16_t status = KEEP_DTOG(USB->EPnR[number]);
// keep DTOGs, clear CTR_TX & set TX VALID to start transmission
USB->EPnR[number] = (status & ~(USB_EPnR_CTR_TX)) ^ USB_EPnR_STAT_TX;
}
/*
* Copy data from EP buffer into user buffer area
* @param *buf - user array for data
* @return amount of data read
*/
int EP_Read(uint8_t number, uint16_t *buf){
int sz = endpoints[number].rx_cnt;
if(!sz) return 0;
endpoints[number].rx_cnt = 0;
int n = (sz + 1) >> 1;
uint32_t *in = (uint32_t *)endpoints[number].rx_buf;
if(n){
for(int i = 0; i < n; ++i, ++in)
buf[i] = *(uint16_t*)in;
}
return sz;
}

View File

@@ -0,0 +1,184 @@
/*
* This file is part of the MLX90640 project.
* Copyright 2020 Edward V. Emelianov <edward.emelianoff@gmail.com>.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#ifndef __USB_LIB_H__
#define __USB_LIB_H__
#include <wchar.h>
#include "usb_defs.h"
#define EP0DATABUF_SIZE (64)
#define LASTADDR_DEFAULT (STM32ENDPOINTS * 8)
// bmRequestType & 0x7f
#define STANDARD_DEVICE_REQUEST_TYPE 0
#define STANDARD_ENDPOINT_REQUEST_TYPE 2
#define VENDOR_REQUEST_TYPE 0x40
#define CONTROL_REQUEST_TYPE 0x21
// bRequest, standard; for bmRequestType == 0x80
#define GET_STATUS 0x00
#define GET_DESCRIPTOR 0x06
#define GET_CONFIGURATION 0x08
// for bmRequestType == 0
#define CLEAR_FEATURE 0x01
#define SET_FEATURE 0x03 // unused
#define SET_ADDRESS 0x05
#define SET_DESCRIPTOR 0x07 // unused
#define SET_CONFIGURATION 0x09
// for bmRequestType == 0x81, 1 or 0xB2
#define GET_INTERFACE 0x0A // unused
#define SET_INTERFACE 0x0B // unused
#define SYNC_FRAME 0x0C // unused
#define VENDOR_REQUEST 0x01 // unused
// Class-Specific Control Requests
#define SEND_ENCAPSULATED_COMMAND 0x00 // unused
#define GET_ENCAPSULATED_RESPONSE 0x01 // unused
#define SET_COMM_FEATURE 0x02 // unused
#define GET_COMM_FEATURE 0x03 // unused
#define CLEAR_COMM_FEATURE 0x04 // unused
#define SET_LINE_CODING 0x20
#define GET_LINE_CODING 0x21
#define SET_CONTROL_LINE_STATE 0x22
#define SEND_BREAK 0x23
// control line states
#define CONTROL_DTR 0x01
#define CONTROL_RTS 0x02
// wValue
#define DEVICE_DESCRIPTOR 0x100
#define CONFIGURATION_DESCRIPTOR 0x200
#define STRING_LANG_DESCRIPTOR 0x300
#define STRING_MAN_DESCRIPTOR 0x301
#define STRING_PROD_DESCRIPTOR 0x302
#define STRING_SN_DESCRIPTOR 0x303
#define DEVICE_QUALIFIER_DESCRIPTOR 0x600
#define RX_FLAG(epstat) (epstat & USB_EPnR_CTR_RX)
#define TX_FLAG(epstat) (epstat & USB_EPnR_CTR_TX)
#define SETUP_FLAG(epstat) (epstat & USB_EPnR_SETUP)
// EPnR bits manipulation
#define KEEP_DTOG_STAT(EPnR) (EPnR & ~(USB_EPnR_STAT_RX|USB_EPnR_STAT_TX|USB_EPnR_DTOG_RX|USB_EPnR_DTOG_TX))
#define KEEP_DTOG(EPnR) (EPnR & ~(USB_EPnR_DTOG_RX|USB_EPnR_DTOG_TX))
// USB state: uninitialized, addressed, ready for use
typedef enum{
USB_STATE_DEFAULT,
USB_STATE_ADDRESSED,
USB_STATE_CONFIGURED,
USB_STATE_CONNECTED
} USB_state;
// EP types
#define EP_TYPE_BULK 0x00
#define EP_TYPE_CONTROL 0x01
#define EP_TYPE_ISO 0x02
#define EP_TYPE_INTERRUPT 0x03
#define LANG_US (uint16_t)0x0409
#define _USB_STRING_(name, str) \
static const struct name \
{ \
uint8_t bLength; \
uint8_t bDescriptorType; \
uint16_t bString[(sizeof(str) - 2) / 2]; \
\
} \
name = {sizeof(name), 0x03, str}
#define _USB_LANG_ID_(name, lng_id) \
\
static const struct name \
{ \
uint8_t bLength; \
uint8_t bDescriptorType; \
uint16_t bString; \
\
} \
name = {0x04, 0x03, lng_id}
#define STRING_LANG_DESCRIPTOR_SIZE_BYTE (4)
// EP0 configuration packet
typedef struct {
uint8_t bmRequestType;
uint8_t bRequest;
uint16_t wValue;
uint16_t wIndex;
uint16_t wLength;
} config_pack_t;
// endpoints state
typedef struct{
uint16_t *tx_buf; // transmission buffer address
uint16_t txbufsz; // transmission buffer size
uint16_t *rx_buf; // reception buffer address
void (*func)(); // endpoint action function
unsigned rx_cnt : 10; // received data counter
} ep_t;
// USB status & its address
typedef struct {
uint8_t USB_Status;
uint16_t USB_Addr;
}usb_dev_t;
typedef struct {
uint32_t dwDTERate;
uint8_t bCharFormat;
#define USB_CDC_1_STOP_BITS 0
#define USB_CDC_1_5_STOP_BITS 1
#define USB_CDC_2_STOP_BITS 2
uint8_t bParityType;
#define USB_CDC_NO_PARITY 0
#define USB_CDC_ODD_PARITY 1
#define USB_CDC_EVEN_PARITY 2
#define USB_CDC_MARK_PARITY 3
#define USB_CDC_SPACE_PARITY 4
uint8_t bDataBits;
} __attribute__ ((packed)) usb_LineCoding;
typedef struct {
uint8_t bmRequestType;
uint8_t bNotificationType;
uint16_t wValue;
uint16_t wIndex;
uint16_t wLength;
} __attribute__ ((packed)) usb_cdc_notification;
extern ep_t endpoints[];
extern usb_dev_t USB_Dev;
extern uint8_t usbON;
void USB_Init();
void USB_ResetState();
int EP_Init(uint8_t number, uint8_t type, uint16_t txsz, uint16_t rxsz, void (*func)());
void EP_WriteIRQ(uint8_t number, const uint8_t *buf, uint16_t size);
void EP_Write(uint8_t number, const uint8_t *buf, uint16_t size);
int EP_Read(uint8_t number, uint16_t *buf);
usb_LineCoding getLineCoding();
void linecoding_handler(usb_LineCoding *lc);
void clstate_handler(uint16_t val);
void break_handler();
void vendor_handler(config_pack_t *packet);
#endif // __USB_LIB_H__

View File

@@ -0,0 +1,2 @@
#define BUILD_NUMBER "197"
#define BUILD_DATE "2022-05-20"