repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
kiding/DSCapture.framework
|
ScreenCaptureTest/ScreenCaptureTest/AppDelegate.h
|
#import <Cocoa/Cocoa.h>
#import <DSCapture/DSCapture.h>
@interface AppDelegate : NSObject <NSApplicationDelegate>
@property (assign) IBOutlet NSWindow *window;
@property (assign) IBOutlet NSImageView *imageView;
@property (assign) IBOutlet NSButton *cgCheckBox;
- (IBAction)captureFullAction:(id)sender;
- (IBAction)captureSelectionAction:(id)sender;
- (void)displayCaptureData: (NSData *) sender;
@end
|
huangxianhui001/GradientView
|
GradientViewDemo/GradientViewDemo/ViewController.h
|
//
// ViewController.h
// GradientViewDemo
//
// Created by Alan on 2018/10/26.
// Copyright © 2018 Alan. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
|
huangxianhui001/GradientView
|
GradientView/MJAGradientView.h
|
<gh_stars>0
//
// MJAGradientView.h
// nvwang
//
// Created by Alan on 2018/8/8.
// Copyright © 2018年 mengjitv. All rights reserved.
//
#import <UIKit/UIKit.h>
/**
默认渐变颜色类型
- MJAGradientTypePurple: 紫色到粉红色过渡
- MJAGradientTypeYellow: 浅橘色到橘色过渡
*/
typedef NS_ENUM(NSUInteger, MJAGradientType) {
MJAGradientTypePurple,
MJAGradientTypeYellow,
};
/**
渐变方向
- MJAGradientDirectLeftToRight: 从左到右
- MJAGradientDirectRightToLeft: 从右到左
- MJAGradientDirectTopToBottom: 从上到下
- MJAGradientDirectBottomToTop: 从下到上
*/
typedef NS_ENUM(NSUInteger, MJAGradientDirect) {
MJAGradientDirectLeftToRight,
MJAGradientDirectRightToLeft,
MJAGradientDirectTopToBottom,
MJAGradientDirectBottomToTop,
};
/**
针对 CAGradientLayer的简易封装的 view, 目前只支持水平和垂直方向的渐变,
*/
@interface MJAGradientView : UIView
/**
渐变颜色方向,默认 MJAGradientDirectLeftToRight
*/
@property (nonatomic, assign) MJAGradientDirect direction;
/**
圆角,默认 0
*/
@property (nonatomic, assign) CGFloat cornerRadius;
/**
颜色偏移,0~1之间,在渐变方向上,从0到 coloroffset 个单位宽度的地方将会填充颜色数组中第一个的颜色,默认 0
*/
@property (nonatomic, assign) CGFloat colorOffset;
/**
根据内置类型返回渐变 view 对象
@param type 内置类型
@return 渐变 view 对象
*/
+ (instancetype) gradientViewWithType:(MJAGradientType)type;
/**
根据内置类型和渐变方向,返回渐变 view 对象
@param type 内置类型
@param direction 渐变方向
@return 渐变 view 对象
*/
+ (instancetype) gradientViewWithType:(MJAGradientType)type direction:(MJAGradientDirect)direction;
/**
根据提供的颜色数组生成渐变 view, 默认方向是MJAGradientDirectLeftToRight
@param colors 颜色数组
@return 渐变 view 对象
*/
+ (instancetype) gradientViewWithColors:(NSArray<UIColor *>*)colors;
/**
根据提供的颜色数组生成渐变 view, 并设置渐变方向
@param colors 颜色数组
@param direction 渐变方向
@return 渐变 view 对象
*/
+ (instancetype) gradientViewWithColors:(NSArray<UIColor *>*)colors direction:(MJAGradientDirect)direction;
/**
根据给定字符串,字体,字体颜色添加标题,只能居中显示
@param title 标题
@param font 标题字体
@param color 字体颜色
*/
- (void) addTitle:(NSString *)title font:(UIFont *)font color:(UIColor *)color;
/**
添加图片,注意:图片不能与标题共存
@param image 需要添加的图片,显示大小为图片尺寸
*/
- (void) addImage:(UIImage *)image;
/**
添加图片,注意:图片不能与标题共存
@param image 需要添加的图片
@param size 图片显示的大小
*/
- (void) addImage:(UIImage *)image size:(CGSize)size;
@end
|
binhdinh296/IdentifySub
|
Example/Pods/Target Support Files/IdentifySub/IdentifySub-umbrella.h
|
<gh_stars>0
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
#import "MySDKCrypto.h"
FOUNDATION_EXPORT double IdentifySubVersionNumber;
FOUNDATION_EXPORT const unsigned char IdentifySubVersionString[];
|
lindianfeng/kaika_clock_firmware_new
|
User/Inc/at24cxx.h
|
<filename>User/Inc/at24cxx.h
/*
* at24cxx.h
*
* Created on: 2021年1月19日
* Author: linhao
*/
#ifndef INC_AT24CXX_H_
#define INC_AT24CXX_H_
#include <stdint.h>
#define AT24CXX_DEV_ADDRESS 0xA0
#define AT24CXX_DELAY_MS osDelay
void AT24CXX_Write(uint16_t reg_address, uint8_t data);
uint8_t AT24CXX_Read(uint16_t);
#endif /* INC_AT24CXX_H_ */
|
lindianfeng/kaika_clock_firmware_new
|
User/Inc/sht30.h
|
<reponame>lindianfeng/kaika_clock_firmware_new
/*
* sht30.h
*
* Created on: 2021年2月1日
* Author: linhao
*/
#ifndef INC_SHT30_H_
#define INC_SHT30_H_
#include <stdbool.h>
#include <stdint.h>
#define SHT_ADDR (0x44<<1)
uint8_t sht30_init();
uint8_t sht30_sample(float *t, float *h);
#endif /* INC_SHT30_H_ */
|
lindianfeng/kaika_clock_firmware_new
|
User/Src/max72xx.c
|
<reponame>lindianfeng/kaika_clock_firmware_new<gh_stars>0
/*
* max7219.c
*
* Created on: 2020年12月14日
* Author: lindi
*/
#include "max72xx.h"
#include <stdlib.h>
#include <string.h>
#include "main.h"
#include "utils.h"
#define CS_SET() HAL_GPIO_WritePin(MAX7219_CS_GPIO_Port, MAX7219_CS_Pin, GPIO_PIN_RESET)
#define CS_RESET() HAL_GPIO_WritePin(MAX7219_CS_GPIO_Port, MAX7219_CS_Pin, GPIO_PIN_SET)
extern SPI_HandleTypeDef hspi1;
typedef enum
{
REG_DECODE_MODE = 0x09,
REG_INTENSITY = 0x0A,
REG_SCAN_LIMIT = 0x0B,
REG_SHUTDOWN = 0x0C,
REG_DISPLAY_TEST = 0x0F,
} MAX72XX_REGISTERS;
typedef struct
{
uint8_t dig[ROW_SIZE]; // data for each digit of the MAX72xx (DIG0-DIG7)
uint8_t changed; // one bit for each digit changed ('dirty bit')
} deviceInfo_t;
// Control data for the library
static bool _updateEnabled = false; // update the display when this is true, suspend otherwise
static bool _wrapAround = true; // when shifting, wrap left to right and vice versa (circular buffer)
static deviceInfo_t *_matrix = NULL; // the current status of the LED matrix (buffers)
static uint8_t *_spiData = NULL; // data buffer for writing to SPI interface
static uint8_t _intensity = 1;
void MAX72XX_Init(void)
{
_matrix = (deviceInfo_t*) malloc(sizeof(deviceInfo_t) * MAX_DEVICES);
_spiData = (uint8_t*) malloc(SPI_DATA_SIZE);
MAX72XX_ControlAll(TEST, OFF); // no test
MAX72XX_ControlAll(SCANLIMIT, ROW_SIZE - 1); // scan limit is set to max on startup
MAX72XX_ControlAll(INTENSITY, _intensity); // set intensity to a reasonable value
MAX72XX_ControlAll(DECODE, OFF); // ensure no decoding (warm boot potential issue)
MAX72XX_ClearAll();
MAX72XX_ControlAll(SHUTDOWN, OFF); // take the modules out of shutdown mode
}
void MAX72XX_DeInit(void)
{
free(_matrix);
free(_spiData);
}
void MAX72XX_SetIntensity(uint8_t intensity)
{
_intensity = intensity;
MAX72XX_ControlAll(INTENSITY, _intensity);
}
uint8_t MAX72XX_GetIntensity(void)
{
return _intensity;
}
uint8_t MAX72XX_GetDeviceCount(void)
{
return (MAX_DEVICES);
}
uint8_t MAX72XX_GetColumnCount(void)
{
return (MAX_DEVICES * COL_SIZE);
}
static void MAX72XX_SpiSend()
{
CS_SET();
HAL_SPI_Transmit(&hspi1, _spiData, SPI_DATA_SIZE, HAL_MAX_DELAY);
CS_RESET();
}
static void MAX72XX_SpiClearBuffer(void)
{
memset(_spiData, 0, SPI_DATA_SIZE);
}
static void MAX72XX_FlushBufferOne(uint8_t buf)
// Use this function when the changes are limited to one device only.
// Address passed is a buffer address
{
if (buf > LAST_BUFFER)
return;
for (uint8_t i = 0; i < ROW_SIZE; i++)
{
if (bitRead(_matrix[buf].changed, i))
{
MAX72XX_SpiClearBuffer();
// put our device data into the buffer
_spiData[SPI_OFFSET(buf, 0)] = OP_DIGIT0 + i;
_spiData[SPI_OFFSET(buf, 1)] = _matrix[buf].dig[i];
MAX72XX_SpiSend();
}
}
_matrix[buf].changed = ALL_CLEAR;
}
static void MAX72XX_FlushBufferAll()
// Only one data byte is sent to a device, so if there are many changes, it is more
// efficient to send a data byte all devices at the same time, substantially cutting
// the number of communication messages required.
{
for (uint8_t i = 0; i < ROW_SIZE; i++) // all data rows
{
bool bChange = false; // set to true if we detected a change
MAX72XX_SpiClearBuffer();
for (uint8_t dev = FIRST_BUFFER; dev <= LAST_BUFFER; dev++) // all devices
{
if (bitRead(_matrix[dev].changed, i))
{
// put our device data into the buffer
_spiData[SPI_OFFSET(dev, 0)] = OP_DIGIT0 + i;
_spiData[SPI_OFFSET(dev, 1)] = _matrix[dev].dig[i];
bChange = true;
}
}
if (bChange)
MAX72XX_SpiSend();
}
// mark everything as cleared
for (uint8_t dev = FIRST_BUFFER; dev <= LAST_BUFFER; dev++)
_matrix[dev].changed = ALL_CLEAR;
}
static void MAX72XX_ControlHardware(uint8_t dev, controlRequest_t mode, int value)
{
// control command is for the devices, translate internal request to device bytes
// into the transmission buffer
uint8_t opcode = OP_NOOP;
uint8_t param = 0;
// work out data to write
switch (mode)
{
case SHUTDOWN:
opcode = OP_SHUTDOWN;
param = (value == OFF ? 1 : 0);
break;
case SCANLIMIT:
opcode = OP_SCANLIMIT;
param = (value > MAX_SCANLIMIT ? MAX_SCANLIMIT : value);
break;
case INTENSITY:
opcode = OP_INTENSITY;
param = (value > MAX_INTENSITY ? MAX_INTENSITY : value);
break;
case DECODE:
opcode = OP_DECODEMODE;
param = (value == OFF ? 0 : 0xff);
break;
case TEST:
opcode = OP_DISPLAYTEST;
param = (value == OFF ? 0 : 1);
break;
default:
return;
}
// put our device data into the buffer
_spiData[SPI_OFFSET(dev, 0)] = opcode;
_spiData[SPI_OFFSET(dev, 1)] = param;
}
static void MAX7219ControlLibrary(controlRequest_t mode, int value)
{
// control command was internal, set required parameters
switch (mode)
{
case UPDATE:
_updateEnabled = (value == ON);
if (_updateEnabled)
MAX72XX_FlushBufferAll();
break;
case WRAPAROUND:
_wrapAround = (value == ON);
break;
default:
break;
}
}
bool MAX72XX_ControlOne(uint8_t buf, controlRequest_t mode, int value)
{
// dev is zero based and needs adjustment if used
if (buf > LAST_BUFFER)
{
return (false);
}
if (mode < UPDATE)
{
// device based control
MAX72XX_SpiClearBuffer();
MAX72XX_ControlHardware(buf, mode, value);
MAX72XX_SpiSend();
} else
{
// internal control function, doesn't relate to specific device
MAX7219ControlLibrary(mode, value);
}
return (true);
}
bool MAX72XX_ControlBy(uint8_t startDev, uint8_t endDev, controlRequest_t mode, int value)
{
if (endDev < startDev)
{
return (false);
}
if (mode < UPDATE)
{
// device based control
MAX72XX_SpiClearBuffer();
for (uint8_t i = startDev; i <= endDev; i++)
{
MAX72XX_ControlHardware(i, mode, value);
}
MAX72XX_SpiSend();
} else
{
// internal control function, doesn't relate to specific device
MAX7219ControlLibrary(mode, value);
}
return (true);
}
void MAX72XX_ControlAll(controlRequest_t mode, int value)
{
MAX72XX_ControlBy(0, MAX72XX_GetDeviceCount() - 1, mode, value);
}
//for buff
bool MAX72XX_ClearOne(uint8_t buf)
{
if (buf > LAST_BUFFER)
return (false);
memset(_matrix[buf].dig, 0, sizeof(_matrix[buf].dig));
_matrix[buf].changed = ALL_CHANGED;
if (_updateEnabled)
MAX72XX_FlushBufferOne(buf);
return (true);
}
void MAX72XX_ClearBy(uint8_t startDev, uint8_t endDev)
{
if (endDev < startDev)
return;
for (uint8_t buf = startDev; buf <= endDev; buf++)
{
memset(_matrix[buf].dig, 0, sizeof(_matrix[buf].dig));
_matrix[buf].changed = ALL_CHANGED;
}
if (_updateEnabled)
MAX72XX_FlushBufferAll();
}
void MAX72XX_ClearAll(void)
{
MAX72XX_ClearBy(0, MAX72XX_GetDeviceCount() - 1);
}
uint8_t MAX72XX_BitReverse(uint8_t b)
// Reverse the order of bits within a byte.
// Returns the reversed byte value.
{
b = ((b & 0xf0) >> 4) | ((b & 0x0f) << 4);
b = ((b & 0xcc) >> 2) | ((b & 0x33) << 2);
b = ((b & 0xaa) >> 1) | ((b & 0x55) << 1);
return (b);
}
uint8_t MAX72XX_GetC(uint8_t buf, uint8_t c)
// c is in pixel coordinates and the return value must be in pixel coordinate order
{
uint8_t mask = 1 << HW_COL(c); // which column/row of bits is the column data
uint8_t value = 0; // assembles data to be returned to caller
if ((buf > LAST_BUFFER) || (c >= COL_SIZE))
return (0);
// for each digit data, pull out the column/row bit and place
// it in value. The loop creates the data in pixel coordinate order as it goes.
for (uint8_t i = 0; i < ROW_SIZE; i++)
{
if (_matrix[buf].dig[HW_ROW(i)] & mask)
bitSet(value, i);
}
return (value);
}
uint8_t MAX72XX_GetR(uint8_t buf, uint8_t r)
// r is in pixel coordinates for this buffer
// returned value is in pixel coordinates
{
if ((buf > LAST_BUFFER) || (r >= ROW_SIZE))
return (0);
uint8_t value = _hwRevCols ? MAX72XX_BitReverse(_matrix[buf].dig[HW_ROW(r)]) : _matrix[buf].dig[HW_ROW(r)];
return (value);
}
bool MAX72XX_CopyC(uint8_t buf, uint8_t cSrc, uint8_t cDest)
// Src and Dest are in pixel coordinates.
// if we are just copying rows there is no need to repackage any data
{
uint8_t maskSrc = 1 << HW_COL(cSrc); // which column/row of bits is the column data
if ((buf > LAST_BUFFER) || (cSrc >= COL_SIZE) || (cDest >= COL_SIZE))
return (false);
for (uint8_t i = 0; i < ROW_SIZE; i++)
{
if (_matrix[buf].dig[i] & maskSrc)
bitSet(_matrix[buf].dig[i], HW_COL(cDest));
else
bitClear(_matrix[buf].dig[i], HW_COL(cDest));
}
_matrix[buf].changed = ALL_CHANGED;
if (_updateEnabled)
MAX72XX_FlushBufferOne(buf);
return (true);
}
bool MAX72XX_CopyR(uint8_t buf, uint8_t rSrc, uint8_t rDest)
// Src and Dest are in pixel coordinates.
// if we are just copying digits there is no need to repackage any data
{
if ((buf > LAST_BUFFER) || (rSrc >= ROW_SIZE) || (rDest >= ROW_SIZE))
return (false);
_matrix[buf].dig[HW_ROW(rDest)] = _matrix[buf].dig[HW_ROW(rSrc)];
bitSet(_matrix[buf].changed, HW_ROW(rDest));
if (_updateEnabled)
MAX72XX_FlushBufferOne(buf);
return (true);
}
bool MAX72XX_CopyColumn(uint8_t buf, uint8_t cSrc, uint8_t cDest)
{
if (_hwDigRows)
return (MAX72XX_CopyC(buf, cSrc, cDest));
else
return (MAX72XX_CopyR(buf, cSrc, cDest));
}
bool MAX72XX_CopyRow(uint8_t buf, uint8_t rSrc, uint8_t rDest)
{
if (_hwDigRows)
return (MAX72XX_CopyR(buf, rSrc, rDest));
else
return (MAX72XX_CopyC(buf, rSrc, rDest));
}
uint8_t MAX72XX_GetDevColumn(uint8_t buf, uint8_t c)
{
if (_hwDigRows)
return (MAX72XX_GetC(buf, c));
else
return (MAX72XX_GetR(buf, c));
}
uint8_t MAX72XX_GetPixelColumn(uint8_t c)
{
return MAX72XX_GetDevColumn((c / COL_SIZE), c % COL_SIZE);
}
uint8_t MAX72XX_GetRow(uint8_t buf, uint8_t r)
{
if (_hwDigRows)
return (MAX72XX_GetR(buf, r));
else
return (MAX72XX_GetC(buf, r));
}
bool MAX72XX_SetC(uint8_t buf, uint8_t c, uint8_t value)
// c and value are in pixel coordinate order
{
if ((buf > LAST_BUFFER) || (c >= COL_SIZE))
return (false);
for (uint8_t i = 0; i < ROW_SIZE; i++)
{
if (value & (1 << i)) // mask off next column/row value passed in and set it in the dig buffer
bitSet(_matrix[buf].dig[HW_ROW(i)], HW_COL(c));
else
bitClear(_matrix[buf].dig[HW_ROW(i)], HW_COL(c));
}
_matrix[buf].changed = ALL_CHANGED;
if (_updateEnabled)
MAX72XX_FlushBufferOne(buf);
return (true);
}
bool MAX72XX_SetR(uint8_t buf, uint8_t r, uint8_t value)
// r and value are in pixel coordinates
{
if ((buf > LAST_BUFFER) || (r >= ROW_SIZE))
return (false);
_matrix[buf].dig[HW_ROW(r)] = _hwRevCols ? MAX72XX_BitReverse(value) : value;
bitSet(_matrix[buf].changed, HW_ROW(r));
if (_updateEnabled)
MAX72XX_FlushBufferOne(buf);
return (true);
}
bool MAX72XX_SetDevColumn(uint8_t buf, uint8_t c, uint8_t value)
{
if (_hwDigRows)
return (MAX72XX_SetC(buf, c, value));
else
return (MAX72XX_SetR(buf, c, value));
}
bool MAX72XX_SetPixelColumn(uint16_t c, uint8_t value)
{
return MAX72XX_SetDevColumn((c / COL_SIZE), c % COL_SIZE, value);
}
bool MAX72XX_SetRowOne(uint8_t buf, uint8_t r, uint8_t value)
{
if (_hwDigRows)
return (MAX72XX_SetR(buf, r, value));
else
return (MAX72XX_SetC(buf, r, value));
}
bool MAX72XX_TransformBuffer(uint8_t buf, transformType_t ttype)
{
uint8_t t[ROW_SIZE];
switch (ttype)
{
//--------------
case TSL: // Transform Shift Left one pixel element
if (_hwDigRows)
{
for (uint8_t i = 0; i < ROW_SIZE; i++)
{
if (_hwRevCols)
_matrix[buf].dig[i] >>= 1;
else
_matrix[buf].dig[i] <<= 1;
}
} else
{
for (uint8_t i = ROW_SIZE; i > 0; --i)
_matrix[buf].dig[i] = _matrix[buf].dig[i - 1];
}
break;
//--------------
case TSR: // Transform Shift Right one pixel element
if (_hwDigRows)
{
for (uint8_t i = 0; i < ROW_SIZE; i++)
{
if (_hwRevCols)
_matrix[buf].dig[i] <<= 1;
else
_matrix[buf].dig[i] >>= 1;
}
} else
{
for (uint8_t i = 0; i < ROW_SIZE - 1; i++)
_matrix[buf].dig[i] = _matrix[buf].dig[i + 1];
}
break;
//--------------
case TSU: // Transform Shift Up one pixel element
if (_wrapAround) // save the first row or a zero row
t[0] = MAX72XX_GetRow(buf, 0);
else
t[0] = 0;
if (_hwDigRows)
{
for (uint8_t i = 0; i < ROW_SIZE - 1; i++)
MAX72XX_CopyRow(buf, i + 1, i);
} else
{
for (int8_t i = ROW_SIZE - 1; i >= 0; i--)
_matrix[buf].dig[i] <<= 1;
}
MAX72XX_SetRowOne(buf, ROW_SIZE - 1, t[0]);
break;
//--------------
case TSD: // Transform Shift Down one pixel element
if (_wrapAround) // save the last row or a zero row
t[0] = MAX72XX_GetRow(buf, ROW_SIZE - 1);
else
t[0] = 0;
if (_hwDigRows)
{
for (uint8_t i = ROW_SIZE; i > 0; --i)
MAX72XX_CopyRow(buf, i - 1, i);
} else
{
for (uint8_t i = 0; i < ROW_SIZE; i++)
_matrix[buf].dig[i] >>= 1;
}
MAX72XX_SetRowOne(buf, 0, t[0]);
break;
//--------------
case TFLR: // Transform Flip Left to Right
if (_hwDigRows)
{
for (uint8_t i = 0; i < ROW_SIZE; i++)
_matrix[buf].dig[i] = MAX72XX_BitReverse(_matrix[buf].dig[i]);
} else // really a TFUD
{
for (uint8_t i = 0; i < ROW_SIZE / 2; i++)
{
uint8_t t = _matrix[buf].dig[i];
_matrix[buf].dig[i] = _matrix[buf].dig[ROW_SIZE - i - 1];
_matrix[buf].dig[ROW_SIZE - i - 1] = t;
}
}
break;
//--------------
case TFUD: // Transform Flip Up to Down
if (_hwDigRows)
{
for (uint8_t i = 0; i < ROW_SIZE / 2; i++)
{
uint8_t t = _matrix[buf].dig[i];
_matrix[buf].dig[i] = _matrix[buf].dig[ROW_SIZE - i - 1];
_matrix[buf].dig[ROW_SIZE - i - 1] = t;
}
} else // really a TFLR
{
for (uint8_t i = 0; i < ROW_SIZE; i++)
_matrix[buf].dig[i] = MAX72XX_BitReverse(_matrix[buf].dig[i]);
}
break;
//--------------
case TRC: // Transform Rotate Clockwise
for (uint8_t i = 0; i < ROW_SIZE; i++)
t[i] = MAX72XX_GetDevColumn(buf, COL_SIZE - 1 - i);
for (uint8_t i = 0; i < ROW_SIZE; i++)
MAX72XX_SetRowOne(buf, i, t[i]);
break;
//--------------
case TINV: // Transform INVert
for (uint8_t i = 0; i < ROW_SIZE; i++)
_matrix[buf].dig[i] = ~_matrix[buf].dig[i];
break;
default:
return (false);
}
_matrix[buf].changed = ALL_CHANGED;
return (true);
}
bool MAX72XX_TransformOne(uint8_t buf, transformType_t ttype)
{
if (buf > LAST_BUFFER)
return (false);
if (!MAX72XX_TransformBuffer(buf, ttype))
return (false);
if (_updateEnabled)
MAX72XX_FlushBufferOne(buf);
return (true);
}
//for pix
bool MAX72XX_GetBuffer(uint16_t col, uint8_t size, uint8_t *pd)
{
if ((col >= MAX72XX_GetColumnCount()) || (pd == NULL))
return (false);
for (uint8_t i = 0; i < size; i++)
*pd++ = MAX72XX_GetPixelColumn(col--);
return (true);
}
bool MAX72XX_SetBuffer(uint16_t col, uint8_t size, uint8_t *pd)
{
bool b = _updateEnabled;
if ((col >= MAX72XX_GetColumnCount()) || (pd == NULL))
return (false);
_updateEnabled = false;
for (uint8_t i = 0; i < size; i++)
MAX72XX_SetPixelColumn(col--, *pd++);
_updateEnabled = b;
if (_updateEnabled)
MAX72XX_FlushBufferAll();
return (true);
}
bool MAX72XX_GetPoint(uint8_t r, uint16_t c)
{
uint8_t buf = c / COL_SIZE;
c %= COL_SIZE;
if ((buf > LAST_BUFFER) || (r >= ROW_SIZE) || (c >= COL_SIZE))
return (false);
if (_hwDigRows)
return (bitRead(_matrix[buf].dig[HW_ROW(r)], HW_COL(c)) == 1);
else
return (bitRead(_matrix[buf].dig[HW_ROW(c)], HW_COL(r)) == 1);
}
bool MAX72XX_SetPoint(uint8_t r, uint16_t c, bool state)
{
uint8_t buf = c / COL_SIZE;
c %= COL_SIZE;
if ((buf > LAST_BUFFER) || (r >= ROW_SIZE) || (c >= COL_SIZE))
return (false);
if (state)
{
if (_hwDigRows)
bitSet(_matrix[buf].dig[HW_ROW(r)], HW_COL(c));
else
bitSet(_matrix[buf].dig[HW_ROW(c)], HW_COL(r));
} else
{
if (_hwDigRows)
bitClear(_matrix[buf].dig[HW_ROW(r)], HW_COL(c));
else
bitClear(_matrix[buf].dig[HW_ROW(c)], HW_COL(r));
}
if (_hwDigRows)
bitSet(_matrix[buf].changed, HW_ROW(r));
else
bitSet(_matrix[buf].changed, HW_ROW(c));
if (_updateEnabled)
MAX72XX_FlushBufferOne(buf);
return (true);
}
bool MAX72XX_SetRowBy(uint8_t startDev, uint8_t endDev, uint8_t r, uint8_t value)
{
bool b = _updateEnabled;
if ((r >= ROW_SIZE) || (endDev < startDev))
return (false);
_updateEnabled = false;
for (uint8_t i = startDev; i <= endDev; i++)
MAX72XX_SetRowOne(i, r, value);
_updateEnabled = b;
if (_updateEnabled)
MAX72XX_FlushBufferAll();
return (true);
}
bool MAX72XX_SetRowAll(uint8_t r, uint8_t value)
{
return MAX72XX_SetRowBy(0, MAX72XX_GetDeviceCount() - 1, r, value);
}
bool MAX72XX_TransformBy(uint8_t startDev, uint8_t endDev, transformType_t ttype)
{
// uint8_t t[ROW_SIZE];
uint8_t colData;
bool b = _updateEnabled;
if (endDev < startDev)
return (false);
_updateEnabled = false;
switch (ttype)
{
case TSL: // Transform Shift Left one pixel element (with overflow)
colData = 0;
if (_wrapAround)
colData = MAX72XX_GetPixelColumn(((endDev + 1) * COL_SIZE) - 1);
// shift all the buffers along
for (int8_t buf = endDev; buf >= startDev; --buf)
{
MAX72XX_TransformBuffer(buf, ttype);
// handle the boundary condition
MAX72XX_SetDevColumn(buf, 0, MAX72XX_GetDevColumn(buf - 1, COL_SIZE - 1));
}
MAX72XX_SetPixelColumn((startDev * COL_SIZE), colData);
break;
case TSR: // Transform Shift Right one pixel element (with overflow)
// if we can call the user function later then we don't need to do anything here
// however, wraparound mode means we know the data so no need to request from the
// callback at all - just save it for later.
colData = 0;
if (_wrapAround)
colData = MAX72XX_GetPixelColumn(startDev * COL_SIZE);
// shift all the buffers along
for (uint8_t buf = startDev; buf <= endDev; buf++)
{
MAX72XX_TransformBuffer(buf, ttype);
// handle the boundary condition
MAX72XX_SetDevColumn(buf, COL_SIZE - 1, MAX72XX_GetDevColumn(buf + 1, 0));
}
MAX72XX_SetPixelColumn(((endDev + 1) * COL_SIZE) - 1, colData);
break;
case TFLR: // Transform Flip Left to Right (use the whole field)
// first reverse the device buffers end for end
for (uint8_t buf = 0; buf < (endDev - startDev + 1) / 2; buf++)
{
deviceInfo_t t;
t = _matrix[startDev + buf];
_matrix[startDev + buf] = _matrix[endDev - buf];
_matrix[endDev - buf] = t;
}
// now reverse the columns in each device
for (uint8_t buf = startDev; buf <= endDev; buf++)
MAX72XX_TransformBuffer(buf, ttype);
break;
// These next transformations work the same just by doing the individual devices
case TSU: // Transform Shift Up one pixel element
case TSD: // Transform Shift Down one pixel element
case TFUD: // Transform Flip Up to Down
case TRC: // Transform Rotate Clockwise
case TINV: // Transform INVert
for (uint8_t buf = startDev; buf <= endDev; buf++)
MAX72XX_TransformBuffer(buf, ttype);
break;
default:
return (false);
}
_updateEnabled = b;
if (_updateEnabled)
MAX72XX_FlushBufferAll();
return (true);
}
bool MAX72XX_TransformAll(transformType_t ttype)
{
return MAX72XX_TransformBy(0, MAX72XX_GetDeviceCount() - 1, ttype);
}
void MAX72XX_UpdateAll(void)
{
MAX72XX_FlushBufferAll();
}
void MAX72XX_UpdateMode(controlValue_t mode)
{
MAX72XX_ControlAll(UPDATE, mode);
}
void MAX72XX_UpdateOne(uint8_t buf)
{
MAX72XX_FlushBufferOne(buf);
}
void MAX72XX_Wraparound(controlValue_t mode)
{
MAX72XX_ControlAll(WRAPAROUND, mode);
}
|
lindianfeng/kaika_clock_firmware_new
|
User/Src/clock.c
|
/*
* clock.c
*
* Created on: Dec 10, 2020
* Author: linhao
*/
#include "gpio.h"
#include "i2c.h"
#include "spi.h"
#include "adc.h"
#include "ds3231.h"
#include "max72xx.h"
#include "main.h"
#include "dht11.h"
#include "cmsis_os.h"
#include "key.h"
#include "delay.h"
#include "utils.h"
#include "sht30.h"
#include "usbd_cdc_if.h"
extern ADC_HandleTypeDef hadc1;
extern RTC_Data rtc;
extern osThreadId mainTaskHandle;
extern osThreadId keyTaskHandle;
extern osTimerId getRTCTimerHandle;
extern osTimerId getSensorDataTimerHandle;
extern osTimerId togglePointTimerHandle;
extern osTimerId showDateTimerHandle;
extern uint8_t UserRxBufferFS[APP_RX_DATA_SIZE];
extern vcp_rx_t rx_data_ctr;
extern void SystemClock_Config(void);
extern void MX_FREERTOS_Init(void);
extern void MX_USB_DEVICE_Init(void);
static uint8_t temp_int = 0;
static uint8_t temp_deci = 0;
static uint8_t humi_int = 0;
uint32_t volatile clock_flag = 0;
#define POINT_COL_NUM 11
static const uint8_t numbers_5x8[][8] =
{
{ 0x0e, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0e },
{ 0x04, 0x06, 0x04, 0x04, 0x04, 0x04, 0x04, 0x0e },
{ 0x0e, 0x11, 0x10, 0x10, 0x08, 0x04, 0x02, 0x1f },
{ 0x0e, 0x11, 0x10, 0x0c, 0x10, 0x10, 0x11, 0x0e },
{ 0x10, 0x18, 0x14, 0x12, 0x11, 0x1f, 0x10, 0x10 },
{ 0x1f, 0x01, 0x01, 0x0f, 0x10, 0x10, 0x11, 0x0e },
{ 0x0e, 0x11, 0x01, 0x0f, 0x11, 0x11, 0x11, 0x0e },
{ 0x1f, 0x10, 0x10, 0x08, 0x04, 0x02, 0x02, 0x02 },
{ 0x0e, 0x11, 0x11, 0x0e, 0x11, 0x11, 0x11, 0x0e },
{ 0x0e, 0x11, 0x11, 0x11, 0x1e, 0x10, 0x11, 0x0e },
{ 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x07, 0x04, 0x07, 0x01, 0x07 },
{ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01 },
{ 0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x01, 0x00 }
};
static const uint8_t numbers_3x5[10][8] = {
{ 0x00, 0x00, 0x00, 0x07, 0x05, 0x05, 0x05, 0x07 },
{ 0x00, 0x00, 0x00, 0x02, 0x02, 0x02, 0x02, 0x02 },
{ 0x00, 0x00, 0x00, 0x07, 0x04, 0x07, 0x01, 0x07 },
{ 0x00, 0x00, 0x00, 0x07, 0x04, 0x07, 0x04, 0x07 },
{ 0x00, 0x00, 0x00, 0x05, 0x05, 0x07, 0x04, 0x04 },
{ 0x00, 0x00, 0x00, 0x07, 0x01, 0x07, 0x04, 0x07 },
{ 0x00, 0x00, 0x00, 0x07, 0x01, 0x07, 0x05, 0x07 },
{ 0x00, 0x00, 0x00, 0x07, 0x04, 0x04, 0x04, 0x04 },
{ 0x00, 0x00, 0x00, 0x07, 0x05, 0x07, 0x05, 0x07 },
{ 0x00, 0x00, 0x00, 0x07, 0x05, 0x07, 0x04, 0x07 }
};
static const uint8_t signs[][8] = {
{ 0x00, 0x80, 0x80, 0x00, 0x00, 0x80, 0x80, 0x00 },
{ 0x3c, 0x42, 0xa5, 0x81, 0xa5, 0x99, 0x42, 0x3c },
{ 0x3c, 0x42, 0xa5, 0x81, 0xbd, 0x81, 0x42, 0x3c },
{ 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x06, 0x0c, 0x18, 0x30, 0x18, 0x0c, 0x06 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }
};
enum
{
CLOCK_FLAG_REFRESH_DISPLAY = 1,
CLOCK_FLAG_TIME_SECOND_CHANGED = 2,
CLOCK_FLAG_SHOW_DATE = 3,
CLOCK_FLAG_SHOW_TEMP = 4,
CLOCK_FLAG_FLASH_POINT = 5,
CLOCK_FLAG_KEY1_PRESSED = 6,
CLOCK_FLAG_KEY2_PRESSED = 7,
CLOCK_FLAG_SET_RTC = 8,
};
static inline void SetClockFlag(uint32_t bit)
{
bitSet(clock_flag, bit);
}
static inline void ClearClockFlag(uint32_t bit)
{
bitClear(clock_flag, bit);
}
static inline void FlipClockFlag(uint32_t bit)
{
bitFlip(clock_flag, bit);
}
static inline bool TestClockFlag(uint32_t bit)
{
return bitRead(clock_flag, bit);
}
static bool TestAndClearFlag(uint32_t bit)
{
if (bitRead(clock_flag, bit))
{
bitClear(clock_flag, bit);
return true;
}
return false;
}
void led_display_time(uint8_t hour, uint8_t minute, uint8_t second)
{
const uint8_t hour_1st = hour / 10;
const uint8_t hour_2nd = hour % 10;
const uint8_t minute_1st = minute / 10;
const uint8_t minute_2nd = minute % 10;
const uint8_t second_1st = second / 10;
const uint8_t second_2nd = second % 10;
MAX72XX_ClearAll();
for (uint8_t row = 0; row < 8; row++)
{
for (uint8_t dev = 0; dev < MAX_DEVICES; dev++)
{
uint8_t data = numbers_5x8[0][row];
switch (dev)
{
case 0:
data = (numbers_5x8[hour_1st][row] | numbers_5x8[hour_2nd][row] << 5);
break;
case 1:
data = numbers_5x8[hour_2nd][row] >> 3 | ((numbers_5x8[minute_1st][row]) << 5);
break;
case 2:
data = (numbers_5x8[minute_1st][row] >> 3) | (numbers_5x8[minute_2nd][row] << 2);
break;
case 3:
data = (numbers_3x5[second_1st][row]) << 1 | ((numbers_3x5[second_2nd][row]) << 5);
break;
}
MAX72XX_SetRowOne(dev, row, data);
}
}
}
void led_display_date(uint8_t month, uint8_t day_of_month, uint8_t dayofweek)
{
const uint8_t month_1st = month / 10;
const uint8_t month_2nd = month % 10;
const uint8_t day_1st = day_of_month / 10;
const uint8_t day_2nd = day_of_month % 10;
const uint8_t day_of_week = dayofweek;
MAX72XX_ClearAll();
for (uint8_t row = 0; row < 8; row++)
{
for (uint8_t dev = 0; dev < MAX_DEVICES; dev++)
{
uint8_t data = 0;
switch (dev)
{
case 0:
data = numbers_5x8[month_1st][row] << 2 | numbers_5x8[month_2nd][row] << 7;
break;
case 1:
data = numbers_5x8[month_2nd][row] >> 1 | signs[3][row] << 5;
break;
case 2:
data = numbers_5x8[day_1st][row] << 1 | numbers_5x8[day_2nd][row] << 6;
break;
case 3:
data = numbers_5x8[day_2nd][row] >> 2 | (numbers_3x5[day_of_week == 1 ? 7 : day_of_week - 1][row]) << 5;
break;
}
MAX72XX_SetRowOne(dev, row, data);
}
}
}
void led_display_temp_and_humi(uint8_t temp_int, uint8_t temp_decimals, uint8_t humidity)
{
const uint8_t temp_int_1st = temp_int / 10;
const uint8_t temp_int_2nd = temp_int % 10;
const uint8_t temp_decimals_1st = temp_decimals & 0x0f;
const uint8_t humidity_1st = humidity / 10;
const uint8_t humidity_2nd = humidity % 10;
MAX72XX_ClearAll();
for (uint8_t row = 0; row < 8; row++)
{
for (uint8_t dev = 0; dev < MAX_DEVICES; dev++)
{
uint8_t data = 0;
switch (dev)
{
case 0:
data = numbers_5x8[temp_int_1st][row] | numbers_5x8[temp_int_2nd][row] << 5;
break;
case 1:
data = numbers_5x8[temp_int_2nd][row] >> 3 | signs[5][row] << 3 | numbers_3x5[temp_decimals_1st][row] << 5;
break;
case 2:
data = numbers_5x8[humidity_1st][row] << 6;
break;
case 3:
data = (numbers_5x8[humidity_1st][row]) >> 2 | ((numbers_5x8[humidity_2nd][row]) << 3);
break;
}
MAX72XX_SetRowOne(dev, row, data);
}
}
}
static void Clock_SetRunLed(bool b)
{
HAL_GPIO_WritePin(RUN_LED_GPIO_Port, RUN_LED_Pin, b);
}
static void Clock_Init(void)
{
DS3231_Init();
MAX72XX_Init();
sht30_init();
Clock_SetRunLed(true);
}
static bool Clock_UpdateRTC(void)
{
static uint8_t old_sec = 0;
DS3231_GetTime(&rtc);
if (rtc.Sec != old_sec)
{
old_sec = rtc.Sec;
return true;
}
return false;
}
static void Clock_FlashTimePoint()
{
const bool need_flash_point = TestClockFlag(CLOCK_FLAG_FLASH_POINT);
MAX72XX_SetPoint(1, POINT_COL_NUM, need_flash_point);
MAX72XX_SetPoint(2, POINT_COL_NUM, need_flash_point);
MAX72XX_SetPoint(5, POINT_COL_NUM, need_flash_point);
MAX72XX_SetPoint(6, POINT_COL_NUM, need_flash_point);
}
static void Clock_ShowTime()
{
led_display_time(rtc.Hour, rtc.Min, rtc.Sec);
Clock_FlashTimePoint();
SetClockFlag(CLOCK_FLAG_REFRESH_DISPLAY);
}
static void Clock_ShowDate(void)
{
led_display_date(rtc.Month, rtc.Day, rtc.DaysOfWeek);
SetClockFlag(CLOCK_FLAG_REFRESH_DISPLAY);
}
static void Clock_ShowTemp(void)
{
led_display_temp_and_humi(temp_int, temp_deci, humi_int);
SetClockFlag(CLOCK_FLAG_REFRESH_DISPLAY);
}
static void Clock_SecondJumpUp(void)
{
Clock_FlashTimePoint();
MAX72XX_TransformOne(3, TSU);
SetClockFlag(CLOCK_FLAG_REFRESH_DISPLAY);
}
static void Clock_SecondJumpDown(void)
{
Clock_FlashTimePoint();
MAX72XX_TransformOne(3, TSD);
SetClockFlag(CLOCK_FLAG_REFRESH_DISPLAY);
}
static void Clock_UpdateDiplay()
{
if (TestAndClearFlag(CLOCK_FLAG_REFRESH_DISPLAY))
{
MAX72XX_UpdateAll();
}
}
static void Clock_ShowWelcome(void)
{
MAX72XX_ControlAll(UPDATE, 1);
MAX72XX_ClearAll();
osDelay(200);
for (uint8_t row = 0; row < 8; row++)
{
MAX72XX_SetRowAll(row, 0xff);
osDelay(20);
}
osDelay(200);
MAX72XX_ClearAll();
for (int i = 0; i < 32; i++)
{
MAX72XX_SetPixelColumn(i, 0xff);
vTaskDelay(15);
MAX72XX_SetPixelColumn(i, 0x00);
vTaskDelay(15);
}
osDelay(200);
MAX72XX_ClearAll();
for (int i = 0; i < 8; i++)
{
MAX72XX_SetRowAll(i, 0xff);
vTaskDelay(20);
MAX72XX_SetRowAll(i, 0x00);
osDelay(20);
}
vTaskDelay(200);
MAX72XX_ClearAll();
Clock_ShowTime();
MAX72XX_ControlAll(UPDATE, 0);
}
enum
{
STATE_CLOCK_NONE = -1,
STATE_CLOCK_TIME_SHOW = 0,
STATE_CLOCK_TIME_SEC_CHANGED = 1,
STATE_CLOCK_TIME_SEC_JUMP_UP = 2,
STATE_CLOCK_TIME_SEC_JUMP_DOWN = 3,
STATE_CLOCK_DATE = 4,
STATE_CLOCK_TEMP = 5,
STATE_CLOCK_KEY_INPUT0 = 6,
STATE_CLOCK_KEY_INPUT1 = 7,
STATE_CLOCK_KEY_INPUT2 = 8,
STATE_CLOCK_KEY_INPUT3 = 9,
STATE_CLOCK_KEY_INPUT4 = 10,
};
typedef struct
{
uint32_t state;
uint32_t next_state;
int32_t repeat;
uint32_t duration;
void (*callback)(void);
bool change_state;
} ClockState;
static ClockState clock_states[] = {
{
.state = STATE_CLOCK_TIME_SHOW,
.next_state = STATE_CLOCK_NONE,
.repeat = -1,
.duration = 10,
.callback = Clock_ShowTime,
.change_state = 0
},
{
.state = STATE_CLOCK_TIME_SEC_CHANGED,
.next_state = STATE_CLOCK_TIME_SEC_JUMP_UP,
.repeat = 1,
.duration = 0,
.callback = Clock_ShowTime,
.change_state = 0
},
{
.state = STATE_CLOCK_TIME_SEC_JUMP_UP,
.next_state = STATE_CLOCK_TIME_SEC_JUMP_DOWN,
.repeat = 2,
.duration = 98,
.callback = Clock_SecondJumpUp,
.change_state = 0
},
{
.state = STATE_CLOCK_TIME_SEC_JUMP_DOWN,
.next_state = STATE_CLOCK_TIME_SHOW,
.repeat = 2,
.duration = 98,
.callback = Clock_SecondJumpDown,
.change_state = 0
},
{
.state = STATE_CLOCK_DATE,
.next_state = STATE_CLOCK_TEMP,
.repeat = 1,
.duration = 2000,
.callback = Clock_ShowDate,
.change_state = 0
},
{
.state = STATE_CLOCK_TEMP,
.next_state = STATE_CLOCK_TIME_SHOW,
.repeat = 1,
.duration = 2000,
.callback = Clock_ShowTemp,
.change_state = 0
},
{
.state = STATE_CLOCK_KEY_INPUT0,
.next_state = STATE_CLOCK_TIME_SHOW,
.repeat = 1,
.duration = 2000,
.callback = Clock_ShowTemp,
.change_state = 0
},
{
.state = STATE_CLOCK_KEY_INPUT1,
.next_state = STATE_CLOCK_TIME_SHOW,
.repeat = 1,
.duration = 2000,
.callback = Clock_ShowTemp,
.change_state = 0
},
{
.state = STATE_CLOCK_KEY_INPUT2,
.next_state = STATE_CLOCK_TIME_SHOW,
.repeat = 1,
.duration = 2000,
.callback = Clock_ShowTemp,
.change_state = 0
},
{
.state = STATE_CLOCK_KEY_INPUT3,
.next_state = STATE_CLOCK_TIME_SHOW,
.repeat = 1,
.duration = 2000,
.callback = Clock_ShowTemp,
.change_state = 0
},
{
.state = STATE_CLOCK_KEY_INPUT4,
.next_state = STATE_CLOCK_TIME_SHOW,
.repeat = 1,
.duration = 2000,
.callback = Clock_ShowTemp,
.change_state = 0
}
};
static ClockState clock_s = { 0 };
static inline void ChangeClockState(ClockState *s, int clock_state_n)
{
if (STATE_CLOCK_NONE == clock_state_n)
{
return;
}
*s = clock_states[clock_state_n];
}
static inline void TickState(ClockState *s)
{
if (!s->repeat)
{
s->change_state = 1;
return;
}
if (s->callback)
{
s->callback();
}
if (s->repeat != -1)
{
s->repeat--;
if (!s->repeat)
{
s->change_state = 1;
}
}
}
void CallbackGetRTC(void const *argument)
{
if (Clock_UpdateRTC())
{
SetClockFlag(CLOCK_FLAG_TIME_SECOND_CHANGED);
usb_printf("sec changed!\r\n");
}
}
void CallbackGetSensorData(void const *argument)
{
//DHT11_ReadData(&temp_int, &temp_deci, &humi_int);
//SetClockFlag(CLOCK_FLAG_SHOW_TEMP);
float t = 0;
float h = 0;
sht30_sample(&t, &h);
temp_int = (int) t;
temp_deci = t * 10 - temp_int * 10;
humi_int = (int) h;
//usb_printf("r:%d,t:%d,h:%d \r\n",r,(int)t,(int)h);
}
void CallbackShowDate(void const *argument)
{
SetClockFlag(CLOCK_FLAG_SHOW_DATE);
}
void CallbackTogglePoint(void const *argument)
{
FlipClockFlag(CLOCK_FLAG_FLASH_POINT);
//Clock_SetRunLed(TestClockFlag(CLOCK_FLAG_FLASH_POINT));
}
void StartCheckKeyTask(void const *argument)
{
for (;;)
{
if (Key_Scan(KEY1_GPIO_Port, KEY1_Pin) == KEY_ON)
{
/* K1 被按下 */
SetClockFlag(CLOCK_FLAG_KEY1_PRESSED);
}
if (Key_Scan(KEY2_GPIO_Port, KEY2_Pin) == KEY_ON)
{
/* K2 被按下 */
SetClockFlag(CLOCK_FLAG_KEY2_PRESSED);
}
osDelay(100);
}
}
void StartAdcTask(void const *argument)
{
uint32_t ad_Value = 0;
for (;;)
{
HAL_ADC_Start(&hadc1);
HAL_ADC_PollForConversion(&hadc1, 50);
if (HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC))
{
ad_Value = HAL_ADC_GetValue(&hadc1);
const uint8_t cur_intensity = MAX72XX_GetIntensity();
const uint8_t cal_intensity = ad_Value > 2999 ? 0 : 15 - ad_Value / 200;
//usb_printf("ad_value:%d,cur_intensity:%d,cal_intensity:%d.\r\n", ad_Value, cur_intensity, cal_intensity);
if (cal_intensity != cur_intensity)
{
MAX72XX_SetIntensity(cal_intensity > 5 ? 5 : cal_intensity);
}
}
osDelay(500);
}
}
void StartSetRTCTask(void const *argument)
{
for (;;)
{
if (rx_data_ctr.flag)
{
rx_data_ctr.flag = 0;
do
{
if (14 != rx_data_ctr.rxlen)
{
usb_printf("ERR,len:%d.\r\n", rx_data_ctr.rxlen);
break;
}
usb_printf("OK,len:%d.\r\n", rx_data_ctr.rxlen);
const uint8_t year = (UserRxBufferFS[0] - 48) * 10 + (UserRxBufferFS[1] - 48);
const uint8_t month = (UserRxBufferFS[2] - 48) * 10 + (UserRxBufferFS[3] - 48);
const uint8_t day = (UserRxBufferFS[4] - 48) * 10 + (UserRxBufferFS[5] - 48);
const uint8_t hour = (UserRxBufferFS[6] - 48) * 10 + (UserRxBufferFS[7] - 48);
const uint8_t min = (UserRxBufferFS[8] - 48) * 10 + (UserRxBufferFS[9] - 48);
const uint8_t sec = (UserRxBufferFS[10] - 48) * 10 + (UserRxBufferFS[11] - 48);
const uint8_t week = UserRxBufferFS[12] - 48 + 1;
rtc.Year = 2000 + year;
rtc.Month = month;
rtc.Day = day;
rtc.Hour = hour;
rtc.Min = min;
rtc.Sec = sec;
rtc.DaysOfWeek = week;
DS3231_SetTime(&rtc);
} while (0);
rx_data_ctr.rxlen = 0;
memset(UserRxBufferFS, 0, APP_RX_DATA_SIZE);
}
osDelay(100);
}
}
static inline bool IsNotInShowTimeState(ClockState *s)
{
if (s->state == STATE_CLOCK_DATE || s->state == STATE_CLOCK_TEMP)
{
return true;
}
return false;
}
void StartMainTask(void const *argument)
{
Clock_Init();
Clock_ShowWelcome();
DHT11_Init();
Clock_SetRunLed(false);
clock_s = clock_states[0];
usb_printf("start main task\r\n");
for (;;)
{
if (TestAndClearFlag(CLOCK_FLAG_KEY1_PRESSED))
{
ChangeClockState(&clock_s, STATE_CLOCK_DATE);
} else if (TestAndClearFlag(CLOCK_FLAG_KEY2_PRESSED))
{
ChangeClockState(&clock_s, STATE_CLOCK_TEMP);
} else if (!IsNotInShowTimeState(&clock_s) && TestAndClearFlag(CLOCK_FLAG_TIME_SECOND_CHANGED))
{
ChangeClockState(&clock_s, STATE_CLOCK_TIME_SEC_CHANGED);
} else if (TestAndClearFlag(CLOCK_FLAG_SHOW_DATE))
{
ChangeClockState(&clock_s, STATE_CLOCK_DATE);
}
TickState(&clock_s);
Clock_UpdateDiplay();
osDelay(clock_s.duration);
if (clock_s.change_state)
{
//usb_printf("clock_s cur_s:%d,next_s:%d.\r\n",clock_s.state,clock_s.next_state);
ChangeClockState(&clock_s, clock_s.next_state);
}
osDelay(1);
}
}
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_I2C1_Init();
MX_I2C2_Init();
MX_SPI1_Init();
MX_ADC1_Init();
MX_USB_DEVICE_Init();
DWT_Init();
MX_FREERTOS_Init();
osTimerStart(getRTCTimerHandle, 100);
osTimerStart(getSensorDataTimerHandle, 20 * 1000);
osTimerStart(togglePointTimerHandle, 500);
osTimerStart(showDateTimerHandle, 60 * 1000);
osKernelStart();
while (1)
{
}
}
|
lindianfeng/kaika_clock_firmware_new
|
User/Inc/key.h
|
<reponame>lindianfeng/kaika_clock_firmware_new
/*
* key.h
*
* Created on: Dec 10, 2020
* Author: linhao
*/
#ifndef KEY_H_
#define KEY_H_
#include <stdint.h>
#include "stm32f1xx.h"
#define KEY_ON 0
#define KEY_OFF 1
uint8_t Key_Scan(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin);
#endif /* KEY_H_ */
|
lindianfeng/kaika_clock_firmware_new
|
User/Inc/delay.h
|
/*
* delay.h
*
* Created on: Dec 10, 2020
* Author: linhao
*/
#ifndef DELAY_H_
#define DELAY_H_
#include "stm32f1xx.h"
#include <stdint.h>
uint32_t DWT_Init(void);
void DWT_DelayUs(uint32_t us);
void DWT_DelayMs(uint32_t ms);
static inline uint32_t DWT_MaxSec(void)
{
return (UINT32_MAX / SystemCoreClock);
}
static inline uint32_t DWT_MaxMsec(void)
{
return (UINT32_MAX / (SystemCoreClock / 1000));
}
static inline uint32_t DWT_MaxUsec(void)
{
return (UINT32_MAX / (SystemCoreClock / 1000000));
}
static inline uint32_t DWT_GetCycles(void)
{
return (DWT->CYCCNT);
}
#endif /* DELAY_H_ */
|
lindianfeng/kaika_clock_firmware_new
|
User/Src/dht11.c
|
/*
* dht11.c
*
* Created on: Jan 9, 2021
* Author: lindianfeng
*/
#include "dht11.h"
#include "delay.h"
/**
* @brief DHT11 输出模式
*/
static inline void DHT11_Mode_OUT_PP(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Pin = DHT11_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(DHT11_GPIO_Port, &GPIO_InitStruct);
}
/**
* @brief DHT11 输入模式
*/
static inline void DHT11_Mode_IN_NP(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.Pin = DHT11_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(DHT11_GPIO_Port, &GPIO_InitStruct);
}
//复位DHT11
static inline void DHT11_Rst(void)
{
DHT11_Mode_IN_NP();
DWT_DelayMs(1);
DHT11_Mode_OUT_PP(); //SET OUTPUT
DHT11_OUT_0; //拉低DQ
DWT_DelayMs(20); //拉低至少18ms
DHT11_OUT_1; //DQ=1
DWT_DelayUs(30); //主机拉高20~40us
}
//等待DHT11的回应
//返回1:未检测到DHT11的存在
//返回0:存在
static inline uint8_t DHT11_Check(void)
{
uint8_t retry = 0;
DHT11_Mode_IN_NP(); //SET INPUT
while (DHT11_IN && retry < 100)
{
//DHT11 Pull down 40~80us
retry++;
DWT_DelayUs(1);
}
if (retry >= 100)
{
return 1;
}
retry = 0;
while (!DHT11_IN && retry < 100)
{
//DHT11 Pull up 40~80us
retry++;
DWT_DelayUs(1);
}
if (retry >= 100)
{
return 1; //chack error
}
return 0;
}
//从DHT11读取一个位
//返回值:1/0
static inline uint8_t DHT11_ReadBit(void)
{
uint8_t retry = 0;
while (DHT11_IN && retry < 100)
{
//wait become Low level
retry++;
DWT_DelayUs(1);
}
retry = 0;
while (!DHT11_IN && retry < 100)
{
//wait become High level
retry++;
DWT_DelayUs(1);
}
DWT_DelayUs(40); //wait 40us
return DHT11_IN == GPIO_PIN_RESET ? 0 : 1;
}
//从DHT11读取一个字节
//返回值:读到的数据
static inline uint8_t DHT11_ReadByte(void)
{
uint8_t dat = 0;
for (uint8_t i = 0; i < 8; i++)
{
dat <<= 1;
dat |= DHT11_ReadBit();
}
return dat;
}
//从DHT11读取一次数据
//temp:温度值(范围:0~50°)
//humi:湿度值(范围:20%~90%)
//返回值:0,正常;1,读取失败
uint8_t DHT11_ReadData(uint8_t *temp_int, uint8_t *temp_deci, uint8_t *humi_int)
{
uint8_t buf[5] = { 0, 0, 0, 0, 0 };
DHT11_Rst();
if (DHT11_Check())
{
return 1;
}
for (int i = 0; i < 5; i++)
{
//读取40位数据
buf[i] = DHT11_ReadByte();
}
if ((buf[0] + buf[1] + buf[2] + buf[3]) == buf[4])
{
*humi_int = buf[0];
*temp_int = buf[2];
*temp_deci = buf[3];
}
return 0;
}
uint8_t DHT11_ReadDataFloat(float *temp, float *humi)
{
uint8_t buf[5] = { 0, 0, 0, 0, 0 };
DHT11_Rst();
if (DHT11_Check())
{
return 1;
}
for (int i = 0; i < 5; i++)
{
//读取40位数据
buf[i] = DHT11_ReadByte();
}
if ((buf[0] + buf[1] + buf[2] + buf[3]) == buf[4])
{
*humi = ((buf[0] << 8) + buf[1]) / 10.0;
*temp = ((buf[2] << 8) + buf[3]) / 10.0;
}
return 0;
}
uint8_t DHT11_Init(void)
{
DHT11_Mode_OUT_PP();
DHT11_Rst();
return DHT11_Check();
}
|
lindianfeng/kaika_clock_firmware_new
|
User/Src/at24cxx.c
|
/*
* at24cxx.c
*
* Created on: 2021年1月19日
* Author: linhao
*/
#include "at24cxx.h"
#include "cmsis_os.h"
#include "stm32f1xx_hal.h"
extern I2C_HandleTypeDef hi2c2;
void AT24CXX_Write(uint16_t reg_address, uint8_t data)
{
HAL_I2C_Mem_Write(&hi2c2, AT24CXX_DEV_ADDRESS, reg_address, I2C_MEMADD_SIZE_16BIT, &data, 1, 100);
AT24CXX_DELAY_MS(5); //AT24C64的最长写入时间是5ms
}
uint8_t AT24CXX_Read(uint16_t reg_address)
{
uint8_t data = 0;
HAL_I2C_Mem_Read(&hi2c2, AT24CXX_DEV_ADDRESS, reg_address, I2C_MEMADD_SIZE_16BIT, &data, 2, 100);
return data;
}
|
lindianfeng/kaika_clock_firmware_new
|
User/Inc/utils.h
|
<filename>User/Inc/utils.h
/*
* utils.h
*
* Created on: Dec 11, 2020
* Author: linhao
*/
#ifndef UTILS_H_
#define UTILS_H_
#define MAX_DEBUG 0 ///< Enable or disable (default) debugging output from the MD_MAX72xx library
#define bitRead(value, bit) (((value) >> (bit)) & 0x01)
#define bitSet(value, bit) ((value) |= (1UL << (bit)))
#define bitClear(value, bit) ((value) &= ~(1UL << (bit)))
#define bitWrite(value, bit, bitvalue) (bitvalue ? bitSet(value, bit) : bitClear(value, bit))
#define bitFlip(value,bit) ((value) ^= (1UL << (bit)))
#endif /* UTILS_H_ */
|
lindianfeng/kaika_clock_firmware_new
|
User/Src/sht30.c
|
<gh_stars>0
/*
* sht30.c
*
* Created on: 2021年2月1日
* Author: linhao
*/
#include "sht30.h"
#include "cmsis_os.h"
#include "stm32f1xx_hal.h"
extern I2C_HandleTypeDef hi2c2;
//I2C写2字节命令
uint8_t i2c_write_cmd(uint16_t cmd)
{
uint8_t cmd_buff[2] = { 0, 0 };
cmd_buff[0] = cmd >> 8;
cmd_buff[1] = cmd;
return HAL_I2C_Master_Transmit(&hi2c2, SHT_ADDR, cmd_buff, 2, 0xffff);
}
//CRC校验计算
#define CRC8_POLYNOMIAL 0x31
uint8_t CheckCrc8(uint8_t *message, uint8_t initial_value)
{
uint8_t remainder;
uint8_t i = 0, j = 0;
remainder = initial_value;
for (j = 0; j < 2; j++)
{
remainder ^= message[j];
for (i = 0; i < 8; i++)
{
if (remainder & 0x80)
{
remainder = (remainder << 1) ^ CRC8_POLYNOMIAL;
}
else
{
remainder = (remainder << 1);
}
}
}
return remainder;
}
//初始化代码
uint8_t sht30_init()
{
//soft reset
i2c_write_cmd(0x30a2);
osDelay(25);
return i2c_write_cmd(0x2220); //repeat medium_2
}
//read temp&humi from sensor
//1-ERR
//0-OK
uint8_t sht30_sample(float *t, float *h)
{
uint8_t read_buff[6] = { 0 };
uint16_t temp_value;
uint16_t humi_value;
i2c_write_cmd(0xe000); //read for period mode
//read value
if (HAL_I2C_Master_Receive(&hi2c2, SHT_ADDR | 0x01, read_buff, 6, 0xffff) != HAL_OK)
{
return HAL_ERROR;
}
//check crc
if (CheckCrc8(read_buff, 0xFF) != read_buff[2] || CheckCrc8(&read_buff[3], 0xFF) != read_buff[5])
{
return HAL_ERROR + 10;
}
//translate
temp_value = ((uint16_t) read_buff[0] << 8) | read_buff[1];
*t = -45 + 175 * ((float) temp_value / 65535);
humi_value = ((uint16_t) read_buff[3] << 8) | read_buff[4];
*h = 100 * ((float) humi_value / 65535);
return HAL_OK;
}
|
lindianfeng/kaika_clock_firmware_new
|
User/Src/key.c
|
/*
* key.c
*
* Created on: Jan 18, 2021
* Author: linhao
*/
#include "key.h"
uint8_t Key_Scan(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin)
{
if (HAL_GPIO_ReadPin(GPIOx, GPIO_Pin) == KEY_ON)
{
/*等待按键释放 */
while (HAL_GPIO_ReadPin(GPIOx, GPIO_Pin) == KEY_ON)
;
return KEY_ON;
}
else
{
return KEY_OFF;
}
}
|
lindianfeng/kaika_clock_firmware_new
|
User/Inc/dht11.h
|
<reponame>lindianfeng/kaika_clock_firmware_new<filename>User/Inc/dht11.h
/*
* dht11.h
*
* Created on: Jan 9, 2021
* Author: lindianfeng
*/
#ifndef INC_DHT11_H_
#define INC_DHT11_H_
#include "main.h"
#define DHT11_OUT_1 HAL_GPIO_WritePin(DHT11_GPIO_Port, DHT11_Pin, GPIO_PIN_SET)
#define DHT11_OUT_0 HAL_GPIO_WritePin(DHT11_GPIO_Port, DHT11_Pin, GPIO_PIN_RESET)
#define DHT11_IN HAL_GPIO_ReadPin(DHT11_GPIO_Port, DHT11_Pin)
uint8_t DHT11_Init(void);
uint8_t DHT11_ReadData(uint8_t *temp_int, uint8_t *temp_deci, uint8_t *humi_int);
uint8_t DHT11_ReadDataFloat(float *temp, float *humi);
#endif /* INC_DHT11_H_ */
|
lindianfeng/kaika_clock_firmware_new
|
User/Src/delay.c
|
/*
* delay.c
*
* Created on: Jan 11, 2021
* Author: linhao
*/
#include "delay.h"
#include "stm32f1xx_hal.h"
//void delay_us(uint32_t us) {
// uint32_t delay = (HAL_RCC_GetHCLKFreq() / 4000000 * us);
// while (delay--) {
// ;
// }
//}
uint32_t DWT_Init(void)
{
if (!(CoreDebug->DEMCR & CoreDebug_DEMCR_TRCENA_Msk))
{
CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
}
/* Reset the clock cycle counter value */
DWT->CYCCNT = 0;
/* Enable clock cycle counter */
DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;
for (int i = 0; i < 5; ++i)
{
__NOP();
}
/* Check if clock cycle counter has started */
return (DWT->CYCCNT) ? 0 : 1;
}
void DWT_DelayUs(volatile uint32_t us)
{
uint32_t startTick = DWT->CYCCNT;
uint32_t delayTicks = us * (SystemCoreClock / 1000000);
while (DWT->CYCCNT - startTick < delayTicks)
;
}
void DWT_DelayMs(uint32_t ms)
{
DWT_DelayUs(1000 * ms);
}
|
rwaithera/larabook
|
node_modules/gulp-sass/node_modules/node-sass/src/custom_importer_bridge.h
|
<filename>node_modules/gulp-sass/node_modules/node-sass/src/custom_importer_bridge.h
#ifndef CUSTOM_IMPORTER_BRIDGE_H
#define CUSTOM_IMPORTER_BRIDGE_H
#include <nan.h>
#include <sass_context.h>
#include "callback_bridge.h"
using namespace v8;
typedef Sass_Import_List SassImportList;
class CustomImporterBridge : public CallbackBridge<SassImportList> {
public:
CustomImporterBridge(NanCallback* cb, bool is_sync) : CallbackBridge<SassImportList>(cb, is_sync) {}
private:
SassImportList post_process_return_value(Handle<Value>) const;
Sass_Import* get_importer_entry(const Local<Object>&) const;
std::vector<Handle<Value>> pre_process_args(std::vector<void*>) const;
};
#endif
|
rwaithera/larabook
|
node_modules/gulp-sass/node_modules/node-sass/src/sass_types/boolean.h
|
#ifndef SASS_TYPES_BOOLEAN_H
#define SASS_TYPES_BOOLEAN_H
#include <nan.h>
#include "value.h"
#include "sass_value_wrapper.h"
namespace SassTypes
{
using namespace v8;
class Boolean : public Value {
public:
static Boolean& get_singleton(bool);
static Handle<Function> get_constructor();
Sass_Value* get_sass_value();
Local<Object> get_js_object();
static NAN_METHOD(New);
static NAN_METHOD(GetValue);
private:
Boolean(bool);
bool value;
Persistent<Object> js_object;
static Persistent<Function> constructor;
static bool constructor_locked;
};
}
#endif
|
rwaithera/larabook
|
node_modules/gulp-sass/node_modules/node-sass/src/callback_bridge.h
|
#ifndef CALLBACK_BRIDGE_H
#define CALLBACK_BRIDGE_H
#include <vector>
#include <nan.h>
#include <condition_variable>
#include <algorithm>
#define COMMA ,
using namespace v8;
template <typename T, typename L = void*>
class CallbackBridge {
public:
CallbackBridge(NanCallback*, bool);
virtual ~CallbackBridge();
// Executes the callback
T operator()(std::vector<void*>);
protected:
// We will expose a bridge object to the JS callback that wraps this instance so we don't loose context.
// This is the V8 constructor for such objects.
static Handle<Function> get_wrapper_constructor();
static void async_gone(uv_handle_t *handle);
static NAN_METHOD(New);
static NAN_METHOD(ReturnCallback);
static Persistent<Function> wrapper_constructor;
Persistent<Object> wrapper;
// The callback that will get called in the main thread after the worker thread used for the sass
// compilation step makes a call to uv_async_send()
static void dispatched_async_uv_callback(uv_async_t*);
// The V8 values sent to our ReturnCallback must be read on the main thread not the sass worker thread.
// This gives a chance to specialized subclasses to transform those values into whatever makes sense to
// sass before we resume the worker thread.
virtual T post_process_return_value(Handle<Value>) const =0;
virtual std::vector<Handle<Value>> pre_process_args(std::vector<L>) const =0;
NanCallback* callback;
bool is_sync;
std::mutex cv_mutex;
std::condition_variable condition_variable;
uv_async_t *async;
std::vector<L> argv;
bool has_returned;
T return_value;
};
template <typename T, typename L>
Persistent<Function> CallbackBridge<T, L>::wrapper_constructor;
template <typename T, typename L>
CallbackBridge<T, L>::CallbackBridge(NanCallback* callback, bool is_sync) : callback(callback), is_sync(is_sync) {
// This assumes the main thread will be the one instantiating the bridge
if (!is_sync) {
this->async = new uv_async_t;
this->async->data = (void*) this;
uv_async_init(uv_default_loop(), this->async, (uv_async_cb) dispatched_async_uv_callback);
}
NanAssignPersistent(wrapper, NanNew(CallbackBridge<T, L>::get_wrapper_constructor())->NewInstance());
NanSetInternalFieldPointer(NanNew(wrapper), 0, this);
}
template <typename T, typename L>
CallbackBridge<T, L>::~CallbackBridge() {
delete this->callback;
NanDisposePersistent(this->wrapper);
if (!is_sync) {
uv_close((uv_handle_t*)this->async, &async_gone);
}
}
template <typename T, typename L>
T CallbackBridge<T, L>::operator()(std::vector<void*> argv) {
// argv.push_back(wrapper);
if (this->is_sync) {
std::vector<Handle<Value>> argv_v8 = pre_process_args(argv);
argv_v8.push_back(NanNew(wrapper));
return this->post_process_return_value(
NanNew<Value>(this->callback->Call(argv_v8.size(), &argv_v8[0]))
);
}
this->argv = argv;
std::unique_lock<std::mutex> lock(this->cv_mutex);
this->has_returned = false;
uv_async_send(this->async);
this->condition_variable.wait(lock, [this] { return this->has_returned; });
return this->return_value;
}
template <typename T, typename L>
void CallbackBridge<T, L>::dispatched_async_uv_callback(uv_async_t *req) {
CallbackBridge* bridge = static_cast<CallbackBridge*>(req->data);
NanScope();
TryCatch try_catch;
std::vector<Handle<Value>> argv_v8 = bridge->pre_process_args(bridge->argv);
argv_v8.push_back(NanNew(bridge->wrapper));
NanNew<Value>(bridge->callback->Call(argv_v8.size(), &argv_v8[0]));
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
}
template <typename T, typename L>
NAN_METHOD(CallbackBridge<T COMMA L>::ReturnCallback) {
NanScope();
CallbackBridge<T, L>* bridge = static_cast<CallbackBridge<T, L>*>(NanGetInternalFieldPointer(args.This(), 0));
TryCatch try_catch;
bridge->return_value = bridge->post_process_return_value(args[0]);
{
std::lock_guard<std::mutex> lock(bridge->cv_mutex);
bridge->has_returned = true;
}
bridge->condition_variable.notify_all();
if (try_catch.HasCaught()) {
node::FatalException(try_catch);
}
NanReturnUndefined();
}
template <typename T, typename L>
Handle<Function> CallbackBridge<T, L>::get_wrapper_constructor() {
if (wrapper_constructor.IsEmpty()) {
Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(New);
tpl->SetClassName(NanNew("CallbackBridge"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
tpl->PrototypeTemplate()->Set(
NanNew("success"),
NanNew<FunctionTemplate>(ReturnCallback)->GetFunction()
);
NanAssignPersistent(wrapper_constructor, tpl->GetFunction());
}
return NanNew(wrapper_constructor);
}
template <typename T, typename L>
NAN_METHOD(CallbackBridge<T COMMA L>::New) {
NanScope();
NanReturnValue(args.This());
}
template <typename T, typename L>
void CallbackBridge<T, L>::async_gone(uv_handle_t *handle) {
delete (uv_async_t *)handle;
}
#endif
|
rwaithera/larabook
|
node_modules/gulp-sass/node_modules/node-sass/src/sass_types/number.h
|
#ifndef SASS_TYPES_NUMBER_H
#define SASS_TYPES_NUMBER_H
#include <nan.h>
#include "sass_value_wrapper.h"
namespace SassTypes
{
using namespace v8;
class Number : public SassValueWrapper<Number> {
public:
Number(Sass_Value*);
static char const* get_constructor_name() { return "SassNumber"; }
static Sass_Value* construct(const std::vector<Local<v8::Value>>);
static void initPrototype(Handle<ObjectTemplate>);
static NAN_METHOD(GetValue);
static NAN_METHOD(GetUnit);
static NAN_METHOD(SetValue);
static NAN_METHOD(SetUnit);
};
}
#endif
|
rwaithera/larabook
|
node_modules/gulp-sass/node_modules/node-sass/src/sass_types/factory.h
|
<gh_stars>100-1000
#ifndef SASS_TYPES_FACTORY_H
#define SASS_TYPES_FACTORY_H
#include <nan.h>
#include <sass_values.h>
#include "value.h"
namespace SassTypes
{
using namespace v8;
// This is the guru that knows everything about instantiating the right subclass of SassTypes::Value
// to wrap a given Sass_Value object.
class Factory {
public:
static void initExports(Handle<Object>);
static Value* create(Sass_Value*);
static Value* unwrap(Handle<v8::Value>);
};
}
#endif
|
invincible1900/C-examples
|
misc/log/main.c
|
/****************************************************************
* Desc: 打印有颜色的日志
*
* Author: X++D
*
****************************************************************/
#include <stdio.h>
#define NONE "\033[m"
#define RED "\033[0;32;31m"
#define LIGHT_RED "\033[1;31m"
#define GREEN "\033[0;32;32m"
#define LIGHT_GREEN "\033[1;32m"
#define BLUE "\033[0;32;34m"
#define LIGHT_BLUE "\033[1;34m"
#define DARK_GRAY "\033[1;30m"
#define CYAN "\033[0;36m"
#define LIGHT_CYAN "\033[1;36m"
#define PURPLE "\033[0;35m"
#define LIGHT_PURPLE "\033[1;35m"
#define BROWN "\033[0;33m"
#define YELLOW "\033[1;33m"
#define LIGHT_GRAY "\033[0;37m"
#define WHITE "\033[1;37m"
#define x_err(fmt, ...) \
while(1) { \
printf("[D] %s:%d, ", __func__, __LINE__); \
printf(RED fmt NONE, ##__VA_ARGS__); \
break; \
}
#define x_log(fmt, ...) \
while(1) { \
printf("[D] %s:%d, ", __func__, __LINE__); \
printf(YELLOW fmt NONE, ##__VA_ARGS__); \
break; \
}
int main(){
x_log("Hello\n");
x_err("Oops\n");
}
|
invincible1900/C-examples
|
misc/lib-test/dynamic-lib/create-lib/libwow.c
|
#include <stdio.h>
#define NONE "\033[m"
#define YELLOW "\033[1;33m"
void wow(){
printf(YELLOW"Wow ~\n"NONE);
return;
}
|
invincible1900/C-examples
|
memory/read_mem.c
|
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#define PAGE_SIZE 4096
void hexdump(const void* data, size_t size) {
char ascii[17];
size_t i, j;
ascii[16] = '\0';
for (i = 0; i < size; ++i) {
printf("%02X ", ((unsigned char*)data)[i]);
if (((unsigned char*)data)[i] >= ' ' && ((unsigned char*)data)[i] <= '~') {
ascii[i % 16] = ((unsigned char*)data)[i];
} else {
ascii[i % 16] = '.';
}
if ((i+1) % 8 == 0 || i+1 == size) {
printf(" ");
if ((i+1) % 16 == 0) {
printf("| %s \n", ascii);
} else if (i+1 == size) {
ascii[(i+1) % 16] = '\0';
if ((i+1) % 16 <= 8) {
printf(" ");
}
for (j = (i+1) % 16; j < 16; ++j) {
printf(" ");
}
printf("| %s \n", ascii);
}
}
}
}
int main(int argc, char *argv[]){
char path[1024];
off_t offset = atoi(argv[2]);
// off_t base = 0x7feccbe00000;
off_t base = 0x0;
pid_t pid;
int mem_fd;
char buf[PAGE_SIZE * 2];
if(argc < 3){
return 0;
// pid = getpid();
}else{
pid = atol(argv[1]);
offset = strtol(argv[2], NULL, 16);
}
sprintf(path, "/proc/%u/mem", pid);
printf("path: %s, offset: %lu\n", path, offset);
mem_fd = open(path, O_RDONLY);
ptrace(PTRACE_ATTACH, pid, NULL, NULL);
waitpid(pid, NULL, 0);
lseek(mem_fd, base + offset, SEEK_SET);
read(mem_fd, buf, PAGE_SIZE);
ptrace(PTRACE_DETACH, pid, NULL, NULL);
hexdump(buf, PAGE_SIZE);
}
|
invincible1900/C-examples
|
exec/main.c
|
#include <unistd.h>
#include <stdio.h>
#include <wait.h>
int main(){
int ret;
ret = fork();
if(ret == 0){
char * argv[] = {"ls", "-l", NULL};
execve("/bin/ls", argv, NULL);
perror("err");
}
ret = fork();
if(ret == 0){
execl("/bin/ls", "ls", "-l", NULL);
perror("err");
}
wait(NULL);
wait(NULL);
}
|
invincible1900/C-examples
|
signal/main.c
|
<gh_stars>1-10
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void sig_handler(int sig){
printf("sig: %d\n", sig);
return;
}
int main(){
printf("pid: %d\n", getpid());
for(int i = SIGHUP; i<= SIGRTMAX; i++){
signal(i, sig_handler);
}
while(1){
sleep(1);
}
}
|
invincible1900/C-examples
|
kvm/1/main.c
|
/*
* Creating a KVM-based VM basically needs 7 steps:
*
* 1. Open the KVM device, `kvmfd=open("/dev/kvm", O_RDWR|O_CLOEXEC)`
* 2. Do create a VM, `vmfd=ioctl(kvmfd, KVM_CREATE_VM, 0)`
* 3. Set up memory for VM guest, `ioctl(vmfd, KVM_SET_USER_MEMORY_REGION, ®ion)`
* 4. Create a virtual CPU for the VM, `vcpufd=ioctl(vmfd, KVM_CREATE_VCPU, 0)`
* 5. Set up memory for the vCPU
* - `vcpu_size=ioctl(kvmfd, KVM_GET_VCPU_MMAP_SIZE, NULL)`
* - `run=(struct kvm_run*)mmap(NULL, mmap_size, PROT_READ|PROT_WRITE, MAP_SHARED, vcpufd, 0)`
* 6. Put assembled code on user memory region, set up vCPU's registers such as rip
* 7. Run and handle exit reason. `while(1) { ioctl(vcpufd, KVM_RUN, 0); ... }`
*
* https://david942j.blogspot.com/2018/10/note-learning-kvm-implement-your-own.html
*/
#include <stdio.h>
#include <linux/kvm.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#define NONE "\033[m"
#define LIGHT_BLUE "\033[1;34m"
#define DBG_MSG(fmt, ...) \
while(1) { \
printf("[D] %s:%d, ", __func__, __LINE__); \
printf(LIGHT_BLUE fmt NONE, ##__VA_ARGS__); \
break; \
}
struct vm {
int dev_fd; // open "/dev/kvm"
int vm_fd; // KVM_CREATE_VM
int vcpu_fd; // KVM_CREATE_VCPU
__u64 ram_start; // KVM_SET_USER_MEMORY_REGION
__u64 ram_size; // KVM_SET_USER_MEMORY_REGION
struct kvm_run *run; // mmap KVM_GET_VCPU_MMAP_SIZE
};
/* 加载 vm binary */
void load_binary(struct vm *vm, char *path){
int fd = open(path, O_RDONLY);
int ret = 0;
char *p = (char *)vm->ram_start;
while(1){
ret = read(fd, p, 4096);
if(ret <= 0)
break;
// DBG_MSG("read size: %d\n", ret);
p += ret;
}
}
void run_vm(struct vm *vm){
DBG_MSG("%s\n", "KVM start run");
while(1){
/* KVM_RUN */
ioctl(vm->vcpu_fd, KVM_RUN, 0);
switch(vm->run->exit_reason){
case KVM_EXIT_UNKNOWN:
DBG_MSG("KVM_EXIT_UNKNOWN\n");
break;
case KVM_EXIT_IO:
DBG_MSG("KVM_EXIT_IO, out port: 0x%x, data: %d\n",
vm->run->io.port,
*(int *)((void *)(vm->run) + vm->run->io.data_offset)
);
break;
case KVM_EXIT_MMIO:
DBG_MSG("KVM_EXIT_MMIO\n");
break;
case KVM_EXIT_HLT:
DBG_MSG("KVM_EXIT_HLT\n");
goto exit_kvm;
case KVM_EXIT_SHUTDOWN:
DBG_MSG("KVM_EXIT_SHUTDOWN\n");
goto exit_kvm;
default:
DBG_MSG("KVM EXIT: %d\n", vm->run->exit_reason);
goto exit_kvm;
}
}
exit_kvm:
return;
}
int main(int argc, char *argv[]){
int ret;
struct vm *vm = malloc(sizeof(struct vm));
/* KVM_CREATE_VM */
vm->dev_fd = open("/dev/kvm", O_RDWR);
DBG_MSG("vm->dev_fd: %d\n", vm->dev_fd);
vm->vm_fd = ioctl(vm->dev_fd, KVM_CREATE_VM, 0);
DBG_MSG("vm->vm_fd: %d\n", vm->vm_fd);
vm->ram_size = 0x200000;
vm->ram_start= (__u64)mmap(NULL, vm->ram_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
DBG_MSG("vm->ram_start: %p\n", (void *)vm->ram_start);
/* KVM_SET_USER_MEMORY_REGION */
struct kvm_userspace_memory_region mem;
mem.slot = 0;
mem.guest_phys_addr = 0;
mem.memory_size = vm->ram_size;
mem.userspace_addr = vm->ram_start;
ret =ioctl(vm->vm_fd, KVM_SET_USER_MEMORY_REGION, &mem);
DBG_MSG("KVM_SET_USER_MEMORY_REGION ret: %d\n", ret);
/* KVM_CREATE_VCPU */
int run_mmap_size;
vm->vcpu_fd = ioctl(vm->vm_fd, KVM_CREATE_VCPU, 0);
DBG_MSG("vm->vcpu_fd: %d\n", vm->vcpu_fd);
/* KVM_GET_VCPU_MMAP_SIZE */
run_mmap_size = ioctl(vm->dev_fd, KVM_GET_VCPU_MMAP_SIZE, 0);
vm->run = mmap(NULL, run_mmap_size, PROT_READ | PROT_WRITE,
MAP_SHARED, vm->vcpu_fd, 0);
DBG_MSG("vm->run: %p\n", vm->run);
/* KMV_SET_SREGS */
struct kvm_sregs sregs;
ioctl(vm->vcpu_fd, KVM_GET_SREGS, &sregs);
sregs.cs.base = sregs.cs.selector = 0;
ioctl(vm->vcpu_fd, KVM_SET_SREGS, &sregs);
/* KMV_SET_REGS */
struct kvm_regs regs;
ioctl(vm->vcpu_fd, KVM_SET_REGS, &(regs));
regs.rflags = 0x2ULL;
regs.rip = 0;
regs.rsp = 0x1000;
regs.rbp= 0;
ret = ioctl(vm->vcpu_fd, KVM_SET_REGS, &(regs));
DBG_MSG("KVM_SET_REGS ret: %d\n", ret);
/* Load binary */
if(argc < 2)
load_binary(vm, "a.bin");
else
load_binary(vm, argv[1]);
run_vm(vm);
}
|
invincible1900/C-examples
|
time/sleep.c
|
<gh_stars>1-10
/*
SLEEP(3) Linux Programmer's Manual SLEEP(3)
NAME top
sleep - sleep for a specified number of seconds
SYNOPSIS top
#include <unistd.h>
unsigned int sleep(unsigned int seconds);
*/
#include <unistd.h>
#include <stdio.h>
int main(){
for(int i=0;i<10;i++){
printf("%d\n", i);
sleep(1);
}
}
|
invincible1900/C-examples
|
time/nanosleep.c
|
/*
NANOSLEEP(2) Linux Programmer's Manual NANOSLEEP(2)
NAME top
nanosleep - high-resolution sleep
SYNOPSIS top
#include <time.h>
int nanosleep(const struct timespec *req, struct timespec *rem);
...
DESCRIPTION top
nanosleep() suspends the execution of the calling thread until either
at least the time specified in *req has elapsed, or ...
...
The structure timespec is used to specify intervals of time with
nanosecond precision. It is defined as follows:
struct timespec {
time_t tv_sec; // seconds
long tv_nsec; // nanoseconds
};
The value of the nanoseconds field must be in the range 0 to
999999999.
...
RETURN VALUE top
On successfully sleeping for the requested interval, nanosleep()
returns 0.
If the call is interrupted by a signal handler or
encounters an error, then it returns -1, with errno set to indicate
the error.
*/
// nanosecond是纳秒的意思 1秒 = 10^9纳秒
#include <time.h>
int main(){
struct timespec currentTime;
currentTime.tv_sec=5;
currentTime.tv_nsec=1000000000-1;
nanosleep(¤tTime, NULL);
}
/*
$ time ./nanosleep_demo
real 0m6.016s
...
*/
|
invincible1900/C-examples
|
elf/1/main.c
|
<reponame>invincible1900/C-examples
/************************************************************
* Desc: Open an elf file and read elf header ( no error check )
*
* Author: X++D
*
***********************************************************/
#include <elf.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int dump_elf_header(Elf64_Ehdr *ehdr){
printf("Magic:\t");
for(int i = 0; i<EI_NIDENT; i++){
printf("%02x ", ehdr->e_ident[i]);
}
printf("\n");
if(ehdr->e_ident[EI_CLASS] == ELFCLASS64){
printf("Class: %s\n", "ELF64");
}
if(ehdr->e_machine == EM_X86_64){
printf("Machine: %s\n", "AMD x86-64 architecture");
}
printf("Entry point address: %lu\n", ehdr->e_entry);
printf("Start of section headers: %lu\n", ehdr->e_shoff);
printf("Size of section header: %u\n", ehdr->e_shentsize);
printf("Number of section headers: %d\n", ehdr->e_shnum);
printf("Section header string table index: %u\n", ehdr->e_shstrndx);
}
int read_elf_header(char *path) {
Elf64_Ehdr ehdr;
FILE *fd = fopen(path, "rb");
fread(&ehdr, 1, sizeof(Elf64_Ehdr), fd);
dump_elf_header(&ehdr);
pclose(fd);
return 0;
}
int main(int argc, char *argv[]){
read_elf_header(argv[1]);
return 0;
}
/*************************************************************************
$ ./elf /bin/ls
Magic: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
Class: ELF64
Machine: AMD x86-64 architecture
Entry point address: 26576
Start of section headers: 140224
Size of section header: 64
Number of section headers: 30
Section header string table index: 29
$ readelf -h /bin/ls
ELF Header:
Magic: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
Class: ELF64
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: DYN (Shared object file)
Machine: Advanced Micro Devices X86-64
Version: 0x1
Entry point address: 0x67d0
Start of program headers: 64 (bytes into file)
Start of section headers: 140224 (bytes into file)
Flags: 0x0
Size of this header: 64 (bytes)
Size of program headers: 56 (bytes)
Number of program headers: 13
Size of section headers: 64 (bytes)
Number of section headers: 30
Section header string table index: 29
#define EI_NIDENT (16)
typedef struct
{
unsigned char e_ident[EI_NIDENT]; // magic number and other info
Elf64_Half e_type; // object file type
Elf64_Half e_machine; // architecture
Elf64_Word e_version; // object file version
Elf64_Addr e_entry; // entry point virtual address
Elf64_Off e_phoff; // program header table file offset
Elf64_Off e_shoff; // section header table file offset
Elf64_Word e_flags; // processor-specific flags
Elf64_Half e_ehsize; // elf header size in bytes
Elf64_Half e_phentsize; // program header table entry size
Elf64_Half e_phnum; // program header table entry count
Elf64_Half e_shentsize; // section header table entry size
Elf64_Half e_shnum; // section header table entry count
Elf64_Half e_shstrndx; // section header string table index
} Elf64_Ehdr;
#define EM_X86_64 62 // AMD x86-64 architecture
#define EM_386 3 // Intel 80386
*************************************************************************/
|
invincible1900/C-examples
|
elf/2/main.c
|
/************************************************************
* Desc: mmap an elf file and read elf header ( no error check )
*
* Author: X++D
*
***********************************************************/
#include <stdio.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <elf.h>
int dump_elf_header(Elf64_Ehdr *ehdr){
printf("Magic:\t");
for(int i = 0; i<EI_NIDENT; i++){
printf("%02x ", ehdr->e_ident[i]);
}
printf("\n");
if(ehdr->e_ident[EI_CLASS] == ELFCLASS64){
printf("Class: %s\n", "ELF64");
}
if(ehdr->e_machine == EM_X86_64){
printf("Machine: %s\n", "AMD x86-64 architecture");
}
printf("Entry point address: %lu\n", ehdr->e_entry);
printf("Start of section headers: %lu\n", ehdr->e_shoff);
printf("Size of section header: %u\n", ehdr->e_shentsize);
printf("Number of section headers: %d\n", ehdr->e_shnum);
printf("Section header string table index: %u\n", ehdr->e_shstrndx);
}
int main(int argc, char *argv[]){
FILE *file;
int fd;
size_t file_size;
struct stat stat;
void *maddr;
char *path;
if(argc < 2){
path = "/bin/ls";
}else{
path = argv[1];
}
file = fopen(path, "rb");
fd = fileno(file);
fstat(fd, &stat);
file_size = stat.st_size;
maddr = mmap(NULL, file_size, PROT_READ, MAP_FILE | MAP_PRIVATE, fd, 0);
Elf64_Ehdr *ehdr = (Elf64_Ehdr *)maddr;
dump_elf_header(ehdr);
munmap(maddr, file_size);
return 0;
}
/*************************************************************************
$ ./elf
Magic: 7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
Class: ELF64
Machine: AMD x86-64 architecture
Entry point address: 26576
Start of section headers: 140224
Size of section header: 64
Number of section headers: 30
Section header string table index: 29
*************************************************************************/
|
invincible1900/C-examples
|
shift/main.c
|
<filename>shift/main.c
#include <stdio.h>
int main(){
int x = 0xe;
int y = x << (32 - 4) >> (32 -4);
int z = x << (32 - 5) >> (32 - 5);
printf("0x%x, %d\n", x, x);
printf("0x%x, %d\n", y, y);
printf("0x%x, %d\n", z, z);
// overflow
printf("0x%lx\n", 1<<32);
// fix 1
printf("0x%lx\n", 1UL<<32);
// fix 2
printf("0x%lx\n", (long)1<<32);
// overflow
printf("oo 0x%lx\n", (1UL << 64));
int width = 64;
printf("oo2 0x%lx\n", (1UL << width));
}
/*
SAR: Shift Arithmetic Right
the SAR instruction sets or clears the most significant bit to correspond
to the sign (most significant bit) of the original value in the destination operand.
In effect, the SAR instruction fills the empty bit position’s shifted value with the sign of the unshifted value .
(gdb) disassemble main
Dump of assembler code for function main:
...
0x000055555555465c <+18>: shl eax,0x1c
0x000055555555465f <+21>: sar eax,0x1c
...
0x0000555555554668 <+30>: shl eax,0x1b
0x000055555555466b <+33>: sar eax,0x1b
...
End of assembler dump.
$ make
gcc main.c -g
./a.out
0xe, 14
0xfffffffe, -2
0xe, 14
0x0
0x100000000
0x100000000
0x0
0x1
* */
|
invincible1900/C-examples
|
misc/lib-test/static-lib/use-lib/main.c
|
#include "libwow.h"
int main(){
wow();
return 0;
}
|
invincible1900/C-examples
|
elf/4/elf.c
|
<gh_stars>1-10
/*****************************************************
*
* Desc: 插入一个 section 到 ELF 文件 (草稿代码, 方便自己抄)
*
* Author: X++D
*
*****************************************************/
#include <elf.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdbool.h>
#include <assert.h>
#define NONE "\033[m"
#define RED "\033[0;32;31m"
#define LIGHT_BLUE "\033[1;34m"
#define DARK_GRAY "\033[1;30m"
#define YELLOW "\033[1;33m"
#define x_err(fmt, ...) \
while(1) { \
printf("[D] %s:%d, ", __func__, __LINE__); \
printf(RED fmt NONE, ##__VA_ARGS__); \
break; \
}
#define x_log(fmt, ...) \
while(1) { \
printf("[D] %s:%d, ", __func__, __LINE__); \
printf(YELLOW fmt NONE, ##__VA_ARGS__); \
break; \
}
struct fix_block {
const char *desc; /* 描述当前block, 方便调试,对功能无影响 */
void *old; /* 指向当前 block 数据的指针 */
void *new; /* 指向当前 block 新数据的指针 */
size_t old_off; /* 当前 block 在原文件中的偏移 */
size_t old_size; /* 当前 block 在原文件中的大小 */
size_t new_off; /* 当前 block 在新文件中的偏移 */
size_t new_size; /* 当前 block 在新文件中的大小 */
struct fix_block *next; /* 单链表指针 */
};
/**********************************************************************************
计算每个fix_block 的 new_off 字段:
- 外层循环遍历每个待更新的 fix_block: fb_x, 顺便累计扩展的大小
- 内层循环遍历每个fix_block: fb_y
- 如果fb_y 位于 fb_x 之前,则fb_y 的大小变化要累加到 fb_x 的 new_off 中
**********************************************************************************/
size_t fixup_new_offset(struct fix_block *fb_head){
size_t added = 0;
struct fix_block *fb_x, *fb_y;
for(fb_x = fb_head; fb_x; fb_x = fb_x->next){
added += (fb_x->new_size - fb_x->old_size);
for(fb_y = fb_head; fb_y; fb_y = fb_y->next){
if(fb_x->old_off > fb_y->old_off){
if(fb_y->new_size - fb_y->old_size == 0)
continue;
x_log(YELLOW"updating fb: %s, old offset: %lu\n"NONE, fb_x->desc, fb_x->new_off);
x_log(YELLOW"compared fb: %s, old offset: %lu, size changed: %lu\n"NONE, fb_y->desc, fb_y->old_off, fb_y->new_size - fb_y->old_size);
fb_x->new_off += (fb_y->new_size - fb_y->old_size);
x_log(YELLOW"fb: %s updated, new offset: %lu\n\n"NONE, fb_x->desc, fb_x->new_off);
}
}
}
return added;
}
/**********************************************************************************
计算每个 program header 的 p_offset 和 p_filesz 字段:
- 外层循环遍历每个待更新的 program header: phdr
- 内层循环遍历每个fix_block: fb
- 如果 phdr->p_offset 位于 fb->old_off + fb->old_size 之后,则 fb 的大小变化要累加到 p_offset 中
- 如果 phdr->p_offset + phdr->p_filesz 位于 fb->old_off 之前则不需要修改
- 如果不是以上两种情况则 program header 指向的 segment 应该为 fb
**********************************************************************************/
int fixup_phdrs(Elf64_Ehdr *ehdr, struct fix_block *fb_phdr, struct fix_block *fb_head){
Elf64_Phdr *phdrs = (Elf64_Phdr *)fb_phdr->new;
Elf64_Phdr *phdr = phdrs;
for(int i =0; i < ehdr->e_phnum; i++, phdr = phdrs + i) {
for(struct fix_block *fb = fb_head; fb; fb = fb->next){
// fb 大小没变,不需要处理
if(fb->new_size - fb->old_size == 0)
continue;
// 在大小发生变化的 fb 之前,不需要处理
if(phdr->p_offset + phdr->p_filesz <= fb->old_off)
continue;
// 在大小发生变化的 fb 之后,则需要更新 offset
if( phdr->p_offset >= fb->old_off+fb->old_size ){
x_log(YELLOW"updating phdr->p_offset: %lu(%d)\n"NONE, phdr->p_offset, i);
x_log(YELLOW"compared to fb: %s, fb->old_off: %lu, size changed: %lu\n"NONE,
fb->desc, fb->old_off, fb->new_size - fb->old_size);
phdr->p_offset += (fb->new_size - fb->old_size);
x_log(YELLOW"updated, phdr->p_offset: %lu\n\n"NONE, phdr->p_offset);
}
// 与大小发生变化的 fb 存在交集
else{
// assert(phdr->p_offset == fb->old_off);
// assert(phdr->p_filesz <= fb->new_size);
x_log(YELLOW"updating phdr->p_filesz: %lu (p_offset: %lu, %d)\n"NONE, phdr->p_filesz, phdr->p_offset, i);
x_log(YELLOW"compared to fb: %s, fb->old_off: %lu, size changed: %lu\n"NONE,
fb->desc, fb->old_off, fb->new_size - fb->old_size);
phdr->p_filesz += (fb->new_size - fb->old_size);
x_log(YELLOW"updated, phdr->p_filesz: %lu\n\n"NONE, phdr->p_filesz);
}
}
}
return 0;
}
/**********************************************************************************
计算每个 section header 的 sh_offset 和 sh_size 字段:
- 外层循环遍历每个待更新的 section header: shdr
- 内层循环遍历每个fix_block: fb
- 如果 shdr->sh_offset 位于 fb->old_off + fb->old_size 之后,则 fb 的大小变化要累加到 sh_offset 中
- 如果 shdr->sh_offset + shdr->sh_size 位于 fb->old_off 之前则不需要修改
- 如果不是以上两种情况则 section header 指向的 section 应该为 fb, 比如 strtble
**********************************************************************************/
int fixup_shdrs(Elf64_Ehdr *ehdr, struct fix_block *fb_shdr, struct fix_block *fb_head, char *strtbl){
Elf64_Shdr *shdrs = (Elf64_Shdr *)fb_shdr->new;
Elf64_Shdr *shdr = shdrs;
// 遍历每个待更新的 section header: shdr,注意跳过最后一个,也就是新添加的section
for(int i =0; i < ehdr->e_shnum - 1; i++, shdr = shdrs + i) {
size_t s_start, s_end;
// 计算当前 section header 对应数据区的 range
s_start = shdr->sh_offset;
s_end = shdr->sh_offset + shdr->sh_size;
// 遍历每个fix_block: fb
for(struct fix_block *fb = fb_head; fb; fb = fb->next){
// fb 大小没变,不需要处理
if((fb->new_size - fb->old_size == 0)){
continue;
}
// 在大小发生变化的 fb 之前,不需要处理
if(s_end <= fb->old_off){
#if 0
x_log(DARK_GRAY"shdr: %s sh_offset: %lu, s_start: %lu, s_end %lu\n"NONE, strtbl + shdr->sh_name, shdr->sh_offset, s_start, s_end);
x_log(DARK_GRAY"compared to fb: %s, data start: %lu, data end: %lu, size changed: %lu\n"NONE,
fb->desc, fb->old_off, fb->old_off + fb->old_size, fb->new_size - fb->old_size);
x_log(DARK_GRAY"shdr: %s sh_offset not changed\n\n"NONE, strtbl + shdr->sh_name)
#endif
continue;
}
// 在大小发生变化的 fb 之后,则需要更新 offset
if( s_start >= fb->old_off+fb->old_size ){
x_log(YELLOW"updating shdr: %s sh_offset: %lu, s_start: %lu, s_end %lu\n"NONE, strtbl + shdr->sh_name, shdr->sh_offset, s_start, s_end);
x_log(YELLOW"compared to fb: %s, old data start: %lu, old data end: %lu, size changed: %lu\n"NONE,
fb->desc, fb->old_off, fb->old_off + fb->old_size, fb->new_size - fb->old_size);
shdr->sh_offset += (fb->new_size - fb->old_size);
x_log(YELLOW"shdr: %s sh_offset updated: %lu\n\n"NONE, strtbl + shdr->sh_name, shdr->sh_offset);
}
// 与大小发生变化的 fb 存在交集
else{
// 应该是包含关系: data range 包含 fb
// assert(s_end >= fb->old_off + fb->old_size);
x_log(YELLOW"updating shdr: %s sh_size: %lu, s_start: %lu, s_end %lu\n"NONE,
strtbl + shdr->sh_name, shdr->sh_size, s_start, s_end);
x_log(YELLOW"compared to fb: %s, data start: %lu, data end: %lu, size changed: %lu\n"NONE,
fb->desc, fb->old_off, fb->old_off + fb->old_size, fb->new_size - fb->old_size);
if(strcmp(".bss", strtbl + shdr->sh_name) != 0){
shdr->sh_size += (fb->new_size - fb->old_size);
}else{
// I don't know how to handle this.
// It's strange that .bss offset + size is larger than the file size
// Adding .bss size may cause crash after objcopy --remove-section
}
x_log(YELLOW"shdr: %s sh_size updated: %lu\n\n"NONE, strtbl + shdr->sh_name, shdr->sh_size);
}
}
}
return 0;
}
/********************************************************************
* dump_fix_block: 打印一个初始化过的 fix_block, 用于 Debug
*******************************************************************/
void dump_fix_block(struct fix_block *fb){
printf("\nfb: %s\n", fb->desc);
printf("\tfb->old: %p\n", fb->old);
printf("\tfb->old_off: %lu\n", fb->old_off);
printf("\tfb->old_size: %lu\n", fb->old_size);
printf("\tfb->new: %p\n", fb->new);
printf("\tfb->new_off: %lu\n", fb->new_off);
printf("\tfb->new_size: %lu\n", fb->new_size);
if(fb->next){
printf("\tfb->next: %p, %s\n", fb->next, fb->next->desc);
}else{
printf("\tfb->next: NULL\n");
}
if(fb->new_size - fb->old_size != 0){
printf(YELLOW"\tsize changed: %lu\n"NONE, fb->new_size - fb->old_size);
}
if(fb->new_off - fb->old_off != 0){
printf(YELLOW"\toffset changed: %lu\n"NONE, fb->new_off - fb->old_off);
}
printf("\n");
}
/********************************************************************
* dump_fix_blocks: 打印 fix_block 链表, 用于 Debug
*******************************************************************/
void dump_fix_blocks(struct fix_block *fb_head){
for(struct fix_block *fb = fb_head; fb; fb = fb->next){
dump_fix_block(fb);
}
}
int mmap_file(char *path, void **maddr, size_t *file_size, int *fd_o){
int fd;
struct stat stat;
size_t f_sz;
void *maddr_l;
fd = open(path, O_RDONLY);
if(fd < 0){
x_err("open failed\n");
return -1;
}
fstat(fd, &stat);
f_sz = stat.st_size;
maddr_l = mmap(NULL, f_sz, PROT_READ, MAP_FILE | MAP_PRIVATE, fd, 0);
if(!maddr_l){
x_err("mmap failed\n");
return -1;
}
*maddr = maddr_l;
*file_size = f_sz;
*fd_o = fd;
return 0;
}
void unmap_file(int fd, void *maddr, size_t file_size){
munmap(maddr, file_size);
close(fd);
}
int elf_sanity_check(Elf64_Ehdr *elf_hdr){
if (memcmp(elf_hdr->e_ident, ELFMAG, SELFMAG) != 0) {
x_err("elf_sanity_check error\n");
return -1;
}
if (!elf_hdr->e_shoff) {
x_err("elf_sanity_check error\n");
return -1;
}
if (elf_hdr->e_shentsize != sizeof(Elf64_Shdr)) {
x_err("elf_sanity_check error\n");
return -1;
}
if (elf_hdr->e_shnum > 65536U / sizeof(Elf64_Shdr)) {
x_err("elf_sanity_check error\n");
return -1;
}
if(elf_hdr->e_ident[EI_CLASS] != ELFCLASS64){
x_err("elf_sanity_check error\n");
return -1;
}
return 0;
}
int check_section_exists(Elf64_Ehdr *ehdr, Elf64_Shdr *sechdrs, char *secstrs, char *s_name){
Elf64_Shdr *s, *se;
for (s = sechdrs, se = sechdrs + ehdr->e_shnum; s < se; s++) {
if (strcmp(s_name, secstrs + s->sh_name) == 0){
return -1;
}
}
return 0;
}
int insert_section(char *file_path, char *new_sec_name, void *new_sec, size_t new_sec_size){
void *maddr;
int fd;
size_t file_size;
/* 0. mmap 目标文件 */
printf(LIGHT_BLUE"************************************************\n"NONE);
printf(LIGHT_BLUE"0. mmap 目标文件\n"NONE);
printf(LIGHT_BLUE"************************************************\n"NONE);
if(mmap_file(file_path, &maddr, &file_size, &fd) < 0){
x_err("mmap_file error\n");
return -1;
}
x_log("maddr: %p, file_size: %lu\n", maddr, file_size);
/* 0. 读取目标文件信息,并进行检查 */
Elf64_Ehdr *ehdr = (Elf64_Ehdr *) maddr;
if(elf_sanity_check(ehdr) < 0){
unmap_file(fd, maddr, file_size);
return -1;
}
Elf64_Shdr *shdrs = (Elf64_Shdr *)( maddr + ehdr->e_shoff);
Elf64_Phdr *phdrs = (Elf64_Phdr *)( maddr + ehdr->e_phoff);
char *strtbl = maddr + (shdrs + ehdr->e_shstrndx)->sh_offset;
size_t strtbl_size = (shdrs + ehdr->e_shstrndx)->sh_size;
if(check_section_exists(ehdr, shdrs, strtbl, new_sec_name) < 0){
x_err("section %s exists, remove it and try again\n", new_sec_name);
x_err("objcopy --remove-section %s %s\n", new_sec_name, file_path);
unmap_file(fd, maddr, file_size);
return -1;
}
struct fix_block fb_ehdr;
struct fix_block fb_shdr;
struct fix_block fb_phdr;
struct fix_block fb_strtbl;
struct fix_block fb_sig;
struct fix_block *fb = NULL, *fb_head = NULL;
Elf64_Ehdr *new_ehdr;
size_t new_file_size;
memset(&fb_ehdr, 0, sizeof(struct fix_block));
memset(&fb_shdr, 0, sizeof(struct fix_block));
memset(&fb_phdr, 0, sizeof(struct fix_block));
memset(&fb_strtbl, 0, sizeof(struct fix_block));
memset(&fb_sig, 0, sizeof(struct fix_block));
/* 1. 初始化将要发生变化的几个 fix_block */
printf(LIGHT_BLUE"************************************************\n"NONE);
printf(LIGHT_BLUE"1. 初始化修改所需的信息\n"NONE);
printf(LIGHT_BLUE"************************************************\n"NONE);
fb = &fb_strtbl;
fb->desc = "String table section";
fb->old = strtbl;
fb->old_off = (shdrs + ehdr->e_shstrndx)->sh_offset;
fb->old_size = strtbl_size;
fb->new_size = strtbl_size + strlen(new_sec_name) + 1;
fb->new = (char *)malloc(fb->new_size);
memset(fb->new, 0, fb->new_size);
memcpy(fb->new, fb->old, fb->old_size);
memcpy(fb->new + fb->old_size, new_sec_name, strlen(new_sec_name));
fb->new_off = fb->old_off;
fb->next = fb_head;
fb_head = fb;
/************************************************/
fb = &fb_sig;
fb->desc = "New section";
fb->old = NULL;
fb->old_size = 0;
fb->old_off = file_size;
fb->new = new_sec;
fb->new_size = new_sec_size;
fb->new_off = fb->old_off;
fb->next = fb_head;
fb_head = fb;
/************************************************/
fb = &fb_shdr;
fb->desc = "Section Headers";
fb->old = (char *)shdrs;
fb->old_off = ehdr->e_shoff;
fb->old_size = ehdr->e_shentsize * ehdr->e_shnum;
fb->new_size = fb->old_size + ehdr->e_shentsize;
// 填充新的section header
fb->new = malloc(fb->new_size);
memset(fb->new, 0, fb->new_size);
memcpy(fb->new, fb->old, fb->old_size);
Elf64_Shdr *shdr_new = (Elf64_Shdr *)(fb->new + fb->old_size);
shdr_new->sh_name = strtbl_size;
shdr_new->sh_type = 0x80aabbcc;
shdr_new->sh_flags = SHF_OS_NONCONFORMING;
shdr_new->sh_offset = fb_sig.old_off;
shdr_new->sh_size = new_sec_size;
shdr_new->sh_addralign = 1;
fb->new_off = fb->old_off;
fb->next = fb_head;
fb_head = fb;
/************************************************/
fb = &fb_phdr;
fb->desc = "Program Headers";
fb->old = (char *)phdrs;
fb->old_size = ehdr->e_phentsize * ehdr->e_phnum;
fb->old_off = ehdr->e_phoff;
fb->new_size = fb->old_size;
fb->new = malloc(fb->new_size);
memcpy(fb->new, fb->old, fb->old_size);
fb->new_off = fb->old_off;
fb->next = fb_head;
fb_head = fb;
// dump_fix_block(fb);
/************************************************/
fb = &fb_ehdr;
fb->desc = "ELF File Header";
fb->old = (char *)ehdr;
fb->old_size = ehdr->e_ehsize;
fb->old_off = 0;
fb->new_size = fb->old_size;
fb->new = malloc(fb->new_size);
memcpy(fb->new, fb->old, fb->old_size);
new_ehdr = (Elf64_Ehdr *)fb->new;
// new_ehdr->e_entry 不需要改
// new_ehdr->e_phoff 需要修改
// new_ehdr->e_shoff 需要修改
new_ehdr->e_shnum = ehdr->e_shnum + 1;
fb->new_off = fb->old_off;
fb->next = fb_head;
fb_head = fb;
dump_fix_blocks(fb_head);
// 2. 计算各个 fix_block 的 new_off 和 新的文件大小
printf(LIGHT_BLUE"************************************************\n"NONE);
printf(LIGHT_BLUE"2. 计算各个 fix_block 的 new_off 和 新的文件大小 \n"NONE);
printf(LIGHT_BLUE"************************************************\n"NONE);
new_file_size = fixup_new_offset(fb_head) + file_size;
x_log(YELLOW"new file size: %lu, old file size: %lu\n"NONE, new_file_size, file_size);
dump_fix_blocks(fb_head);
// 3. 修复新的 section headers 中 signature header 的偏移
printf(LIGHT_BLUE"************************************************\n"NONE);
printf(LIGHT_BLUE"3. 修复新的 section headers 中 signature header 的偏移\n"NONE);
printf(LIGHT_BLUE"************************************************\n"NONE);
x_log(YELLOW"shdr_new->sh_offset before: %lu\n"NONE, shdr_new->sh_offset);
shdr_new->sh_offset = fb_sig.new_off;
x_log(YELLOW"shdr_new->sh_offset after : %lu\n"NONE, shdr_new->sh_offset);
// 4. 修复 ELF Header 中的偏移
printf(LIGHT_BLUE"************************************************\n"NONE);
printf(LIGHT_BLUE"4. 修复 ELF Header 中的偏移\n"NONE);
printf(LIGHT_BLUE"************************************************\n"NONE);
x_log(YELLOW"e_phoff before: %lu, e_shoff before: %lu\n"NONE, new_ehdr->e_phoff, new_ehdr->e_shoff);
new_ehdr->e_phoff = fb_phdr.new_off;
new_ehdr->e_shoff = fb_shdr.new_off;
x_log(YELLOW"e_phoff after : %lu, e_shoff after : %lu\n"NONE, new_ehdr->e_phoff, new_ehdr->e_shoff);
// 5. 修复 program headers 中每个 header 的偏移和大小
printf(LIGHT_BLUE"************************************************\n"NONE);
printf(LIGHT_BLUE"5. 修复 program headers 中每个 header 的偏移和大小\n"NONE);
printf(LIGHT_BLUE"************************************************\n"NONE);
fixup_phdrs(new_ehdr, &fb_phdr, fb_head);
// 6. 修复 section headers 中每个 header 的偏移和大小
printf(LIGHT_BLUE"************************************************\n"NONE);
printf(LIGHT_BLUE"6. 修复 section headers 中每个 header 的偏移和大小\n"NONE);
printf(LIGHT_BLUE"************************************************\n"NONE);
fixup_shdrs(new_ehdr, &fb_shdr, fb_head, fb_strtbl.new);
// 7. 开始 rewrite 整个文件
printf(LIGHT_BLUE"************************************************\n"NONE);
printf(LIGHT_BLUE"7. 开始 rewrite 整个文件\n"NONE);
printf(LIGHT_BLUE"************************************************\n"NONE);
char temp_path[20];
strcpy(temp_path, "my.XXXXXX");
int fd_new = mkstemp(temp_path);
size_t f_pos_new = 0, f_pos_old = 0;
// f_pos_new 指向写入的新文件当前位置,当它位于新文件末尾时循环结束
while(f_pos_new < new_file_size){
size_t write_size = 0, ret = 0;
struct fix_block *fb_next = NULL;
// 先找到未写入的 new_off 最小的 fix_block,保存到 fb_next
for(struct fix_block *fb = fb_head; fb; fb = fb->next){
// 跳过已经写入的 block
if(fb->new_off < f_pos_new){
// x_log("Skip fb: %s, off: %lu, %lu\n", fb->desc, fb->new_off, f_pos_new);
continue;
}
// 找到第一个待写入的 block
if(fb_next == NULL){
fb_next = fb;
// x_log("fb_next fb: %s, off: %lu, %lu\n", fb->desc, fb->new_off, f_pos_new);
continue;
}
// 替换为更小的 block
if(fb->new_off < fb_next->new_off){
fb_next = fb;
// x_log("fb_next update fb: %s, off: %lu, %lu\n", fb->desc, fb->new_off, f_pos_new);
}
}
#if 0
if(fb_next){
dump_fix_block(fb_next);
}
#endif
// 如果有待写入的 fix_block,且 new_off 与当前 f_pos_new 一致,则写入 fix_block->new 的内容
if(fb_next && fb_next->new_off == f_pos_new){
x_log(YELLOW"write fb: %s content, new file write positon: %lu, old file position: %lu\n"NONE, fb_next->desc, f_pos_new, f_pos_old);
write_size = fb_next->new_size;
x_log(YELLOW"content size: %lu\n"NONE, write_size);
ret = write(fd_new, fb_next->new, write_size);
x_log(YELLOW"wrote size: %lu\n"NONE, ret);
if(ret != write_size){
f_pos_new = -1;
x_log(RED"write error\n"NONE);
break;
}else{
f_pos_new += write_size;
f_pos_old += fb_next->old_size;
}
x_log(YELLOW"upate file position: %lu(new), %lu(old)\n\n"NONE, f_pos_new, f_pos_old);
}
// 如果没有待写入的 fix_block,或者 new_off 与当前 f_pos_new 不一致,则写入原文件的内容
else{
x_log(YELLOW"write gap content, new file write positon: %lu, old file position: %lu\n"NONE, f_pos_new, f_pos_old);
write_size = fb_next->new_off - f_pos_new;
assert(write_size == fb_next->old_off - f_pos_old);
x_log(YELLOW"content size: %lu\n"NONE, write_size);
ret = write(fd_new, maddr + f_pos_old, write_size);
x_log(YELLOW"wrote size: %lu\n"NONE, ret);
if(ret != write_size){
f_pos_new = -1;
x_log(RED"write error\n"NONE);
break;
}else{
f_pos_new += write_size;
f_pos_old += write_size;
}
x_log("upate file position: %lu(new), %lu(old)\n\n", f_pos_new, f_pos_old);
}
}
close(fd_new);
return 0;
}
int main(int argc, char *argv[]){
char *path;
if(argc < 2){
path = "./ls";
}else{
path = argv[1];
}
size_t new_sec_size = 1024;
void *new_sec = malloc(new_sec_size);
memset(new_sec, 'x', new_sec_size);
char *new_sec_name = ".X++D";
insert_section(path, new_sec_name, new_sec, new_sec_size);
}
|
invincible1900/C-examples
|
time/gettimeofday.c
|
<reponame>invincible1900/C-examples
/*
clock_gettime
http://man7.org/linux/man-pages/man2/clock_getres.2.html
gettimeofday
http://man7.org/linux/man-pages/man2/gettimeofday.2.html
struct timeval {
time_t tv_sec; // seconds
suseconds_t tv_usec; // microseconds
};
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main(){
struct timeval start;
struct timeval end;
long time_use = 0;
gettimeofday(&start,NULL);
for(int i=0;i<1000000000;i++){
//...
}
gettimeofday(&end,NULL);
time_use= end.tv_sec - start.tv_sec;
printf("Done after %lds\n", time_use);
}
|
invincible1900/C-examples
|
memory/mmu.c
|
<reponame>invincible1900/C-examples<filename>memory/mmu.c
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#include <fcntl.h>
#include <assert.h>
#include <inttypes.h>
#include <sys/types.h>
#include <unistd.h>
#define PAGE_SHIFT 12
#define PAGE_SIZE (1 << PAGE_SHIFT)
#define PFN_PRESENT (1ull << 63)
#define PFN_PFN ((1ull << 55) - 1)
int fd;
uint32_t page_offset(uint32_t addr)
{
return addr & ((1 << PAGE_SHIFT) - 1);
}
uint64_t gva_to_gfn(void *addr)
{
uint64_t pme, gfn;
size_t offset;
printf("[D] addr: %p\n", (void *)addr);
offset = ((uintptr_t)addr / PAGE_SIZE) * 8;
printf("[D] offset: %lu\n", offset);
lseek(fd, offset, SEEK_SET);
read(fd, &pme, 8);
printf("[D] pme: %p\n", (void *)pme);
if (!(pme & PFN_PRESENT))
return -1;
gfn = pme & PFN_PFN;
printf("[D] gfn: %p\n", (void *)gfn);
return gfn;
}
uint64_t gva_to_gpa(void *addr)
{
uint64_t gfn = gva_to_gfn(addr);
assert(gfn != -1);
return (gfn << PAGE_SHIFT) | page_offset((uint64_t)addr);
}
int main()
{
uint8_t *ptr;
uint64_t ptr_mem;
printf("[D] pid: %u\n", getpid());
fd = open("/proc/self/pagemap", O_RDONLY);
if (fd < 0) {
perror("open");
exit(1);
}
ptr = malloc(256);
strcpy(ptr, "Where am I?");
printf("%s\n", ptr);
ptr_mem = gva_to_gpa(ptr);
printf("Your physical address is at 0x%"PRIx64"\n", ptr_mem);
getchar();
return 0;
}
|
invincible1900/C-examples
|
memory/read_phy_mm.c
|
<gh_stars>1-10
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if (argc < 3) {
printf("Usage: %s <phys_addr> <offset>\n", argv[0]);
return 0;
}
off_t offset = strtoul(argv[1], NULL, 0);
size_t len = strtoul(argv[2], NULL, 0);
// Truncate offset to a multiple of the page size, or mmap will fail.
size_t pagesize = sysconf(_SC_PAGE_SIZE);
off_t page_base = (offset / pagesize) * pagesize;
off_t page_offset = offset - page_base;
int fd = open("/dev/mem", O_SYNC);
unsigned char *mem = mmap(NULL, page_offset + len, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, page_base);
if (mem == MAP_FAILED) {
perror("Can't map memory");
return -1;
}
size_t i;
for (i = 0; i < len; ++i)
printf("%02x ", (int)mem[page_offset + i]);
return 0;
}
|
invincible1900/C-examples
|
hexdump/2/main.c
|
/****************************************************************
*
* Desc: hexdump ,附带 ascii 码
*
* Author: not me
*
**************************************************************/
#include <stdio.h>
#include <string.h>
void hexdump(const void* data, size_t size) {
char ascii[17];
size_t i, j;
ascii[16] = '\0';
for (i = 0; i < size; ++i) {
printf("%02X ", ((unsigned char*)data)[i]);
if (((unsigned char*)data)[i] >= ' ' && ((unsigned char*)data)[i] <= '~') {
ascii[i % 16] = ((unsigned char*)data)[i];
} else {
ascii[i % 16] = '.';
}
if ((i+1) % 8 == 0 || i+1 == size) {
printf(" ");
if ((i+1) % 16 == 0) {
printf("| %s \n", ascii);
} else if (i+1 == size) {
ascii[(i+1) % 16] = '\0';
if ((i+1) % 16 <= 8) {
printf(" ");
}
for (j = (i+1) % 16; j < 16; ++j) {
printf(" ");
}
printf("| %s \n", ascii);
}
}
}
}
int main(){
char buf[40];
memset(buf, 0, sizeof(buf));
*(unsigned long *)buf = 0x6f6c6c6548;
hexdump(buf, sizeof(buf));
}
/*****************************************************************************
$ make
gcc main.c
$ ./a.out
48 65 6C 6C 6F 00 00 00 00 00 00 00 00 00 00 00 | Hello...........
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................
00 00 00 00 00 00 00 00 | ........
*****************************************************************************/
|
invincible1900/C-examples
|
misc/err-handler/main.c
|
// https://www.gnu.org/software/libc/manual/html_node/Error-Codes.html
#include <stdio.h>
#include <errno.h>
#include <string.h>
/*********************************
$ ./a.out
[-] main:43
[-] main:44, Invalid argument
$ man errno
$ man strerror
*********************************/
#define SAFE_1(expr) \
while(1) { \
if(expr < 0){ \
printf("[-] %s:%d\n", __func__, __LINE__); \
} \
break; \
}
#define SAFE_2(expr) \
while(1) { \
ret = expr; \
if(ret < 0){ \
printf("[-] %s:%d, %s\n", __func__, __LINE__, strerror(-ret)); \
} \
break; \
}
int foo(){
return -1;
}
int bar(){
return -EINVAL;
}
void print_err(){
char buf[10];
for(int i = EPERM; i<= EHWPOISON; i++){
sprintf(buf, "[%d]", i);
errno = i;
perror(buf);
}
}
int main(){
int ret = 0;
print_err();
SAFE_1(foo());
SAFE_2(bar());
}
|
invincible1900/C-examples
|
portio/main.c
|
<reponame>invincible1900/C-examples<filename>portio/main.c
// man lspci
// man iopl
#include <sys/io.h>
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#define CONFIG_ADDR 0xCF8
#define CONFIG_DATA 0xCFC
#define VENDOR_ID 0x8086
#define EHCI_PRODUCT_ID 0x293A
#define PCI_BASE_ADDR 0x80000000L
#define PCI_MAX_BUS 255
#define PCI_MAX_DEV 31
#define PCI_MAX_FUN 7
#define HEADER_TYPE 0x0c
#define BAR_0 0x10
void do_lspci(int bus, int dev, int fun){
char tmp_cmd[100];
memset(tmp_cmd, 0, sizeof(tmp_cmd));
sprintf(tmp_cmd, "lspci | grep %02d:%02d.%x", bus, dev, fun);
system(tmp_cmd);
}
int get_config(void)
{
int bus, dev, fun, addr, data;
for (bus = 0; bus <= PCI_MAX_BUS; bus++)
{
for (dev = 0; dev <= PCI_MAX_DEV; dev++)
{
for (fun = 0; fun <= PCI_MAX_FUN; fun++)
{
addr = PCI_BASE_ADDR | (bus << 16) | (dev << 11) | (fun << 8);
outl(addr, CONFIG_ADDR);
data = inl(CONFIG_DATA);
if((data & 0xffff) == 0xffff )
continue;
printf("addr: %x(bus: %x, dev: %x, func: %x), VENDOR_ID: %x, DEVICE_ID: %x\n",
addr, bus, dev, fun, data & 0xffff, data >> 16);
do_lspci(bus, dev, fun);
outl(addr + HEADER_TYPE, CONFIG_ADDR);
data = inl(CONFIG_DATA);
printf("%x\n", data);
data = (data >> 16) & 0xff;
if(data == 0x01){
printf("PCI-to-PCI bridge\n");
}else{
printf("PCI device\n");
}
for(int i = 0; i < 6; i++){
outl(addr + BAR_0 + i*4, CONFIG_ADDR);
data = inl(CONFIG_DATA);
if(data & 0x1){
printf("BAR_%d: %x(ioport), base addr: %x\n",
i, data, data & 0xfffffffc);
}else{
printf("BAR_%d: %x(iomem), base addr: %x\n",
i, data, data & 0xfffffff0);
}
}
printf("\n");
}
}
}
return -1;
}
int main(){
iopl(3);
get_config();
}
|
invincible1900/C-examples
|
file/access.c
|
#include <unistd.h>
#include <stdio.h>
/***************************
access
0-检查文件是否存在
1-检查文件是否可运行
2-检查文件是否可写访问
4-检查文件是否可读访问
6-检查文件是否可读/写访问
*****************************/
int file_exists(char *filename)
{
return (access(filename, 0) == 0);
}
int main(){
if(file_exists("Makefile")){
printf("Good\n");
}
return 0;
}
|
invincible1900/C-examples
|
thread/1/main.c
|
<filename>thread/1/main.c
// https://www.educative.io/edpresso/how-to-create-a-simple-thread-in-c
/*
man pthread_create
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
The new thread terminates in one of the following ways:
* It calls pthread_exit(3), specifying an exit status value that is available to another thread in the same
process that calls pthread_join(3).
* It returns from start_routine(). This is equivalent to calling pthread_exit(3) with the value supplied in
the return statement.
* It is canceled (see pthread_cancel(3)).
* Any of the threads in the process calls exit(3), or the main thread performs a return from main(). This
causes the termination of all threads in the process.
man pthread_exit
#include <pthread.h>
void pthread_exit(void *retval);
*/
#include <stdio.h>
#include <string.h>
#include <pthread.h>
// Global variable:
int data = 0xaabb;
int ret = 0;
void* reader(void* p){
while(data < 0xbb00){
printf("[D] reader[%d]: %x\n", *(int *)p, data);
}
ret = *(int *)p;
pthread_exit(&ret);
}
void* writer(void* p){
while(data < 0xbb00){
data += 1;
printf("[D] writer: %x\n", data);
}
ret = 100;
pthread_exit(&ret);
}
int main(void){
pthread_t id[3];
int num[2] = { 0, 1 };
int * _ret;
pthread_create(&id[0], NULL, writer, NULL);
pthread_create(&id[1], NULL, reader, &num[0]);
pthread_create(&id[2], NULL, reader, &num[1]);
pthread_join(id[0], (void**)&_ret);
printf("[D] main: %p, %p, %i\n", _ret, &ret, *_ret);
pthread_join(id[1], (void**)&_ret);
printf("[D] main: %p, %p, %i\n", _ret, &ret, *_ret);
pthread_join(id[2], (void**)&_ret);
printf("[D] main: %p, %p, %i\n", _ret, &ret, *_ret);
}
|
invincible1900/C-examples
|
misc/mkstemp/main.c
|
<reponame>invincible1900/C-examples
/*****************************************************************************************
* Desc: mkstemp 创建临时文件示例
*
* Author: X++D
*
*****************************************************************************************/
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
int main(){
int fd;
char temp_path[24];
strcpy(temp_path, "my.XXXXXX");
fd = mkstemp(temp_path);
write(fd, "Hello\n", strlen("Hello\n")+1);
close(fd);
}
/*****************************************************************************************
OUTPUT:
$ make
$ ls
a.out main.c Makefile
$ ./a.out
$ ls
a.out main.c Makefile my.enMQ45
$ cat my.enMQ45
Hello
*****************************************************************************************/
/*****************************************************************************************
ATTENTION:
int mkstemp(char *template);
The last six characters of template must be "XXXXXX" and these are replaced with
a string that makes the filename unique.
Since it will be modified, template must not be a string constant, but should be
declared as a character array.
*****************************************************************************************/
|
invincible1900/C-examples
|
setjmp/main.c
|
<reponame>invincible1900/C-examples
#include <setjmp.h>
#include <stdio.h>
jmp_buf env;
void A(){
printf("Now A\n");
longjmp(env,1); //这里跳回到if中继续执行
}
void B(){
printf("Now B\n");
}
int main()
{
if (!setjmp(env)) //setjmp初次返回0,第二次回来返回的就是1
A();
else
B();
return 1;
}
/************
>> 执行结果:
Now A
Now B
************/
|
invincible1900/C-examples
|
elf/3/main.c
|
/************************************************************
* Desc: mmap an elf file and read elf section headers ( no error check )
*
* Author: X++D
*
***********************************************************/
#include <elf.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
void read_elf_section_headers(Elf64_Ehdr *ehdr){
Elf64_Shdr *sechdrs;
Elf64_Shdr *s, *se;
char *secstrs;
size_t sh_size;
loff_t sh_off;
int i;
sh_size = ehdr->e_shnum * sizeof(Elf64_Shdr);
sh_off = ehdr->e_shoff;
sechdrs = (Elf64_Shdr *)((char *)ehdr + sh_off);
secstrs = (char *)ehdr + sechdrs[ehdr->e_shstrndx].sh_offset;
for (i = 0, s = sechdrs, se = sechdrs + ehdr->e_shnum; s < se; s++, i++) {
printf("********************************************\n");
printf("Section name: %s [%d]\n", secstrs + s->sh_name, i);
printf("section offset: %lu\n", s->sh_offset);
printf("section size: %lu\n", s->sh_size);
printf("********************************************\n");
}
}
int main(int argc, char *argv[]){
int fd;
size_t file_size;
struct stat stat;
void *maddr;
char *path;
if(argc < 2){
path = "/bin/ls";
}else{
path = argv[1];
}
fd = open(path, O_RDONLY);
fstat(fd, &stat);
file_size = stat.st_size;
maddr = mmap(NULL, file_size, PROT_READ, MAP_FILE | MAP_PRIVATE, fd, 0);
read_elf_section_headers((Elf64_Ehdr *)maddr);
munmap(maddr, file_size);
return 0;
}
/*************************************************************************
$ ./elf
...
********************************************
Section name: .text [16]
section offset: 19872
section size: 75730
********************************************
...
********************************************
Section name: .data [26]
section offset: 139264
section size: 616
********************************************
********************************************
Section name: .bss [27]
section offset: 139880
section size: 4824
********************************************
...
********************************************
Section name: .shstrtab [29]
section offset: 139932
section size: 285
********************************************
$ readelf -S /bin/ls
Section Headers:
[Nr] Name Type Address Offset
Size EntSize Flags Link Info Align
...
[16] .text PROGBITS 0000000000004da0 00004da0
00000000000127d2 0000000000000000 AX 0 0 16
...
[26] .data PROGBITS 0000000000023000 00022000
0000000000000268 0000000000000000 WA 0 0 32
[27] .bss NOBITS 0000000000023280 00022268
00000000000012d8 0000000000000000 WA 0 0 32
...
[29] .shstrtab STRTAB 0000000000000000 0002229c
000000000000011d 0000000000000000 0 0 1
*************************************************************************/
|
invincible1900/C-examples
|
sign/main.c
|
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
long sign_extend(long data, int width){
int shift = sizeof(long) * 8 - width;
return data << shift >> shift;
}
long sign_extend_safe(long data, int width){
if(width > 64 || width < 0){
exit(-1);
}
if(width == 64){
return data;
}
if((data >> (width-1)) & 0x1){
// negative
return data | ~((1UL << width) - 1);
}else{
// positive
return data & ((1UL << width) - 1);
}
}
int test_sign_extend(){
printf("0x%lx\n", sign_extend(0x8, 4));
printf("0x%lx\n", sign_extend(0x8, 5));
printf("0x%lx\n", sign_extend_safe(0x8, 4));
printf("0x%lx\n", sign_extend_safe(0x8, 5));
for(int i = 0; i<64; i++){
printf("0x%lx, ", sign_extend(0x1UL << i, i + 1));
printf("0x%lx\n", sign_extend_safe(0x1UL << i, i + 1));
}
}
int test_sub(){
long base = 0xffff000000000010;
long off = 0x10;
long unsigned_off = 0xfffffffffffffff0;
printf("off: %lx\n", off);
printf("off: %lx\n", -off);
printf("unsigned off: %lx\n", unsigned_off);
printf("base - off: %lx\n", base - off);
printf("base + unsigned off: %lx\n", base + unsigned_off);
printf("base + sign_extend(0x10): %lx\n", base + sign_extend(0x10, 5));
}
int main(){
test_sign_extend();
test_sub();
}
|
invincible1900/C-examples
|
bugs/main.c
|
// 移位运算潜在溢出的bug
#include <stdio.h>
#define MASK_64 1<<63
#define MASK_64_OK 1lu<<63
//#define MASK_32 1<<32
//#define MASK_32_OK 1<<32
int func1(){
long ff = 0x8000000000000000;
if(ff & MASK_64){
printf("True\n");
}else{
printf("False\n");
}
}
int func2(){
long ff = 0x8000000000000000;
if(ff & MASK_64_OK){
printf("True\n");
}else{
printf("False\n");
}
}
int main(){
func1();
func2();
}
|
invincible1900/C-examples
|
misc/lib-test/dynamic-lib/create-lib/libwow.h
|
<filename>misc/lib-test/dynamic-lib/create-lib/libwow.h
#ifndef _LIB_WOW_H
#define _LIB_WOW_H
void wow();
#endif
|
invincible1900/C-examples
|
hexdump/1/main.c
|
#include <stdio.h>
#include <stdint.h>
#include <string.h>
void hexdump(char *buf, int len){
int i;
for(i = 0; i < len; i++){
printf("%02x ", buf[i]);
if( (i+1) % 8 == 0){
printf("\t");
}
if( (i+1) % 16 == 0){
printf("\n");
}
}
}
int main()
{
char buf[100];
memset(buf, 'a', 100);
hexdump(buf, 100);
return 0;
}
/*
output:
61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61
61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61
61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61
61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61
61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61
61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61
61 61 61 61
* */
|
invincible1900/C-examples
|
thread/2/main.c
|
<filename>thread/2/main.c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
//线程函数
void *test(void *ptr)
{
int i;
for(i=0;i<8;i++)
{
printf("the pthread running ,count: %d\n",i);
sleep(1);
}
}
int main(void)
{
pthread_t pId;
int i,ret;
//创建子线程,线程id为pId
ret = pthread_create(&pId,NULL,test,NULL);
if(ret != 0)
{
printf("create pthread error!\n");
exit(1);
}
for(i=0;i < 5;i++)
{
printf("main thread running ,count : %d\n",i);
sleep(1);
}
printf("main thread will exit when pthread is over\n");
//等待线程pId的完成
pthread_join(pId,NULL);
printf("main thread exit\n");
return 0;
}
|
invincible1900/C-examples
|
misc/lib-test/dynamic-lib/use-lib/2/main.c
|
#include <dlfcn.h>
#include <stdio.h>
void (*wow)(void);
int main(){
void *h;
h = dlopen("./libwow.so", RTLD_NOW | RTLD_GLOBAL);
if(!h){
printf("error dlopen\n");
return -1;
}
wow = dlsym(h, "wow");
if(dlerror() != NULL){
printf("error dlsym\n");
return -1;
}
wow();
dlclose(h);
dlerror();
return 0;
}
|
miho/VMF-Text-Tests
|
test-code/transpose-blocking.c
|
//
// Each transpose function must have a prototype of the form:
// void trans(int M, int N, int A[N][M], int B[M][N]);
//
// A transpose function is evaluated by counting the number of misses
// on a 1KB direct mapped cache with a block size of 32 bytes.
// Author: <NAME>
// (note on style: in trans.c and csim.c, I comment using lower-case letters for readability.)
//
#include <stdio.h>
#include <stdbool.h>
#define N 64
#define M 64
//
// Checks whether B is the transpose of A
int is_transpose(int A[N][M], int B[M][N]);
void transpose2(int A[N][M], int B[M][N]) {
for (int i = 0; i < N; i ++) {
for (int j = 0; j < M; j ++) {
B[j][i] = A[i][j];
}
}
}
//
// Transposes A and stores the result in B
void transpose(int A[N][M], int B[M][N]) {
// illegal to have arrays or more than 12 local variables defined
// 6 variables are initialized in this function
int i;
int j;
int row;
int column;
int diagonal = 0;
int temp = 0;
if (N == 64) {
for (column = 0; column < N; column += 4) {
for (row = 0; row < N; row += 4) {
// iterate over the rows
for (i = row; i < row + 4; i++) {
for (j = column; j < column + 4; j++) {
// if not a diagonal element
if (i != j) {
B[j][i] = A[i][j];
} else {
temp = A[i][j];
diagonal = i;
}
}
if (row == column) {
B[diagonal][diagonal] = temp;
}
}
}
}
}
}
//
// is_transpose - This helper function checks if B is the transpose of
// A. You can check the correctness of your transpose by calling
// it before returning from the transpose function.
//
int is_transpose(int A[N][M], int B[M][N])
{
int i;
int j;
for (i = 0; i < N; i++) {
for (j = 0; j < M; ++j) {
if (A[i][j] != B[j][i]) {
return 0;
}
}
}
return 1;
}
// Execute test cases
int main(int argc, char *argv[]) {
// int X[N][N][N][N][N];
//
// Declare A and B
int A[N][M];
int B[M][N];
//
// Initialize A
for(int i = 0; i < N; i++) {
for(int j = 0; j < M; j++) {
A[i][j] = i+N*j;
B[i][j] = A[i][j];
}
}
if(is_transpose(A, B)) {
printf("==TRUE: B is the transpose of A\n");
} else {
printf("==FALSE: B isn't the transpose of A\n");
}
//
transpose(A, B);
//
if(is_transpose(A, B)) {
printf("==TRUE: B is the transpose of A\n");
} else {
printf("==FALSE: B isn't the transpose of A\n");
}
//
return 0;
}
// -- FOOTER --
|
ben5en/MSP430_sensorlessBLDC
|
F5529_sensorlessBLDC/drv8323/DRV8323_SPI.c
|
<reponame>ben5en/MSP430_sensorlessBLDC
// ----------------------------------------------------------------------
// Info
// ----------------------------------------------------------------------
/*
*
* Filename: DRV8323_SPI.c
*
* Author: (c) 2019, <NAME>
*
* Target: XXX
*
* Notes:
*
*/
// ----------------------------------------------------------------------
// History
// ----------------------------------------------------------------------
// 09.05.2019 - initial programming
// ----------------------------------------------------------------------
// Header Files
// ----------------------------------------------------------------------
#include "driverlib.h"
#include "DRV8323.h"
// ----------------------------------------------------------------------
// Defines
// ----------------------------------------------------------------------
#ifndef HIGH
#define HIGH 1
#endif
#ifndef LOW
#define LOW 0
#endif
#ifndef READ
#define READ 1
#endif
#ifndef WRITE
#define WRITE 0
#endif
// ----------------------------------------------------------------------
// Global Variables
// ----------------------------------------------------------------------
// DRV830x SPI Input Data bit definitions:
struct DRV830x_SPI_WRITE_WORD_BITS { // bit description
uint16_t DATA:11; // 10:0 FIFO reset
uint16_t ADDRESS:4; // 14:11 Enhancement enable
uint16_t R_W:1; // 15 R/W
};
union DRV830x_SPI_WRITE_WORD_REG {
uint16_t all;
struct DRV830x_SPI_WRITE_WORD_BITS bit;
};
// ----------------------------------------------------------------------
// Functions
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// SPI driver to interface with TLE5012
// ----------------------------------------------------------------------
uint16_t SPI_Driver(DRV8323_VARS_t *v, uint16_t data)
{
uint8_t highByte = (uint8_t)((data >> 8) & 0x00FF);
uint8_t lowByte = (uint8_t)(data & 0x00FF);
uint16_t returnValue;
//USCI_A0 TX buffer ready?
while (!USCI_B_SPI_getInterruptStatus(USCI_B0_BASE, USCI_B_SPI_TRANSMIT_INTERRUPT));
//Transmit Data to slave
USCI_B_SPI_transmitData(USCI_B0_BASE, highByte);
//USCI_A0 RX buffer ready?
while (!USCI_B_SPI_getInterruptStatus(USCI_B0_BASE, USCI_B_SPI_RECEIVE_INTERRUPT));
returnValue = (USCI_B_SPI_receiveData(USCI_B0_BASE) << 8) &0xFF00;
//USCI_A0 TX buffer ready?
while (!USCI_B_SPI_getInterruptStatus(USCI_B0_BASE, USCI_B_SPI_TRANSMIT_INTERRUPT));
//Transmit Data to slave
USCI_B_SPI_transmitData(USCI_B0_BASE, lowByte);
//USCI_A0 RX buffer ready?
while (!USCI_B_SPI_getInterruptStatus(USCI_B0_BASE, USCI_B_SPI_RECEIVE_INTERRUPT));
returnValue |= USCI_B_SPI_receiveData(USCI_B0_BASE) &0x00FF;
return returnValue;
}
// ----------------------------------------------------------------------
// Read from a DRV830x Register
// ----------------------------------------------------------------------
void DRV8323_SPI_Read(DRV8323_VARS_t *v, uint16_t address)
{
union DRV830x_SPI_WRITE_WORD_REG w;
uint16_t * cntrlReg;
cntrlReg = (uint16_t*)&(v->Fault_Status_1);
w.bit.R_W = READ;
w.bit.ADDRESS = address;
w.bit.DATA = 0;
// Enable CS; SPI transfer; Disable CS
GPIO_setOutputLowOnPin(v->ScsPort, v->ScsPin);
cntrlReg[address] = SPI_Driver(v, w.all);
GPIO_setOutputHighOnPin(v->ScsPort, v->ScsPin);
}
// ----------------------------------------------------------------------
// Write to a DRV830x Register
// ----------------------------------------------------------------------
void DRV8323_SPI_Write(DRV8323_VARS_t *v, uint16_t address)
{
union DRV830x_SPI_WRITE_WORD_REG w;
uint16_t * cntrlReg;
cntrlReg = (uint16_t*)&(v->Fault_Status_1);
w.bit.R_W = WRITE;
w.bit.ADDRESS = address;
w.bit.DATA = cntrlReg[address];
// Enable CS; SPI transfer; Disable CS
GPIO_setOutputLowOnPin(v->ScsPort, v->ScsPin);
SPI_Driver(v, w.all);
GPIO_setOutputHighOnPin(v->ScsPort, v->ScsPin);
}
// ----------------------------------------------------------------------
// something...
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// End of file
// ----------------------------------------------------------------------
|
ben5en/MSP430_sensorlessBLDC
|
F5529_sensorlessBLDC/bldc/bldc_1xPwm.h
|
<filename>F5529_sensorlessBLDC/bldc/bldc_1xPwm.h
#ifndef BLDC_BLDC_1XPWM_H_
#define BLDC_BLDC_1XPWM_H_
#ifdef __cplusplus
extern "C" {
#endif
// ----------------------------------------------------------------------
// info and license
// ----------------------------------------------------------------------
//
// filename: bldc_1xPwm.h
//
// MIT License
//
// Copyright (c) 2019 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// target: Texas Instruments MSP430
//
// ----------------------------------------------------------------------
// history
// ----------------------------------------------------------------------
// 03.09.2019 - initial programming
// ----------------------------------------------------------------------
// header files
// ----------------------------------------------------------------------
#include "driverlib.h"
#include "F5529_BLDC_Settings.h"
#include "bldc_types.h"
// ----------------------------------------------------------------------
// #defines
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// global variables
// ----------------------------------------------------------------------
typedef struct
{
uint16_t TimerBaseAddress; // Parameter: Base Address for driverlib funtion
uint16_t TimerCompareRegister; // Parameter: Timer Compare Register for driverlib function
uint16_t DutyMax; // Parameter: maximum Duty value
}BLDC_1xPWM_t;
// ----------------------------------------------------------------------
// functions
// ----------------------------------------------------------------------
// function to set default values for the object
inline void BLDC_PWM_objectInit(volatile BLDC_1xPWM_t *bldc_pwm_obj,
uint16_t baseAddress,
uint16_t compareRegister)
{
BLDC_1xPWM_t *obj = (BLDC_1xPWM_t*)bldc_pwm_obj;
obj->TimerBaseAddress = baseAddress;
obj->TimerCompareRegister = compareRegister;
obj->DutyMax = 0;
}
// ----------------------------------------------------------------------
// handles DRV8323 1x PWM mode. PWM output on TimerAx pin.
// Sets 3 selected pins high or low corresponding to the commutation table.
inline void BLDC_1xPWM_run(volatile BLDC_1xPWM_t *bldc_pwm_obj,
volatile CMTN_STATE_T cmtnState,
uint16_t duty)
{
BLDC_1xPWM_t *obj = (BLDC_1xPWM_t*)bldc_pwm_obj;
// update PWM on GPIO_DRV_INHA:
Timer_A_setCompareValue(obj->TimerBaseAddress, obj->TimerCompareRegister, duty);
// update logic level for DRV8323 commutation table:
switch(cmtnState)
{
case Cmtn_A_B: // State s1: current flows to motor windings from phase A->B, de-energized phase = C
GPIO_setOutputHighOnPin(GPIO_DRV_INLA);
GPIO_setOutputLowOnPin (GPIO_DRV_INHB);
GPIO_setOutputHighOnPin(GPIO_DRV_INLB);
break;
case Cmtn_A_C: // State s2: current flows to motor windings from phase A->C, de-energized phase = B
GPIO_setOutputHighOnPin(GPIO_DRV_INLA);
GPIO_setOutputLowOnPin (GPIO_DRV_INHB);
GPIO_setOutputLowOnPin (GPIO_DRV_INLB);
break;
case Cmtn_B_C: // State s3: current flows to motor windings from phase B->C, de-energized phase = A
GPIO_setOutputHighOnPin(GPIO_DRV_INLA);
GPIO_setOutputHighOnPin(GPIO_DRV_INHB);
GPIO_setOutputLowOnPin (GPIO_DRV_INLB);
break;
case Cmtn_B_A: // State s4: current flows to motor windings from phase B->A, de-energized phase = C
GPIO_setOutputLowOnPin (GPIO_DRV_INLA);
GPIO_setOutputHighOnPin(GPIO_DRV_INHB);
GPIO_setOutputLowOnPin (GPIO_DRV_INLB);
break;
case Cmtn_C_A: // State s5: current flows to motor windings from phase C->A, de-energized phase = B
GPIO_setOutputLowOnPin (GPIO_DRV_INLA);
GPIO_setOutputHighOnPin(GPIO_DRV_INHB);
GPIO_setOutputHighOnPin(GPIO_DRV_INLB);
break;
case Cmtn_C_B: // State s6: current flows to motor windings from phase C->B, de-energized phase = A
GPIO_setOutputLowOnPin (GPIO_DRV_INLA);
GPIO_setOutputLowOnPin (GPIO_DRV_INHB);
GPIO_setOutputHighOnPin(GPIO_DRV_INLB);
break;
case Cmtn_Align: // State s7: current flows to motor windings from phase A->(B+C)
GPIO_setOutputHighOnPin(GPIO_DRV_INLA);
GPIO_setOutputHighOnPin(GPIO_DRV_INHB);
GPIO_setOutputHighOnPin(GPIO_DRV_INLB);
break;
default: break;
}
}
// ----------------------------------------------------------------------
// something...
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// end of file
// ----------------------------------------------------------------------
#ifdef __cplusplus
}
#endif /* extern "C" */
#endif /* BLDC_BLDC_1XPWM_H_ */
|
ben5en/MSP430_sensorlessBLDC
|
F5529_sensorlessBLDC/fifo.h
|
#ifndef FIFO_H_
#define FIFO_H_
#ifdef __cplusplus
extern "C" {
#endif
// ----------------------------------------------------------------------
// info and license
// ----------------------------------------------------------------------
//
// filename: fifo.h
//
// MIT License
//
// Copyright (c) 2019 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// target: general C code
//
// ----------------------------------------------------------------------
// history
// ----------------------------------------------------------------------
// 02.09.2019 - initial programming
// ----------------------------------------------------------------------
// header files
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// #defines
// ----------------------------------------------------------------------
#define FIFO_SIZE 128
// ----------------------------------------------------------------------
// global variables
// ----------------------------------------------------------------------
typedef struct
{
uint8_t readIdx;
uint8_t writeIdx;
uint8_t fifoLvl;
uint8_t fifo[FIFO_SIZE];
bool full;
bool overrun;
} FIFO_t;
// ----------------------------------------------------------------------
// functions
// ----------------------------------------------------------------------
//
inline void FIFO_clear(FIFO_t *fifo_obj)
{
FIFO_t *obj = (FIFO_t*)fifo_obj;
// get buffer size:
uint8_t ctr;
// clear buffer:
for(ctr = 0; ctr < FIFO_SIZE; ctr++)
{
obj->fifo[ctr] = 0;
}
// reset pointer index:
obj->readIdx = 0;
obj->writeIdx = 0;
// reset level ctr:
obj->fifoLvl = 0;
// reset flags:
obj->full = false;
obj->overrun = false;
}
// ----------------------------------------------------------------------
//
inline void FIFO_write(FIFO_t *fifo_obj, uint8_t data)
{
FIFO_t *obj = (FIFO_t*)fifo_obj;
obj->fifo[obj->writeIdx] = data;
if(++obj->writeIdx > FIFO_SIZE-1)
{
obj->writeIdx = 0;
}
// increment fifo level
if(++obj->fifoLvl > FIFO_SIZE)
{
obj->overrun = true;;
}
}
// ----------------------------------------------------------------------
//
inline uint8_t FIFO_read(FIFO_t *fifo_obj)
{
FIFO_t *obj = (FIFO_t*)fifo_obj;
uint8_t retrunValue;
retrunValue = obj->fifo[obj->readIdx];
if(++obj->readIdx > FIFO_SIZE-1)
{
obj->readIdx = 0;
}
if(obj->fifoLvl > 0)
{
// decrement fifo level
obj->fifoLvl -= 1;
}
return retrunValue;
}
// ----------------------------------------------------------------------
// something...
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// end of file
// ----------------------------------------------------------------------
#ifdef __cplusplus
}
#endif /* extern "C" */
#endif /* FIFO_H_ */
|
ben5en/MSP430_sensorlessBLDC
|
F5529_sensorlessBLDC/drv8323/DRV8323.c
|
// ----------------------------------------------------------------------
// Info
// ----------------------------------------------------------------------
/*
*
* Filename: DRV8323.c
*
* Author: (c) 2019, <NAME>
*
* Target: XXX
*
* Notes:
*
*/
// ----------------------------------------------------------------------
// History
// ----------------------------------------------------------------------
// 09.05.2019 - initial programming
// ----------------------------------------------------------------------
// Header Files
// ----------------------------------------------------------------------
#include "driverlib.h"
#include "delay.h"
#include "DRV8323.h"
// ----------------------------------------------------------------------
// Defines
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// Global Variables
// ----------------------------------------------------------------------
DRV8323_VARS_t gDrv8323 = DRV8323_DEFAULTS;
// ----------------------------------------------------------------------
// Functions
// ----------------------------------------------------------------------
void DRV8323_initRegs(DRV8323_VARS_t *v)
{
// Set Register Driver Control Register (0x02)
v->Driver_Control.bit.DIS_CPUV = drv_chargePump_faultEnable;
v->Driver_Control.bit.DIS_GDF = drv_gateDrive_faultEnable;
v->Driver_Control.bit.OTW_REP = drv_otw_no_report;
v->Driver_Control.bit.PWM_MODE = drv_PWM_mode_1;
v->Driver_Control.bit.PWM_COM_1 = drv_1xPWM_synch;
v->Driver_Control.bit.PWM_DIR_1 = drv_1xPWM_noChangeDir;
v->Driver_Control.bit.COAST = drv_coastDisable;
v->Driver_Control.bit.BRAKE = drv_breakDisable;
v->Driver_Control.bit.CLR_FLT = drv_leaveFaults;
// Set Register Gate Drive HS Register (0x03)
v->Gate_Drive_HS.bit._LOCK = drv_unlock;
v->Gate_Drive_HS.bit.IDRIVEP_HS = drv_idriveP_hs_1000mA;
v->Gate_Drive_HS.bit.IDRIVEN_HS = drv_idriveN_hs_2000mA;
// Set Register Gate Drive LS Register (0x04)
v->Gate_Drive_LS.bit.CBC = drv_clrFaults;
v->Gate_Drive_LS.bit.TDRIVE = drv_tdrive_4000nS;
v->Gate_Drive_LS.bit.IDRIVEP_LS = drv_idriveP_ls_1000mA;
v->Gate_Drive_LS.bit.IDRIVEN_LS = drv_idriveN_ls_2000mA;
// Set Register OCP Control Register (0x05)
v->OCP_Control.bit.TRETRY = drv_retry_time_4ms;
v->OCP_Control.bit.DEAD_TIME = drv_deadTime_100nS;
v->OCP_Control.bit.OCP_MODE = drv_ocp_mode_autoRetryFault;
v->OCP_Control.bit.OCP_DEG = drv_ocp_deg_4us;
v->OCP_Control.bit.VDS_LVL = drv_vds_lvl_750mV;
// Set Register CSA Control Register (0x06)
v->CSA_Control.bit.CSA_FET = drv_input_SPx;
v->CSA_Control.bit.VREF_DIV = drv_vref_div_2; // bidirectional
v->CSA_Control.bit.LS_REF = drv_vds_ocp_SHx_SPx;
v->CSA_Control.bit.CSA_GAIN = drv_gain_20;
v->CSA_Control.bit.DIS_SEN = drv_oc_faultEnable;
v->CSA_Control.bit.CSA_CAL_A = drv_normal_sense;
v->CSA_Control.bit.CSA_CAL_B = drv_normal_sense;
v->CSA_Control.bit.CSA_CAL_C = drv_normal_sense;
v->CSA_Control.bit.SEN_LVL = drv_ocp_1000mV;
}
// ----------------------------------------------------------------------
//
void DRV8323_init(DRV8323_VARS_t *v)
{
DRV8323_SPI_Write(v, DRV8323_DRIVER_CNTRL_ADDR); //write to DRV8323
DRV8323_SPI_Write(v, DRV8323_GATE_DRIVE_HS_ADDR); //write to DRV8323
DRV8323_SPI_Write(v, DRV8323_GATE_DRIVE_LS_ADDR); //write to DRV8323
DRV8323_SPI_Write(v, DRV8323_OCP_CNTRL_ADDR); //write to DRV8323
DRV8323_SPI_Write(v, DRV8323_CSA_CNTRL_ADDR); //write to DRV8323
uint16_t i;
for(i= 0; i < DRV8323_CSA_CNTRL_ADDR + 1; i++)
{
DRV8323_SPI_Read(v, i);
delay_us(5);
}
}
// ----------------------------------------------------------------------
// something...
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// End of file
// ----------------------------------------------------------------------
|
ben5en/MSP430_sensorlessBLDC
|
F5529_sensorlessBLDC/bldc/step_resp.h
|
#ifndef BLDC_STEP_RESP_H_
#define BLDC_STEP_RESP_H_
#ifdef __cplusplus
extern "C" {
#endif
// ----------------------------------------------------------------------
// info and license
// ----------------------------------------------------------------------
//
// filename: step_resp.h
//
// MIT License
//
// Copyright (c) 2019 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// target: Texas Instruments MSP430
//
//
// Contains routine which is used to do a current reference step.
// This can be used to adjust the current controller gains.
// Visualize response with the help of an oscilloscope.
//
//
// ----------------------------------------------------------------------
// history
// ----------------------------------------------------------------------
// 07.09.2019 - initial programming
// ----------------------------------------------------------------------
// header files
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// #defines
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// global variables
// ----------------------------------------------------------------------
typedef volatile struct
{
uint16_t Cntr; // actual counter value
uint16_t CntMax; // maximum counter value
_q IdcRef_pu; // holds reference current for current step [pu]
bool DoStep; // flag to perform step
}STEP_RESPONSE_t;
// ----------------------------------------------------------------------
// functions
// ----------------------------------------------------------------------
// function to set default values for the object
inline void STEP_objectInit(volatile STEP_RESPONSE_t *step_obj)
{
STEP_RESPONSE_t *obj = (STEP_RESPONSE_t*)step_obj;
obj->CntMax = 0;
obj->Cntr = 0;
obj->DoStep = false;
obj->IdcRef_pu = 0;
}
// ----------------------------------------------------------------------
// function handles step response and energizes for predefined time (ticks)
//
inline _q STEP_run(volatile STEP_RESPONSE_t *step_obj)
{
STEP_RESPONSE_t *obj = (STEP_RESPONSE_t*)step_obj;
_q out;
if(true == obj->DoStep)
{
if(++(obj->Cntr) > obj->CntMax)
{
obj->DoStep = false;
obj->Cntr = 0;
}
out = obj->IdcRef_pu;
}
else
{
out = 0;
}
return out;
}
// ----------------------------------------------------------------------
// end of file
// ----------------------------------------------------------------------
#ifdef __cplusplus
}
#endif /* extern "C" */
#endif /* BLDC_STEP_RESP_H_ */
|
ben5en/MSP430_sensorlessBLDC
|
F5529_sensorlessBLDC/bldc/status.h
|
<gh_stars>1-10
#ifndef BLDC_STATUS_H_
#define BLDC_STATUS_H_
#ifdef __cplusplus
extern "C" {
#endif
// ----------------------------------------------------------------------
// info and license
// ----------------------------------------------------------------------
//
// filename: status.h
//
// MIT License
//
// Copyright (c) 2019 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// target: Texas Instruments MSP430
//
// ----------------------------------------------------------------------
// history
// ----------------------------------------------------------------------
// 03.09.2019 - initial programming
// ----------------------------------------------------------------------
// header files
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// #defines
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// global variables
// ----------------------------------------------------------------------
typedef enum
{
STATUS_stop = 0, // state = stop
STATUS_run // state = start
}STAUTS_pwr_flag_e;
typedef enum
{
STATUS_stepResponse = 0, // operation mode = stepResponse, only for adjustments
STATUS_lock, // operation mode = lock
STATUS_alignment, // operation mode = alignment
STATUS_spin // operation mode = spin
}STAUTS_operation_mode_e;
typedef volatile struct
{
STAUTS_pwr_flag_e PwrFlag;
STAUTS_operation_mode_e OperationMode;
bool Aligned;
}STATUS_t;
// ----------------------------------------------------------------------
// functions
// ----------------------------------------------------------------------
// function to set default values for the object
inline void STATUS_objectInit(volatile STATUS_t *status_obj)
{
STATUS_t *obj = (STATUS_t*)status_obj;
obj->Aligned = false;
obj->OperationMode = STATUS_lock;
obj->PwrFlag = STATUS_stop;
}
// ----------------------------------------------------------------------
// something...
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// end of file
// ----------------------------------------------------------------------
#ifdef __cplusplus
}
#endif /* extern "C" */
#endif /* BLDC_STATUS_H_ */
|
ben5en/MSP430_sensorlessBLDC
|
F5529_sensorlessBLDC/unused_interrupts.c
|
#include <driverlib.h>
// *****************************************************************************
// MSP430F5529 Unused Vectors
// *****************************************************************************
// UNUSED_HWI_ISR()
//
// The default linker command file created by CCS links all interrupt vectors to
// their specified address location. This gives you a warning for vectors that
// are not associated with an ISR function. The following function (and pragma's)
// handles all interrupt vectors.
//
// Just make sure you comment out the vector pragmas handled by your own code.
// For example, you will receive a "program will not fit into" error if you do
// not comment out the WDT vector below. This occurs since the linker tries to
// fit both of the vector addresses into the same memory locations ... and they
// won't fit.
// *****************************************************************************
#pragma vector=ADC12_VECTOR
#pragma vector=COMP_B_VECTOR
//#pragma vector=DMA_VECTOR
#pragma vector=PORT1_VECTOR
#pragma vector=PORT2_VECTOR
#pragma vector=RTC_VECTOR
#pragma vector=SYSNMI_VECTOR
#pragma vector=TIMER0_A0_VECTOR
#pragma vector=TIMER0_A1_VECTOR
#pragma vector=TIMER0_B0_VECTOR
#pragma vector=TIMER0_B1_VECTOR
#pragma vector=TIMER1_A0_VECTOR
#pragma vector=TIMER1_A1_VECTOR
//#pragma vector=TIMER2_A0_VECTOR
#pragma vector=TIMER2_A1_VECTOR
#pragma vector=UNMI_VECTOR
#pragma vector=USB_UBM_VECTOR
//#pragma vector=USCI_A0_VECTOR
#pragma vector=USCI_A1_VECTOR
#pragma vector=USCI_B0_VECTOR
#pragma vector=USCI_B1_VECTOR
#pragma vector=WDT_VECTOR
__interrupt void UNUSED_HWI_ISR (void)
{
__no_operation();
}
|
ben5en/MSP430_sensorlessBLDC
|
F5529_sensorlessBLDC/main.c
|
<reponame>ben5en/MSP430_sensorlessBLDC
// ----------------------------------------------------------------------
// info and license
// ----------------------------------------------------------------------
//
// filename: main.c
//
// MIT License
//
// Copyright (c) 2019 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// target: Texas Instruments MSP430
//
// ######################################################################
// Info:
// This software provides a simple example of a cascaded speed control as a sensorless
// block commutation on an MSP430F5529 Launchpad in combination with a DRV8323 BoosterPack.
//
// Other features include debugging via the serial interface (UartMonitor) and a decoupling
// of the DC link voltage.
//
// The underlying current control as well as the sensorless calculations are generated with
// a frequency of max. 16kHz running. The DRV8323RS can be controlled with 6, 3 or 1 PWM signals.
// According to the pin layout of the Launchpad it becomes clear that for the 6 or 3 PWM mode
// several different timer peripherals would be necessary. Unfortunately, there is no way to
// start different timers synchronized. Thus, in this case, the 1x PWM method was used.
//
// The ADC module offers the possibility to be started in hardware from one out of three timer
// modules. Sad to say, the Launchpad's routing in combination with the DRV BoosterPack does
// not allow you to use one of the three triggering timer modules. For this purpose, a timer
// interrupt is triggered at the reversal point of the PWM carrier signal and the ADC conversion
// is started in software!
//
// Since the start of the ADC conversion is triggered in software, all calculations must be done
// so that the timer ISR can be triggered and called undisturbed:
// The ADC values are provided via DMA. From the sampling start to calling the DMA ISR for motor
// control, nearly 22us pass. The calculations needed for motor control take almost 38us at a
// system frequency of 25MHz. Thus, about 60us pass, which represents the maximum value (62.5us at
// 16kHz PWM / ISR frequency) for the calculation time, so that the ISR / starting point of the ADC
// conversion is not called late / not aligned.
//
// The 1x PWM method is practicable. In a separate layout I would recommend to use one out of the
// three timer peripherals which allow you to start ADC sampling via hardware.
// In this way, the PWM frequency can be further increased because sufficient computation time
// is available, or the system frequency can be lowered.
//
// Nonetheless, the MSP430 performs very well and can be used for simple motor control tasks
// with a suitable routing.
//
// Source: some of the routines are based on routines of the "math blocks" found in the
// controlSuite for C2000 controllers.
// ######################################################################
//
// ----------------------------------------------------------------------
// history
// ----------------------------------------------------------------------
// 16.08.2019 - initial programming
// ----------------------------------------------------------------------
// header files
// ----------------------------------------------------------------------
#include "driverlib.h"
#include "QmathLib.h"
#include "F5529_BLDC_Settings.h"
#include "delay.h"
#include "config.h"
#include "status.h"
#include "bldc.h"
#include "fifo.h"
#include "Serial_Cmd_Monitor.h"
#include "DRV8323.h"
// ----------------------------------------------------------------------
// #defines
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// global variables
// ----------------------------------------------------------------------
FIFO_t Fifo;
// ----------------------------------------------------------------------
// functions
// ----------------------------------------------------------------------
void debugMonitor(void);
void drv8323RS_init(void);
// ----------------------------------------------------------------------
//
void main (void)
{
// ----------------------------------------------------------------------
// Initialize the MSP430F5529LP
MSP430F5529LP_init();
// ----------------------------------------------------------------------
// UART Monitor is used for debugging
// More information can be found here: https://github.com/ben5en/MSP430_UartMonitor
ClearBufferRelatedParam();
// UART RX is ISR - handled and TX is handled in main loop.
// The MSP430F5529 does not have a hardware FIFO, thus a SW FIFO is used
// to store RX'ed values and handle the debug-routine in main loop.
FIFO_clear(&Fifo);
// ----------------------------------------------------------------------
// Initialize the DRV8323
drv8323RS_init();
// ----------------------------------------------------------------------
// Initialize the motor control parameter with the help of DMA peripheral:
BLDC_initWithDMA();
// ----------------------------------------------------------------------
// Start the timer; make sure you specify the correct counting mode:
Timer_A_startCounter(TIMER_A2_BASE, TIMER_A_UPDOWN_MODE);
// ----------------------------------------------------------------------
// TODO: enable nFault ISR + IE config for pin + ISR routine for fault state
// ----------------------------------------------------------------------
//
__bis_SR_register(GIE); // Enable interrupts globally
// ----------------------------------------------------------------------
//
while(1)
{
BLDC_runSpeedCntl();
BLDC_runDecoupling();
debugMonitor();
}
}
// ----------------------------------------------------------------------
// Start the ADC conversion aligned to the center of the PWM period:
#pragma vector=TIMER2_A0_VECTOR
__interrupt void CCR0_ISR (void)
{
ADC12_A_startConversion(ADC12_A_BASE, ADC12_A_MEMORY_0, ADC12_A_SEQOFCHANNELS);
}
// ----------------------------------------------------------------------
// UartMonitor RX, write into software FIFO:
#pragma vector=USCI_A0_VECTOR
__interrupt void USCI_A0_ISR (void)
{
switch (__even_in_range(UCA0IV,4)){
case 0: break; //Vector 0: No interrupt
case 2: FIFO_write(&Fifo, USCI_A_UART_receiveData(USCI_A0_BASE)); break; //Vector 2: RX ISR
case 4: break; //Vector 4: TX ISR
default: break;
}
}
// ----------------------------------------------------------------------
// ADC values are transferd to there corresponding variable, run BLDC routine:
#pragma vector=DMA_VECTOR
__interrupt void DMA_ISR (void)
{
switch (__even_in_range(DMAIV,16)){
case 0: break;
case 2: BLDC_runCmtnCntl(); break; //DMA0IFG = DMA Channel 0
case 4: break; //DMA1IFG = DMA Channel 1
case 6: break; //DMA2IFG = DMA Channel 2
case 8: break; //DMA3IFG = DMA Channel 3
case 10: break; //DMA4IFG = DMA Channel 4
case 12: break; //DMA5IFG = DMA Channel 5
case 14: break; //DMA6IFG = DMA Channel 6
case 16: break; //DMA7IFG = DMA Channel 7
default: break;
}
}
// ----------------------------------------------------------------------
//
void debugMonitor(void)
{
// if something is in the FIFO, handle it:
if(Fifo.fifoLvl > 0)
{
// SerialCmdMonitor routine:
receivedDataCommand(FIFO_read(&Fifo));
}
// reset FIFO if an overrun is detected:
if(true == Fifo.overrun)
{
//Disable receive interrupt
USCI_A_UART_clearInterrupt (USCI_A0_BASE, USCI_A_UART_RECEIVE_INTERRUPT);
USCI_A_UART_disableInterrupt(USCI_A0_BASE, USCI_A_UART_RECEIVE_INTERRUPT);
ClearBufferRelatedParam();
FIFO_clear(&Fifo);
//Enable receive interrupt
USCI_A_UART_clearInterrupt (USCI_A0_BASE, USCI_A_UART_RECEIVE_INTERRUPT);
USCI_A_UART_enableInterrupt(USCI_A0_BASE, USCI_A_UART_RECEIVE_INTERRUPT);
}
}
// ----------------------------------------------------------------------
//
void drv8323RS_init(void)
{
// Connect chip select port and pin
gDrv8323.ScsPort = (uint16_t)GPIO_PORT_P2;
gDrv8323.ScsPin = (uint16_t)GPIO_PIN3;
// enable the DRV8323RS driver
GPIO_setOutputHighOnPin(GPIO_DRV_ENABLE);
delay_us(1e6);
// hardware offset calibration:
GPIO_setOutputHighOnPin(GPIO_DRV_CAL);
delay_us(120);
GPIO_setOutputLowOnPin (GPIO_DRV_CAL);
delay_us(120);
// read and store the default register values:
uint16_t i;
for(i= 0; i < DRV8323_CSA_CNTRL_ADDR + 1; i++)
{
DRV8323_SPI_Read(&gDrv8323, i);
delay_us(5);
}
// update to PWM_mode_1:
gDrv8323.Driver_Control.bit.PWM_MODE = drv_PWM_mode_1;
DRV8323_SPI_Write(&gDrv8323, DRV8323_DRIVER_CNTRL_ADDR);
// update to CSA_GAIN correspond to the settings:
#ifdef DRV8323_GAIN_5
gDrv8323.CSA_Control.bit.CSA_GAIN = drv_gain_5;
#elif DRV8323_GAIN_10
gDrv8323.CSA_Control.bit.CSA_GAIN = drv_gain_10;
#elif DRV8323_GAIN_20
gDrv8323.CSA_Control.bit.CSA_GAIN = drv_gain_20;
#elif DRV8323_GAIN_40
gDrv8323.CSA_Control.bit.CSA_GAIN = drv_gain_40;
#endif
DRV8323_SPI_Write(&gDrv8323, DRV8323_CSA_CNTRL_ADDR);
}
// ----------------------------------------------------------------------
// end of file
// ----------------------------------------------------------------------
|
ben5en/MSP430_sensorlessBLDC
|
F5529_sensorlessBLDC/F5529_BLDC_Settings.h
|
<gh_stars>1-10
#ifndef F5529_BLDC_SETTINGS_H_
#define F5529_BLDC_SETTINGS_H_
#ifdef __cplusplus
extern "C" {
#endif
// ----------------------------------------------------------------------
// info and license
// ----------------------------------------------------------------------
//
// filename: F5529_BLDC_Settings.h
//
// MIT License
//
// Copyright (c) 2019 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// target: Texas Instruments MSP430F5529LP with BOOSTXL-DRV8323RS EVM
//
// ----------------------------------------------------------------------
// history
// ----------------------------------------------------------------------
// 17.08.2019 - initial programming
// ----------------------------------------------------------------------
// header files
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// #defines
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// Define the system frequencies:
// ----------------------------------------------------------------------
#define XT1_LF_CRYSTAL_FREQUENCY_IN_HZ 32768 // 32KHz
#define XT2_HF_CRYSTAL_FREQUENCY_IN_HZ 4000000 // 4MHz
#define MCLK_FREQUENCY_1MHz 1000 // Value has to be in kHz
#define MCLK_FREQUENCY_4MHz 4000 // Value has to be in kHz
#define MCLK_FREQUENCY_8MHz 8000 // Value has to be in kHz
#define MCLK_FREQUENCY_12MHz 12000 // Value has to be in kHz
#define MCLK_FREQUENCY_16MHz 16000 // Value has to be in kHz
#define MCLK_FREQUENCY_25MHz 25000 // Value has to be in kHz
#define MCLK_DESIRED_FREQUENCY_IN_KHZ MCLK_FREQUENCY_25MHz
#define MCLK_FLLREF_RATIO MCLK_DESIRED_FREQUENCY_IN_KHZ / ( UCS_REFOCLK_FREQUENCY / 1024 ) // Ratio = 250 for 8MHz clock
#define XT1_TIMEOUT 50000
#define XT2_TIMEOUT 50000
#define SYSTEM_FREQUENCY_MHz (MCLK_DESIRED_FREQUENCY_IN_KHZ / 1000)
// ----------------------------------------------------------------------
// Define the control and PWM frequencies:
// ----------------------------------------------------------------------
// 16kHz is the maximum frequency according to the calculation duration in the mode run and spin.
#define DEVICE_PWM_FREQUENCY_kHz (16.0)
#define DEVICE_ISR_FREQUENCY_kHz DEVICE_PWM_FREQUENCY_kHz
#define DEVICE_ISR_PERIDODE_Sec (0.001/DEVICE_ISR_FREQUENCY_kHz)
// ticks for the PWM module
#define DEVICE_PWM_CLOCK_FREQUENCY_MHz (MCLK_DESIRED_FREQUENCY_IN_KHZ)
#define DEVICE_PWM_TICKS ((DEVICE_PWM_CLOCK_FREQUENCY_MHz/DEVICE_PWM_FREQUENCY_kHz)*1000)
#define DEVICE_PWM_TBPRD (DEVICE_PWM_TICKS/2)
// ----------------------------------------------------------------------
// Define the ADC dependencies:
// ----------------------------------------------------------------------
// 3 phase currents are located at:
#define DRV_ISEN_A_CH ADC12_A_INPUT_A12
#define DRV_ISEN_B_CH ADC12_A_INPUT_A4
#define DRV_ISEN_C_CH ADC12_A_INPUT_A3
// 3 phase voltages are located at:
#define DRV_VSEN_A_CH ADC12_A_INPUT_A0
#define DRV_VSEN_B_CH ADC12_A_INPUT_A1
#define DRV_VSEN_C_CH ADC12_A_INPUT_A2
// bus voltage is located at:
#define DRV_VSEN_VM_CH ADC12_A_INPUT_A5
// DRV potentiometer is located at:
#define DRV_POTENTIOMETER_CH ADC12_A_INPUT_A6
// 3 phase currents memory:
#define DRV_ADC_ISEN_A ADC12_A_MEMORY_3
#define DRV_ADC_ISEN_B ADC12_A_MEMORY_4
#define DRV_ADC_ISEN_C ADC12_A_MEMORY_5
// 3 phase voltages memory:
#define DRV_ADC_VSEN_A ADC12_A_MEMORY_0
#define DRV_ADC_VSEN_B ADC12_A_MEMORY_1
#define DRV_ADC_VSEN_C ADC12_A_MEMORY_2
// bus voltage memory:
#define DRV_ADC_VSEN_VM ADC12_A_MEMORY_6
// DRV potentiometer memory:
#define DRV_ADC_POTI ADC12_A_MEMORY_7
// ----------------------------------------------------------------------
// Define motor parameter:
// ----------------------------------------------------------------------
// these values fit for an "Hetai 42BLF01" motor
#define MOTOR_POLES (8)
#define MOTOR_POLEPAIRS (MOTOR_POLES/2)
#define MOTOR_RS_OHM (0.985100389)
#define MOTOR_LD_H (0.00053623761)
#define MOTOR_LQ_H (0.00053623761)
#define MOTOR_FLUX_WB (0.0063879968)
#define MOTOR_MAX_SPD_RPM (4000.0L)
#define MOTOR_MAX_SPD_ELEC ((MOTOR_MAX_SPD_RPM/60)*MOTOR_POLEPAIRS)
#define MOTOR_MEASURINGRANGE_RPM (1.2 * MOTOR_MAX_SPD_RPM) // give 20% headroom
#define MOTOR_MAX_CURRENT_IDC_A (2.0)
// ----------------------------------------------------------------------
// Define the operating conditions for open-loop start up ramp
// ----------------------------------------------------------------------
#define TRIGGER_PER_REVOLUTION 6 // 6-step commutation
#define OPENLOOP_END_RPM 500 // [rpm]
#define OPENLOOP_RAMP_DELAY (0.4) // [sec]
#define OPENLOOP_DUTY (0.3) // 30% of DEVICE_SHUNT_CURRENT_A
// open loop ramps up from 1 rpm up to OPENLOOP_END_RPM.
// open-loop algorithm works with period input...
// don't change the following 5 lines:
#define OPENLOOP_START_TICKS ((DEVICE_ISR_FREQUENCY_kHz*1000)/(TRIGGER_PER_REVOLUTION*MOTOR_POLEPAIRS*OPENLOOP_START_PERIODE))
#define OPENLOOP_END_TICKS ((DEVICE_ISR_FREQUENCY_kHz*1000)/(TRIGGER_PER_REVOLUTION*MOTOR_POLEPAIRS*OPENLOOP_END_PERIODE))
#define OPENLOOP_DELAY_TICKS ((DEVICE_ISR_FREQUENCY_kHz*1000*OPENLOOP_RAMP_DELAY)/(OPENLOOP_START_TICKS-OPENLOOP_END_TICKS))
#define OPENLOOP_START_PERIODE 1 // [Hz]
#define OPENLOOP_END_PERIODE (OPENLOOP_END_RPM / 60) // [Hz]
// ----------------------------------------------------------------------
// Define the operating conditions for ramp control
// ----------------------------------------------------------------------
#define DEVICE_RAMP_ACC_STEPS 10 // Gradient for accelerate
#define DEVICE_RAMP_DEC_STEPS 15 // Gradient for decelerate
// ----------------------------------------------------------------------
// Define the DRV8323 quantities (gain)
// ----------------------------------------------------------------------
//#define DRV8323_GAIN_5 5
//#define DRV8323_GAIN_10 10
//#define DRV8323_GAIN_20 20
#define DRV8323_GAIN_40 40
// ----------------------------------------------------------------------
// Define the device quantities (voltage, current, speed)
// ----------------------------------------------------------------------
#define DEVICE_DC_VOLTAGE_V 56.867134 // max. ADC bus voltage(PEAK) [V]
#ifdef DRV8323_GAIN_5
#define DEVICE_SHUNT_CURRENT_A 47.0 // phase current(PEAK) [A]
#elif DRV8323_GAIN_10
#define DEVICE_SHUNT_CURRENT_A 23.5 // phase current(PEAK) [A]
#elif DRV8323_GAIN_20
#define DEVICE_SHUNT_CURRENT_A 11.75 // phase current(PEAK) [A]
#elif DRV8323_GAIN_40
#define DEVICE_SHUNT_CURRENT_A 5.875 // phase current(PEAK) [A]
#endif
// ----------------------------------------------------------------------
// Define the device quantities limits for shutdown / safety functions
// ----------------------------------------------------------------------
#define DEVICE_MAX_CURRENT_A 5.90 // limit of motor or semiconductor
#define DEVICE_MAX_DC_VOLTAGE_V 30.00 // limit of motor or semiconductor
#define DEVICE_MIN_DC_VOLTAGE_V 8.00
#define DEVICE_UNDERVOLTAGE_TIMEOUT_mSec 5.0
// scale to per-unit
#define DEVICE_MAX_CURRENT_PU (DEVICE_MAX_CURRENT_A / DEVICE_SHUNT_CURRENT_A)
#define DEVICE_MAX_DC_VOLTAGE_PU (DEVICE_MAX_DC_VOLTAGE_V / DEVICE_DC_VOLTAGE_V)
// ----------------------------------------------------------------------
// Define the device pin mappings
// ----------------------------------------------------------------------
#define GPIO_SPI_SCLK GPIO_PORT_P3, GPIO_PIN2
#define GPIO_SPI_MOSI GPIO_PORT_P3, GPIO_PIN0
#define GPIO_SPI_MISO GPIO_PORT_P3, GPIO_PIN1
#define GPIO_UART_TX GPIO_PORT_P3, GPIO_PIN3
#define GPIO_UART_RX GPIO_PORT_P3, GPIO_PIN4
#define GPIO_I2C_SCL GPIO_PORT_P4, GPIO_PIN2
#define GPIO_I2C_SDA GPIO_PORT_P4, GPIO_PIN1
#define GPIO_HALL_A GPIO_PORT_P2, GPIO_PIN0
#define GPIO_HALL_B GPIO_PORT_P2, GPIO_PIN2
#define GPIO_HALL_C GPIO_PORT_P2, GPIO_PIN6
#define GPIO_LED_RED GPIO_PORT_P1, GPIO_PIN0
#define GPIO_LED_GREEN GPIO_PORT_P4, GPIO_PIN7
#define GPIO_BUTTON_S1 GPIO_PORT_P2, GPIO_PIN1
#define GPIO_BUTTON_S2 GPIO_PORT_P1, GPIO_PIN1
#define GPIO_XOUT_XIN GPIO_PORT_P5, GPIO_PIN5 | GPIO_PIN4
#define GPIO_XT2OUT_XT2IN GPIO_PORT_P5, GPIO_PIN3 | GPIO_PIN2
#define GPIO_ACLK GPIO_PORT_P1, GPIO_PIN0
#define GPIO_SMCLK GPIO_PORT_P2, GPIO_PIN2
#define GPIO_MCLK GPIO_PORT_P7, GPIO_PIN7
#define GPIO_DRV_CS GPIO_PORT_P2, GPIO_PIN3
#define GPIO_DRV_CAL GPIO_PORT_P8, GPIO_PIN1
#define GPIO_DRV_nFAULT GPIO_PORT_P2, GPIO_PIN7
#define GPIO_DRV_ENABLE GPIO_PORT_P1, GPIO_PIN6
#define GPIO_DRV_LED GPIO_PORT_P4, GPIO_PIN0
// The DRV is going to be used in 1xPWM-Mode:
#define GPIO_DRV_INHA GPIO_PORT_P2, GPIO_PIN5
#define GPIO_DRV_INLA GPIO_PORT_P2, GPIO_PIN4
#define GPIO_DRV_INHB GPIO_PORT_P1, GPIO_PIN5
#define GPIO_DRV_INLB GPIO_PORT_P1, GPIO_PIN4
#define GPIO_DRV_INHC GPIO_PORT_P1, GPIO_PIN3
#define GPIO_DRV_INLC GPIO_PORT_P1, GPIO_PIN2
// In 1xPWM-Mode GPIO_DRV_INHC & GPIO_DRV_INLC have some special functions:
// The INHC input controls the direction through the 6-step commutation
// table which is used to change the direction of the motor when Hall
// effect sensors are directly controlling the state of the INLA, INHB,
// and INLB inputs. Tie the INHC pin low if this feature is not required.
#define GPIO_DRV_DIR GPIO_DRV_INHC
// The INLC input brakes the motor by turning off all high-side MOSFETs
// and turning on all low-side MOSFETs when the INLC pin is pulled low.
#define GPIO_DRV_BRAKE GPIO_DRV_INLC
// ----------------------------------------------------------------------
// end of file
// ----------------------------------------------------------------------
#ifdef __cplusplus
}
#endif /* extern "C" */
#endif /* F5529_BLDC_SETTINGS_H_ */
|
ben5en/MSP430_sensorlessBLDC
|
F5529_sensorlessBLDC/ramfunc.h
|
<filename>F5529_sensorlessBLDC/ramfunc.h
#ifndef RAMFUNC_H_
#define RAMFUNC_H_
#ifdef __cplusplus
extern "C" {
#endif
// ----------------------------------------------------------------------
// info and license
// ----------------------------------------------------------------------
//
// filename: ramfunc.h
//
// MIT License
//
// Copyright (c) 2019 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// target: Texas Instruments MSP430
//
// ----------------------------------------------------------------------
// history
// ----------------------------------------------------------------------
// 08.09.2019 - initial programming and testing...
// ----------------------------------------------------------------------
// header files
// ----------------------------------------------------------------------
#include "string.h"
#include "stdlib.h"
// ----------------------------------------------------------------------
// #defines
// ----------------------------------------------------------------------
#define RAMFUNCS_SIZE 0x0800
#define FLASH_START_ADD 0x4400 + (0xBB80 - RAMFUNCS_SIZE) // Flash code starting address
#define FLASH_CODE_SIZE RAMFUNCS_SIZE // Function segment size to be copied
#define RAM_START_ADD 0x2400 + (0x2000 - RAMFUNCS_SIZE) // RAM code starting address
// ----------------------------------------------------------------------
// global variables
// ----------------------------------------------------------------------
extern unsigned char _RamfuncsLoadStart;
extern unsigned char _RamfuncsRunStart;
extern unsigned char _RamfuncsLoadSize;
// ----------------------------------------------------------------------
// functions
// ----------------------------------------------------------------------
void copyFlashToRam (void)
{
unsigned char *flash_start_ptr; // Initialize pointers
unsigned char *RAM_start_ptr;
flash_start_ptr = (unsigned char *)FLASH_START_ADD;
RAM_start_ptr = (unsigned char *)RAM_START_ADD;
// Copy flash function to RAM
memcpy(RAM_start_ptr,flash_start_ptr,FLASH_CODE_SIZE);
}
// ----------------------------------------------------------------------
// something...
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// end of file
// ----------------------------------------------------------------------
#ifdef __cplusplus
}
#endif /* extern "C" */
#endif /* RAMFUNC_H_ */
|
ben5en/MSP430_sensorlessBLDC
|
F5529_sensorlessBLDC/bldc/bldc.c
|
// ----------------------------------------------------------------------
// info and license
// ----------------------------------------------------------------------
//
// filename: bldc.c
//
// MIT License
//
// Copyright (c) 2019 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// target: Texas Instruments MSP430
//
// ######################################################################
// Use the "ProgramModelUart" for a variable view during runtime:
// This is already implemented in this software. More informations:
// https://github.com/ben5en/MSP430_UartMonitor
// ######################################################################
//
// ----------------------------------------------------------------------
// history
// ----------------------------------------------------------------------
// 08.09.2019 - initial programming
// TODO: take offsets:
// ----------------------------------------------------------------------
// header files
// ----------------------------------------------------------------------
#include "driverlib.h"
#include "QmathLib.h"
#include "F5529_BLDC_Settings.h"
#include "bldc_types.h"
#include "status.h"
#include "cmtn.h"
#include "pi.h"
#include "bldc_1xPwm.h"
#include "ramp.h"
#include "step_resp.h"
#include "openLoop.h"
// ----------------------------------------------------------------------
// #defines
// ----------------------------------------------------------------------
#define SPEED_SCALER ((uint16_t)((DEVICE_PWM_FREQUENCY_kHz/(1*MOTOR_MAX_SPD_ELEC*0.001))))
// ----------------------------------------------------------------------
// global variables
// ----------------------------------------------------------------------
// all voltage and current objects, variables and helpers:
volatile MOTOR_3PHASES_t Vphase_pu;
volatile _q VdcBus_pu;
volatile _q VoneByDcBus_pu;
volatile _q Vpoti_pu;
volatile MOTOR_3PHASES_t Iphase_pu;
struct DMA_results
{
uint16_t VphaseAs_dma;
uint16_t VphaseBs_dma;
uint16_t VphaseCs_dma;
uint16_t IphaseAs_dma;
uint16_t IphaseBs_dma;
uint16_t IphaseCs_dma;
uint16_t VdcBus_dma;
uint16_t Vpoti_dma;
};
volatile struct DMA_results Dma;
// ----------------------------------------------------------------------
// all state objects, variables and helpers:
volatile STATUS_t Status; // load this into the expression window in debug mode
volatile CMTN_STATE_T CmtnState;
volatile bool CmtnTrigger;
// ----------------------------------------------------------------------
// all timing objects, variables and helpers:
volatile uint16_t VirtualTimer;
volatile uint16_t AlignCntr;
volatile uint16_t AlignCntMax;
// ----------------------------------------------------------------------
// all controller objects, variables and helpers:
volatile PI_t Pi_Idc;
volatile PI_t Pi_Speed;
// ----------------------------------------------------------------------
// all functional, variables and helpers:
volatile BLDC_1xPWM_t Pwm;
volatile RAMP_t SpeedRamp;
volatile STEP_RESPONSE_t Step;
volatile OPENLOOP_t OpenLoop;
volatile CMTN_t Cmtn;
// ----------------------------------------------------------------------
// others:
volatile _q SpeedTarget_pu; // load this into the expression window in debug mode
volatile _q Speed_pu;
volatile uint16_t Speed_rpm;
volatile uint16_t SpeedCntr;
volatile uint16_t SpeedCntMax;
enum SpeedState_e
{
Speed_idle = 0,
Speed_process
};
volatile enum SpeedState_e SpeedState;
// ----------------------------------------------------------------------
// functions
// ----------------------------------------------------------------------
// reset all the variables of BLDC motor control, initialize and link DMA
void BLDC_initWithDMA()
{
// ----------------------------------------------------------------------
// Initialize all voltage and current objects, variables and helpers:
Vphase_pu.As = 0;
Vphase_pu.Bs = 0;
Vphase_pu.Cs = 0;
VdcBus_pu = 0;
VoneByDcBus_pu = 0;
Vpoti_pu = 0;
Iphase_pu.As = 0;
Iphase_pu.Bs = 0;
Iphase_pu.Cs = 0;
// ----------------------------------------------------------------------
// Initialize all state objects, variables and helpers:
STATUS_objectInit(&Status);
CmtnState = Cmtn_A_B;
CmtnTrigger = false;
// ----------------------------------------------------------------------
// Initialize all timing infos:
VirtualTimer = 0;
AlignCntr = 0;
AlignCntMax = DEVICE_ISR_FREQUENCY_kHz*1000/2; // 0.5 second align time
// ----------------------------------------------------------------------
// Initialize all PWM objects, variables and helpers:
BLDC_PWM_objectInit(&Pwm, TIMER_A2_BASE, TIMER_A_CAPTURECOMPARE_REGISTER_2);
Pwm.DutyMax = (uint16_t)((float)UCS_getSMCLK()/(2.0*DEVICE_PWM_FREQUENCY_kHz*1e3)); // 638 Ticks @ 20kHz
// ----------------------------------------------------------------------
// Initialize all controller objects, variables and helpers:
PI_objectInit(&Pi_Idc);
float motorLs_H = MOTOR_LQ_H * 2.0;
float motorRs_OHM = MOTOR_RS_OHM * 2.0;
Pi_Idc.Kp = PI_calcKp(motorLs_H, DEVICE_SHUNT_CURRENT_A, DEVICE_DC_VOLTAGE_V, DEVICE_ISR_PERIDODE_Sec);
Pi_Idc.Ki = PI_calcKi(motorRs_OHM, motorLs_H, DEVICE_ISR_PERIDODE_Sec);
PI_objectInit(&Pi_Speed);
Pi_Speed.Kp = _Q(4.0);
Pi_Speed.Ki = _Q(0.05);
// ----------------------------------------------------------------------
// Initialize all functional, variables and helpers:
RAMP_objectInit(&SpeedRamp);
SpeedRamp.DelayMax = DEVICE_RAMP_ACC_STEPS;
SpeedRamp.StepWidth = _Q(0.001);
SpeedRamp.LowLimit_pu = _Q(0.0);
SpeedRamp.HighLimit_pu = _Q(1.0);
STEP_objectInit(&Step);
Step.CntMax = (DEVICE_PWM_FREQUENCY_kHz*1000) / 2; // 0.5 Sec
Step.IdcRef_pu = _Q(0.25); // 25% of DEVICE_SHUNT_CURRENT
OPENLOOP_objectInit(&OpenLoop);
OpenLoop.Delay = (uint16_t)OPENLOOP_DELAY_TICKS;
OpenLoop.SetpointValue = (uint16_t)OPENLOOP_START_TICKS;
OpenLoop.TargetValue = (uint16_t)OPENLOOP_END_TICKS;
OpenLoop.Min = (uint16_t)OPENLOOP_END_TICKS;
OpenLoop.DoneFlag = false;
CMTN_objectInit(&Cmtn);
// At the instants of phase commutation, high dV/dt and dI/dt glitches may occur due to the direct
// current level or to the parasitic inductance and capacitance of the power board. This can lead to a
// misreading of the computed neutral voltage. This is overcomed by discarding the first few scans
// of the Bemf once a new phase commutation occurs.
Cmtn.NWDelayThres = 6;
Cmtn.NWDelta = 2;
Cmtn.NoiseWindowMax = Cmtn.NWDelayThres - Cmtn.NWDelta;
// ----------------------------------------------------------------------
// Initialize others:
SpeedTarget_pu = _Q(0.25);
Speed_pu = 0;
Speed_rpm = 0;
// Speed control is handled in the main loop @ 5ms.
// Using a counter and a SpeedState - flag in the ISR handles the period
// of the speed control loop in main.c
SpeedCntMax = DEVICE_ISR_FREQUENCY_kHz*1000*0.005; // 5ms;
SpeedCntr = 0;
SpeedState = Speed_idle;
// ----------------------------------------------------------------------
// Initialize DMA:
// Disable the DMA from preempting a Read-Modify-Write Operation in the CPU
DMA_disableTransferDuringReadModifyWrite();
DMA_initParam dmaInitParam = {0};
dmaInitParam.channelSelect = DMA_CHANNEL_0;
dmaInitParam.transferModeSelect = DMA_TRANSFER_REPEATED_BLOCK;
dmaInitParam.transferSize = 8; // 8 ADC channels are used in this example
dmaInitParam.triggerSourceSelect = DMA_TRIGGERSOURCE_24; // Use DMA Trigger Source 24 (ADC12xIFG)
dmaInitParam.transferUnitSelect = DMA_SIZE_SRCWORD_DSTWORD;
dmaInitParam.triggerTypeSelect = DMA_TRIGGER_RISINGEDGE;
DMA_init(&dmaInitParam);
// transfer a block of data from the ADC memory...
DMA_setSrcAddress(DMA_CHANNEL_0,
ADC12_A_getMemoryAddressForDMA(ADC12_A_BASE,
ADC12_A_MEMORY_0),
DMA_DIRECTION_INCREMENT);
// to the global structure "Dma"
DMA_setDstAddress(DMA_CHANNEL_0,
(uint32_t)(uintptr_t)&Dma.VphaseAs_dma, DMA_DIRECTION_INCREMENT);
//Enable DMA channel 0 interrupt
DMA_clearInterrupt(DMA_CHANNEL_0);
DMA_enableInterrupt(DMA_CHANNEL_0);
//Enable transfers on DMA channel 0
DMA_enableTransfers(DMA_CHANNEL_0);
}
// ----------------------------------------------------------------------
// This routine takes ~38us in STATUS_run and STATUS_spin. This is the
// maximum duration allowed @16kHz PWM frequency. Otherwise we would
// miss / delay the TIMER2_A0 ISR to start the ADC correctly aligned.
// For more information, see the info-text at the main.c file.
void BLDC_runCmtnCntl(void)
{
GPIO_setOutputHighOnPin(GPIO_LED_RED); // toggle for debug / timing measurement
// variables used in this ISR locally:
_q duty;
uint16_t pwmTicks;
// ------------------------------------------------------------------------------
// Get the ADC values and transform them to per unit values:
Vphase_pu.As = _Q12toQ(Dma.VphaseAs_dma);
Vphase_pu.Bs = _Q12toQ(Dma.VphaseBs_dma);
Vphase_pu.Cs = _Q12toQ(Dma.VphaseCs_dma);
VdcBus_pu = _Q12toQ(Dma.VdcBus_dma);
Vpoti_pu = _Q12toQ(Dma.Vpoti_dma);
// Measure DC Bus current, subtract the offset and normalize from (-0.5,+0.5) to (-1,+1)
Iphase_pu.As = _Qmpy2(_Q(0.5) - _Q12toQ(Dma.IphaseAs_dma));
Iphase_pu.Bs = _Qmpy2(_Q(0.5) - _Q12toQ(Dma.IphaseBs_dma));
Iphase_pu.Cs = _Qmpy2(_Q(0.5) - _Q12toQ(Dma.IphaseCs_dma));
// ------------------------------------------------------------------------------
// Since only one phase is energized in BLDC, the respective shunt (3-phase shunt measurement
// with the BoosterPack used) must be selected according to the current commutation:
switch(CmtnState){
case Cmtn_A_B: Pi_Idc.Fbk_pu = Iphase_pu.Bs; break;
case Cmtn_A_C: Pi_Idc.Fbk_pu = Iphase_pu.Cs; break;
case Cmtn_B_C: Pi_Idc.Fbk_pu = Iphase_pu.Cs; break;
case Cmtn_B_A: Pi_Idc.Fbk_pu = Iphase_pu.As; break;
case Cmtn_C_A: Pi_Idc.Fbk_pu = Iphase_pu.As; break;
case Cmtn_C_B: Pi_Idc.Fbk_pu = Iphase_pu.Bs; break;
case Cmtn_Align: Pi_Idc.Fbk_pu = Iphase_pu.Bs + Iphase_pu.Cs; break;
default: break;
}
// There are a lot of switch / cases... but its a bit faster than if / else
// and we are going to get everything out of our MSP 430 ;)
// ------------------------------------------------------------------------------
//
switch(Status.PwrFlag){
case STATUS_run:
switch(Status.OperationMode){
case STATUS_lock:
// ------------------------------------------------------------------------------
// reset the speed reference:
SpeedRamp.TargetValue_pu = 0;
SpeedRamp.SetpointValue_pu = 0;
// ------------------------------------------------------------------------------
// reset the Idc PI controller:
Pi_Idc.Ref_pu = 0;
Pi_Idc.Ui = 0;
Pi_Idc.SatFlag = false;
// ------------------------------------------------------------------------------
// reset the Speed PI controller:
Pi_Speed.Ref_pu = 0;
Pi_Speed.Ui = 0;
Pi_Speed.SatFlag = false;
// ------------------------------------------------------------------------------
// reset the open loop parameter:
OpenLoop.Delay = (uint16_t)OPENLOOP_DELAY_TICKS;
OpenLoop.SetpointValue = (uint16_t)OPENLOOP_START_TICKS;
OpenLoop.TargetValue = (uint16_t)OPENLOOP_END_TICKS;
OpenLoop.Min = (uint16_t)OPENLOOP_END_TICKS;
OpenLoop.DoneFlag = false;
OpenLoop.Counter = 0;
// ------------------------------------------------------------------------------
// reset system switches:
AlignCntr = 0;
CmtnTrigger = false;
Status.Aligned = false;
break;
case STATUS_stepResponse:
// ------------------------------------------------------------------------------
// use this state to tune the PI_Idc current controller.
// update the commutation pointer and update IdcRef_pu:
Pi_Idc.Ref_pu = STEP_run(&Step);
CmtnState = Cmtn_A_B;
break;
case STATUS_alignment:
// ------------------------------------------------------------------------------
// update the commutation pointer and update IdcRef_pu:
// TODO: add local ramper
Pi_Idc.Ref_pu = _Q(0.1);
CmtnState = Cmtn_Align;
break;
case STATUS_spin:
// ------------------------------------------------------------------------------
// Switch from open-loop to closed-loop operation by OpenLoop.DoneFlag flag
switch(OpenLoop.DoneFlag){
case false:
switch(Status.Aligned){
case false: // It may be useful to align the motor. Start out of a defined state:
// TODO: at local ramper:
Pi_Idc.Ref_pu = _Q(OPENLOOP_DUTY); // 30% of max current
// open loop current is 30% of DEVICE_SHUNT_CURRENT_A, thus prevent saturation of
// speed controller by limiting the output to the same value:
Pi_Speed.OutMax_pu = _Q(OPENLOOP_DUTY*DEVICE_SHUNT_CURRENT_A); // prevent saturation and limit
// the open loop pulls up to defined rpm
SpeedRamp.TargetValue_pu = _Q(OPENLOOP_END_RPM/MOTOR_MAX_SPD_RPM);
CmtnState = Cmtn_A_B;
CmtnTrigger = false;
// give the shaft some time to settle down:
if(++AlignCntr >= AlignCntMax)
{
AlignCntr = 0;
Status.Aligned = true;
}
break;
case true: // run the open loop start-up:
OPENLOOP_run(&OpenLoop);
CmtnTrigger = OpenLoop.Trigger;
break;
default: break;
}
break;
case true:
CmtnTrigger = Cmtn.Trigger;
SpeedRamp.TargetValue_pu = SpeedTarget_pu;
Pi_Speed.OutMax_pu = _Q(MOTOR_MAX_CURRENT_IDC_A/DEVICE_SHUNT_CURRENT_A);
break;
default: break;
}
// ------------------------------------------------------------------------------
// wrap around the CmtnState in spin mode:
if(true == CmtnTrigger)
{
if(++CmtnState > Cmtn_C_B)
{
CmtnState = Cmtn_A_B;
}
}
// ------------------------------------------------------------------------------
// update speed control state in a defined time interval:
if(++SpeedCntr > SpeedCntMax)
{
SpeedCntr = 0;
SpeedState = Speed_process;
}
// ------------------------------------------------------------------------------
// This module determines the Bemf zero crossing points of a 3-ph BLDC motor based
// on motor phase voltage measurements and then generates the commutation trigger
// points for the 3-ph power inverter switches. It used in closed loop control.
CMTN_run(&Cmtn, Vphase_pu, CmtnState, VirtualTimer);
break;
default: break;
}
// ------------------------------------------------------------------------------
// ramp up or down the speed target value
RAMP_run(&SpeedRamp);
// ------------------------------------------------------------------------------
// pi current control
Pi_Idc.OutMax_pu = VdcBus_pu;
PI_run(&Pi_Idc);
// ------------------------------------------------------------------------------
// calculate duty (pwm is active low, so ticks must be "inverted")
duty = _Qmpy(Pi_Idc.Out_pu, VoneByDcBus_pu);
pwmTicks = Pwm.DutyMax - _Qmpy(Pwm.DutyMax, duty);
BLDC_1xPWM_run(&Pwm, CmtnState, pwmTicks);
break;
case STATUS_stop:
// ------------------------------------------------------------------------------
// update status and turn off all MOSFETs:
Status.OperationMode = STATUS_lock;
GPIO_setOutputLowOnPin(GPIO_DRV_INLA);
GPIO_setOutputLowOnPin(GPIO_DRV_INHB);
GPIO_setOutputLowOnPin(GPIO_DRV_INLB);
break;
default: break;
}
// ------------------------------------------------------------------------------
// Increase virtual timer and force 15 bit wrap around
VirtualTimer++;
VirtualTimer &= 0x7FFF;
GPIO_setOutputLowOnPin(GPIO_LED_RED); // toggle for debug / timing measurement
}
// ----------------------------------------------------------------------
//
void BLDC_runSpeedCntl(void)
{
// ------------------------------------------------------------------------------
// speed calculation, due to computation power this is handled in the main while loop
if(SpeedState == Speed_process)
{
Speed_pu = _Qdiv(SPEED_SCALER, Cmtn.RevPeriod);
Speed_rpm = _Qmpy(MOTOR_MAX_SPD_RPM, Speed_pu);
Pi_Speed.Fbk_pu = Speed_pu;
Pi_Speed.Ref_pu = SpeedRamp.Out_pu;
PI_run(&Pi_Speed);
Pi_Idc.Ref_pu = Pi_Speed.Out_pu;
SpeedState = Speed_idle;
}
}
// ----------------------------------------------------------------------
//
void BLDC_runDecoupling(void)
{
// this is a slow decoupling handled in the main due to computation power.
// if this would be handled in the BLDC_runCmtnCntl routine, we would extend
// the computing time and miss / delay the TIMER2_A0 ISR to start the ADC.
VoneByDcBus_pu = _Qdiv(_Q(1.0), VdcBus_pu);
}
// ----------------------------------------------------------------------
// something...
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// end of file
// ----------------------------------------------------------------------
|
ben5en/MSP430_sensorlessBLDC
|
F5529_sensorlessBLDC/drv8323/DRV8323_defs.h
|
#ifndef DRV8323_DEFS_H_
#define DRV8323_DEFS_H_
#ifdef __cplusplus
extern "C" {
#endif
// ----------------------------------------------------------------------
// Info
// ----------------------------------------------------------------------
/*
*
* Filename: DRV8323_defs.h
*
* Author: (c) 2019, <NAME>
*
* Target: XXX
*
* Notes:
*
*/
// ----------------------------------------------------------------------
// History
// ----------------------------------------------------------------------
// 09.05.2019 - initial programming
// ----------------------------------------------------------------------
// Header Files
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// Defines
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// Register Addresses
// ----------------------------------------------------------------------
//DRV8323 Register Addresses
#define DRV8323_FAULT_STATUS_1_ADDR 0x00
#define DRV8323_VGS_STATUS_2_ADDR 0x01
#define DRV8323_DRIVER_CNTRL_ADDR 0x02
#define DRV8323_GATE_DRIVE_HS_ADDR 0x03
#define DRV8323_GATE_DRIVE_LS_ADDR 0x04
#define DRV8323_OCP_CNTRL_ADDR 0x05
#define DRV8323_CSA_CNTRL_ADDR 0x06
// ----------------------------------------------------------------------
// Global Variables
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// DRV8323 Fault Status Register 1 (address = 0x00)
// ----------------------------------------------------------------------
struct DRV8323_FAULT_STATUS_1_REG_BITS
{ // bit description
uint16_t VDS_LC:1; // 0 overcurrent fault C low-side MOSFET
uint16_t VDS_HC:1; // 1 overcurrent fault C high-side MOSFET
uint16_t VDS_LB:1; // 2 overcurrent fault B low-side MOSFET
uint16_t VDS_HB:1; // 3 overcurrent fault B high-side MOSFET
uint16_t VDS_LA:1; // 4 overcurrent fault A low-side MOSFET
uint16_t VDS_HA:1; // 5 overcurrent fault A high-side MOSFET
uint16_t OTSD:1; // 6 overtemperature shutdown
uint16_t UVLO:1; // 7 undervoltage lockout fault
uint16_t GDF:1; // 8 gate drive fault
uint16_t VDS_OCP:1; // 9 VDS overcurrent fault
uint16_t FAULT:1; // 10 latched fault
uint16_t Reserved:5; // 15-11
};
typedef union {
uint16_t all;
struct DRV8323_FAULT_STATUS_1_REG_BITS bit;
} DRV8323_FAULT_STATUS_1_REG_t;
// ----------------------------------------------------------------------
// DRV8323 Fault Status Register 2 (address = 0x01)
// ----------------------------------------------------------------------
struct DRV8323_VGS_STATUS_2_REG_BITS
{ // bit description
uint16_t VGS_LC:1; // 0 gate drive fault C low-side MOSFET
uint16_t VGS_HC:1; // 1 gate drive fault C high-side MOSFET
uint16_t VGS_LB:1; // 2 gate drive fault B low-side MOSFET
uint16_t VGS_HB:1; // 3 gate drive fault B high-side MOSFET
uint16_t VGS_LA:1; // 4 gate drive fault A low-side MOSFET
uint16_t VGS_HA:1; // 5 gate drive fault A high-side MOSFET
uint16_t CPUV:1; // 6 charge pump undervoltage fault
uint16_t OTW:1; // 7 overtemperature warning
uint16_t SC_OC:1; // 8 overcurrent on phase C sense amplifier
uint16_t SB_OC:1; // 9 overcurrent on phase B sense amplifier
uint16_t SA_OC:1; // 10 overcurrent on phase A sense amplifier
uint16_t Reserved:5; // 15-11
};
typedef union {
uint16_t all;
struct DRV8323_VGS_STATUS_2_REG_BITS bit;
} DRV8323_VGS_STATUS_2_REG_t;
// ----------------------------------------------------------------------
// DRV8323 Driver Control Register (address = 0x02)
// ----------------------------------------------------------------------
enum Flt{
drv_leaveFaults = 0,
drv_clrFaults = 1
};
enum Break{
drv_breakDisable = 0,
drv_breakEnable = 1
};
enum Coast{
drv_coastDisable = 0,
drv_coastEnable = 1
};
enum _1PWM_Dir{
drv_1xPWM_noChangeDir = 0,
drv_1xPWM_changeDir = 1
};
enum _1xPWM{
drv_1xPWM_synch = 0,
drv_1xPWM_asynch = 1
};
enum PWM_mode{
drv_PWM_mode_6 = 0,
drv_PWM_mode_3 = 1,
drv_PWM_mode_1 = 2,
drv_PWM_modeIndpt = 3
};
enum OTW{
drv_otw_no_report = 0,
drv_otw_report = 1
};
enum GateFault{
drv_gateDrive_faultEnable = 0,
drv_gateDrive_faultDisable = 1
};
enum CPumpFault{
drv_chargePump_faultEnable = 0,
drv_chargePump_faultDisable = 1
};
struct DRV8323_DRIVER_CNTRL_REG_BITS
{ // bit description
enum Flt CLR_FLT:1; // 0 clear latched fault flags
enum Break BRAKE:1; // 1 all low side MOSFETs on when in 1x PWM
enum Coast COAST:1; // 2 all MOSFETs in Hi-Z state
enum _1PWM_Dir PWM_DIR_1:1; // 3
enum _1xPWM PWM_COM_1:1; // 4
enum PWM_mode PWM_MODE:2; // 6-5 PWM Mode
enum OTW OTW_REP:1; // 7
enum GateFault DIS_GDF:1; // 8 enable gate drive fault
enum CPumpFault DIS_CPUV:1; // 9 enable charge pump fault
uint16_t Reserved:6; // 15-10
};
typedef union {
uint16_t all;
struct DRV8323_DRIVER_CNTRL_REG_BITS bit;
} DRV8323_DRIVER_CNTRL_REG_t;
// ----------------------------------------------------------------------
// DRV8323 Gate Drive HS Register (address = 0x03)
// ----------------------------------------------------------------------
enum Lock{
drv_unlock = 3,
drv_lock = 6
};
enum IdriveP_Hs{
drv_idriveP_hs_10mA = 0,
drv_idriveP_hs_30mA = 1,
drv_idriveP_hs_60mA = 2,
drv_idriveP_hs_80mA = 3,
drv_idriveP_hs_120mA = 4,
drv_idriveP_hs_140mA = 5,
drv_idriveP_hs_170mA = 6,
drv_idriveP_hs_190mA = 7,
drv_idriveP_hs_260mA = 8,
drv_idriveP_hs_330mA = 9,
drv_idriveP_hs_370mA = 10,
drv_idriveP_hs_440mA = 11,
drv_idriveP_hs_570mA = 12,
drv_idriveP_hs_680mA = 13,
drv_idriveP_hs_820mA = 14,
drv_idriveP_hs_1000mA = 15
};
enum IdriveN_Hs{
drv_idriveN_hs_20mA = 0,
drv_idriveN_hs_60mA = 1,
drv_idriveN_hs_120mA = 2,
drv_idriveN_hs_160mA = 3,
drv_idriveN_hs_240mA = 4,
drv_idriveN_hs_280mA = 5,
drv_idriveN_hs_340mA = 6,
drv_idriveN_hs_380mA = 7,
drv_idriveN_hs_520mA = 8,
drv_idriveN_hs_660mA = 9,
drv_idriveN_hs_740mA = 10,
drv_idriveN_hs_880mA = 11,
drv_idriveN_hs_1140mA = 12,
drv_idriveN_hs_1360mA = 13,
drv_idriveN_hs_1640mA = 14,
drv_idriveN_hs_2000mA = 15
};
struct DRV8323_GATE_DRIVE_HS_REG_BITS
{ // bit description
enum IdriveN_Hs IDRIVEN_HS:4; // 3:0 high side gate driver peak source current
enum IdriveP_Hs IDRIVEP_HS:4; // 7:4 high side gate driver peak sink current
enum Lock _LOCK:3; // 10-8 lock register write
uint16_t Reserved:5; // 15-11
};
typedef union {
uint16_t all;
struct DRV8323_GATE_DRIVE_HS_REG_BITS bit;
} DRV8323_GATE_DRIVE_HS_REG_t;
// ----------------------------------------------------------------------
// DRV8323 Gate Drive LS Register (address = 0x04)
// ----------------------------------------------------------------------
enum Tdrive{
drv_tdrive_500nS = 0,
drv_tdrive_1000nS = 1,
drv_tdrive_2000nS = 2,
drv_tdrive_4000nS = 3
};
enum IdriveP_Ls{
drv_idriveP_ls_10mA = 0,
drv_idriveP_ls_30mA = 1,
drv_idriveP_ls_60mA = 2,
drv_idriveP_ls_80mA = 3,
drv_idriveP_ls_120mA = 4,
drv_idriveP_ls_140mA = 5,
drv_idriveP_ls_170mA = 6,
drv_idriveP_ls_190mA = 7,
drv_idriveP_ls_260mA = 8,
drv_idriveP_ls_330mA = 9,
drv_idriveP_ls_370mA = 10,
drv_idriveP_ls_440mA = 11,
drv_idriveP_ls_570mA = 12,
drv_idriveP_ls_680mA = 13,
drv_idriveP_ls_820mA = 14,
drv_idriveP_ls_1000mA = 15
};
enum IdriveN_Ls{
drv_idriveN_ls_20mA = 0,
drv_idriveN_ls_60mA = 1,
drv_idriveN_ls_120mA = 2,
drv_idriveN_ls_160mA = 3,
drv_idriveN_ls_240mA = 4,
drv_idriveN_ls_280mA = 5,
drv_idriveN_ls_340mA = 6,
drv_idriveN_ls_380mA = 7,
drv_idriveN_ls_520mA = 8,
drv_idriveN_ls_660mA = 9,
drv_idriveN_ls_740mA = 10,
drv_idriveN_ls_880mA = 11,
drv_idriveN_ls_1140mA = 12,
drv_idriveN_ls_1360mA = 13,
drv_idriveN_ls_1640mA = 14,
drv_idriveN_ls_2000mA = 15
};
struct DRV8323_GATE_DRIVE_LS_REG_BITS
{ // bit description
enum IdriveN_Ls IDRIVEN_LS:4; // 3:0 low side gate driver peak source current
enum IdriveP_Ls IDRIVEP_LS:4; // 7:4 low side gate driver peak sink current
enum Tdrive TDRIVE:2; // 9:8 gate driver peak source time
uint16_t CBC:1; // 10
uint16_t Reserved:5; // 15-11
};
typedef union {
uint16_t all;
struct DRV8323_GATE_DRIVE_LS_REG_BITS bit;
} DRV8323_GATE_DRIVE_LS_REG_t;
// ----------------------------------------------------------------------
// DRV8323 OCP Control Register (address = 0x05)
// ----------------------------------------------------------------------
enum Tretry{
drv_retry_time_4ms = 0,
drv_retry_time_50us = 1
};
enum DeadTime{
drv_deadTime_50nS = 0,
drv_deadTime_100nS = 1,
drv_deadTime_200nS = 2,
drv_deadTime_400nS = 3,
};
enum OcpMode{
drv_ocp_mode_latcheFault = 0,
drv_ocp_mode_autoRetryFault = 1,
drv_ocp_mode_reportNoAction = 2,
drv_ocp_mode_noProtection = 3
};
enum OcpDeg{
drv_ocp_deg_2us = 0,
drv_ocp_deg_4us = 1,
drv_ocp_deg_6us = 2,
drv_ocp_deg_8us
};
enum VdsLvl{
drv_vds_lvl_60mV = 0,
drv_vds_lvl_130mV = 1,
drv_vds_lvl_200mV = 2,
drv_vds_lvl_260mV = 3,
drv_vds_lvl_310mV = 4,
drv_vds_lvl_450mV = 5,
drv_vds_lvl_530mV = 6,
drv_vds_lvl_600mV = 7,
drv_vds_lvl_680mV = 8,
drv_vds_lvl_750mV = 9,
drv_vds_lvl_940mV = 10,
drv_vds_lvl_1130mV = 11,
drv_vds_lvl_1300mV = 12,
drv_vds_lvl_1500mV = 13,
drv_vds_lvl_1700mV = 14,
drv_vds_lvl_1880mV = 15
};
struct DRV8323_OCP_CNTRL_REG_BITS
{ // bit description
enum VdsLvl VDS_LVL:4; // 3-0
enum OcpDeg OCP_DEG:2; // 5-4 overcurrent deglitch time
enum OcpMode OCP_MODE:2; // 7-6 overcurrent action
enum DeadTime DEAD_TIME:2; // 9-8
enum Tretry TRETRY:1; // 10 VDS_OCP and SEN_OCP retry time
uint16_t Reserved:5; // 15-11
};
typedef union {
uint16_t all;
struct DRV8323_OCP_CNTRL_REG_BITS bit;
} DRV8323_OCP_CNTRL_REG_t;
// ----------------------------------------------------------------------
// DRV8323 CSA Control Register (DRV8323x Only) (address = 0x06)
// ----------------------------------------------------------------------
enum CsaFet{
drv_input_SPx = 0,
drv_input_SHx = 1
};
enum Vref{
drv_vref_div_1 = 0,
drv_vref_div_2 = 1
};
enum LsRef{
drv_vds_ocp_SHx_SPx = 0,
drv_vds_ocp_SHx_SNx = 1
};
enum Gain{
drv_gain_5 = 0,
drv_gain_10 = 1,
drv_gain_20 = 2,
drv_gain_40 = 3
};
enum OcFault{
drv_oc_faultEnable = 0,
drv_oc_faultDisable = 1
};
enum SenseCal{
drv_normal_sense = 0,
drv_short_sense = 1
};
enum SenseLvl{
drv_ocp_250mV = 0,
drv_ocp_500mV = 1,
drv_ocp_750mV = 2,
drv_ocp_1000mV = 3
};
struct DRV8323_CSA_CNTRL_REG_BITS
{ // bit description
enum SenseLvl SEN_LVL:2; // 1-0 sense OCP
enum SenseCal CSA_CAL_C:1; // 2 C side amplifier setting
enum SenseCal CSA_CAL_B:1; // 3 B side amplifier setting
enum SenseCal CSA_CAL_A:1; // 4 A side amplifier setting
enum OcFault DIS_SEN:1; // 5 overcurrent fault action
enum Gain CSA_GAIN:2; // 7-6 shunt amplifier gain
enum LsRef LS_REF:1; // 8
enum Vref VREF_DIV:1; // 9 amplifier reference setting
enum CsaFet CSA_FET:1; // 10 amplifier setting
uint16_t Reserved:5; // 15-11
};
typedef union {
uint16_t all;
struct DRV8323_CSA_CNTRL_REG_BITS bit;
} DRV8323_CSA_CNTRL_REG_t;
// ----------------------------------------------------------------------
// Global structure
// ----------------------------------------------------------------------
typedef struct {
DRV8323_FAULT_STATUS_1_REG_t Fault_Status_1;
DRV8323_VGS_STATUS_2_REG_t VGS_Status_2;
DRV8323_DRIVER_CNTRL_REG_t Driver_Control;
DRV8323_GATE_DRIVE_HS_REG_t Gate_Drive_HS;
DRV8323_GATE_DRIVE_LS_REG_t Gate_Drive_LS;
DRV8323_OCP_CNTRL_REG_t OCP_Control;
DRV8323_CSA_CNTRL_REG_t CSA_Control;
// DRV8323 variables
uint16_t fault,
ScsPort,
ScsPin;
// change following register name to use this
// code with another controller platform
// volatile struct SPI_REGS *SpiRegs;
} DRV8323_VARS_t;
#define DRV8323_DEFAULTS { \
0, /* fault_status */ \
0, /* vgs_status */ \
0, /* driver_cntrl */ \
0, /* gate_cntrl_hs */ \
0, /* gate_cntrl_ls */ \
0, /* ocp_cntrl */ \
0, /* csa_cntrl */ \
\
0, /* fault */ \
0, /* ScsPort */ \
0, /* ScsPin */ \
/*&SpiaRegs */ /* SPI Register - change in main */ \
}
// ----------------------------------------------------------------------
// something...
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// End of file
// ----------------------------------------------------------------------
#ifdef __cplusplus
}
#endif /* extern "C" */
#endif /* DRV8323_DEFS_H_ */
|
ben5en/MSP430_sensorlessBLDC
|
F5529_sensorlessBLDC/Serial_Cmd_Monitor.h
|
<reponame>ben5en/MSP430_sensorlessBLDC
#ifndef SERIAL_CMD_MONITOR_H_
#define SERIAL_CMD_MONITOR_H_
void ClearBufferRelatedParam();
void receivedDataCommand(unsigned char d);
#endif
|
ben5en/MSP430_sensorlessBLDC
|
F5529_sensorlessBLDC/config.h
|
<filename>F5529_sensorlessBLDC/config.h<gh_stars>1-10
#ifndef CONFIG_H_
#define CONFIG_H_
#ifdef __cplusplus
extern "C" {
#endif
// ----------------------------------------------------------------------
// info and license
// ----------------------------------------------------------------------
//
// filename: config.h
//
// MIT License
//
// Copyright (c) 2019 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// target: Texas Instruments MSP430F5529LP with BOOSTXL-DRV8323RS EVM
//
// ----------------------------------------------------------------------
// history
// ----------------------------------------------------------------------
// 17.08.2019 - initial programming
// ----------------------------------------------------------------------
// header files
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// #defines
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// global variables
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// functions
// ----------------------------------------------------------------------
extern void MSP430F5529LP_init(void);
// ----------------------------------------------------------------------
// something...
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// end of file
// ----------------------------------------------------------------------
#ifdef __cplusplus
}
#endif /* extern "C" */
#endif /* CONFIG_H_ */
|
ben5en/MSP430_sensorlessBLDC
|
F5529_sensorlessBLDC/bldc/pi.h
|
<reponame>ben5en/MSP430_sensorlessBLDC
#ifndef BLDC_PI_H_
#define BLDC_PI_H_
#ifdef __cplusplus
extern "C" {
#endif
// ----------------------------------------------------------------------
// info and license
// ----------------------------------------------------------------------
//
// filename: pi.h
//
// MIT License
//
// Copyright (c) 2019 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// target: Texas Instruments MSP430
//
// ----------------------------------------------------------------------
// history
// ----------------------------------------------------------------------
// 03.09.2019 - initial programming
// ----------------------------------------------------------------------
// header files
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// #defines
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// global variables
// ----------------------------------------------------------------------
typedef volatile struct
{
_q Kp; // the proportional gain for the PI controller
_q Ki; // the integral gain for the PI controller
_q Ref_pu; // the reference value [pu]
_q Fbk_pu; // the feedback value [pu]
_q OutMax_pu; // the saturation high limit for the controller output [pu]
_q OutMin_pu; // the saturation low limit for the controller output [pu]
_q Out_pu; // the controller output [pu]
_q Ui; // the integrator value for the PI controller
bool SatFlag; // flag to signal controller saturation
} PI_t;
// ----------------------------------------------------------------------
// functions
// ----------------------------------------------------------------------
// function to set default values for the object
inline void PI_objectInit(volatile PI_t *pPi_obj)
{
PI_t *obj = (PI_t *)pPi_obj;
// Function initializes the object with default values
obj->Kp = _Q(1.0);
obj->Ki = 0;
obj->Fbk_pu = 0;
obj->Ref_pu = 0;
obj->Out_pu = 0;
obj->OutMax_pu = 0;
obj->OutMin_pu = 0;
obj->Ui = 0;
obj->SatFlag = false;
}
// ----------------------------------------------------------------------
//
inline void PI_run(volatile PI_t *pPi_obj)
{
PI_t *obj = (PI_t *)pPi_obj;
_q up, error, preOut;
// Compute the controller error
error = obj->Ref_pu - obj->Fbk_pu;
// Compute the proportional term
up = _Qmpy(obj->Kp, error);
// Compute the integral term in parallel form and saturate
obj->Ui = _Qsat(obj->Ui + _Qmpy(obj->Ki, up), obj->OutMax_pu, obj->OutMin_pu);
preOut = up + obj->Ui;;
// Saturate the output
obj->Out_pu = _Qsat(preOut, obj->OutMax_pu, obj->OutMin_pu);
// if saturation flag is needed, comment out:
// obj->SatFlag = (out == preOut) ? false : true;
}
// ----------------------------------------------------------------------
//
inline _q PI_calcKp(float Ls_H, float deviceCurrent_A, float deviceVoltage_V,
float deviceCtrlPeriode_Sec)
{
// calculation is based on "Betragsoptimum"
// Kp = Ls/(2*tau)
float x1;
float y1;
_q Kp;
// multiplication with deviceCurrent_A is to get per unit values
x1 = Ls_H * deviceCurrent_A;
y1 = 2.0 * deviceCtrlPeriode_Sec;
// multiplication with deviceVoltage_V is to get per unit values
y1 = y1 * deviceVoltage_V;
Kp = _Q(x1 / y1);
return Kp;
}
// ----------------------------------------------------------------------
//
inline _q PI_calcKi(float Rs_Ohm, float Ls_H, float deviceCtrlPeriode_Sec)
{
// calculation is based on "TI - MotorWare's documentation"
float RsByLs = Rs_Ohm / Ls_H;
_q Ki = _Q(RsByLs * deviceCtrlPeriode_Sec);
return Ki;
}
// ----------------------------------------------------------------------
// something...
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// end of file
// ----------------------------------------------------------------------
#ifdef __cplusplus
}
#endif /* extern "C" */
#endif /* BLDC_PI_H_ */
|
ben5en/MSP430_sensorlessBLDC
|
F5529_sensorlessBLDC/bldc/ramp.h
|
<gh_stars>1-10
#ifndef BLDC_RAMP_H_
#define BLDC_RAMP_H_
#ifdef __cplusplus
extern "C" {
#endif
// ----------------------------------------------------------------------
// info and license
// ----------------------------------------------------------------------
//
// filename: ramp.h
//
// MIT License
//
// Copyright (c) 2019 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// target: Texas Instruments MSP430
//
// This file is mainly build up on the Texas Instruments "maths-blocks" found
// in the C2000 control suite and adopted to work with Q-Formats and MPS430 types.
//
// ----------------------------------------------------------------------
// history
// ----------------------------------------------------------------------
// 02.09.2019 - initial programming
// ----------------------------------------------------------------------
// header files
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// #defines
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// global variables
// ----------------------------------------------------------------------
typedef volatile struct
{
_q LowLimit_pu; // Parameter: Minimum limit [pu]
_q HighLimit_pu; // Parameter: Maximum limit [pu]
_q TargetValue_pu; // Input: Target value [pu]
_q SetpointValue_pu; // Parameter: Setpoint value [pu]
_q Out_pu; // Output: ramp output value [pu]
_q StepWidth; // Parameter: ramp step width [global Q]
uint16_t DelayMax; // Parameter: ramp delay for next iteration
uint16_t DelayCnt; // Variable: Counter for delay
bool EqualFlag; // Output: Flag output (Q0) - independently with global Q
} RAMP_t;
// ----------------------------------------------------------------------
// functions
// ----------------------------------------------------------------------
// function to set default values for the object
inline void RAMP_objectInit(volatile RAMP_t *ramp_obj)
{
RAMP_t *obj = (RAMP_t*)ramp_obj;
obj->LowLimit_pu = _Q(-1.0);
obj->HighLimit_pu = _Q(1.0);
obj->TargetValue_pu = 0;
obj->SetpointValue_pu = 0;
obj->Out_pu = 0;
obj->StepWidth = _Q(0.001);
obj->DelayMax = 10;
obj->DelayCnt = 0;
obj->EqualFlag = false;
}
// ----------------------------------------------------------------------
//
inline void RAMP_run(volatile RAMP_t *ramp_obj)
{
RAMP_t *obj = (RAMP_t*)ramp_obj;
_q error = obj->TargetValue_pu - obj->SetpointValue_pu;
if (_Qabs(error) >= obj->StepWidth)
{
obj->EqualFlag = false;
if (++obj->DelayCnt >= obj->DelayMax)
{
if (obj->TargetValue_pu >= obj->SetpointValue_pu)
{
obj->SetpointValue_pu += obj->StepWidth;
}
else
{
obj->SetpointValue_pu -= obj->StepWidth;
}
obj->SetpointValue_pu = _Qsat(obj->SetpointValue_pu, obj->HighLimit_pu, obj->LowLimit_pu);
obj->DelayCnt = 0;
}
}
else
{
obj->EqualFlag = true;
}
obj->Out_pu = obj->SetpointValue_pu;
}
// ----------------------------------------------------------------------
// something...
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// end of file
// ----------------------------------------------------------------------
#ifdef __cplusplus
}
#endif /* extern "C" */
#endif /* BLDC_RAMP_H_ */
|
ben5en/MSP430_sensorlessBLDC
|
F5529_sensorlessBLDC/Serial_Cmd_Monitor.c
|
<reponame>ben5en/MSP430_sensorlessBLDC
#include <msp430.h>
#include "Serial_Cmd_Monitor.h"
#define TEMP_THRESHOLD 4
#define RW_CMD 0x80
#define EXTENSION_BYTE 0x07
//PERIPHERAL
//
//RW CMD TYPE
#define READ 1
#define WRITE 0
//ENDIANNESS
#define BIG_ENDIAN 1
#define LITTLE_ENDIAN 0
//ADDRESSIBLE SIZE
#define ADDRESSIBLE_32_BIT 1
#define ADDRESSIBLE_16_BIT 0
// override these depends on target: CMD_BUFFER_SIZE = 5 + sizeOfMauIn8BitByte * 63
#define CMD_BUFFER_SIZE 68 //1 + 4 + 63 = 68
unsigned char gInCmdBuffer[CMD_BUFFER_SIZE];
unsigned short gInCmdBufferIdx = 0;
volatile unsigned short gInCmdSkipCount;
void ClearBufferRelatedParam();
// override these depends on target
int GetTargetEndianness()
{
return LITTLE_ENDIAN;
}
// override these depends on target
void Write8bitByteToCOM(unsigned char c)
{
// uartTxByte(c & 0xff);
/* USCI_A0 TX buffer ready? */
while(!(UCA0IFG&UCTXIFG));
UCA0TXBUF = (c & 0xff);
}
int GetSizeOfMAUIn8bitByte()
{
unsigned char maxMAUValue = (unsigned char)(-1);
switch (maxMAUValue)
{
case 0xff:
return 1;
case 0xffff:
return 2;
default:
return 0;
}
}
int WriteToCmdBuffer(unsigned char* buf, unsigned short* bufIdx, unsigned char d)
{
if ( (*bufIdx) < CMD_BUFFER_SIZE )
{
buf[*bufIdx] = d & 0xff;
(*bufIdx)++;
return 0;
}
return 1;
}
void ResetInCmdBuffer()
{
gInCmdBufferIdx = 0;
}
int WriteByteToInCmdBuffer(unsigned char d)
{
return WriteToCmdBuffer(gInCmdBuffer, &gInCmdBufferIdx, d);
}
int GetTransferSizeInMAU() //transfer size refer to the words to read/write of a given cmd, not the number of bytes for the whole cmd packet
{
return (gInCmdBuffer[0] & 0x3f);
}
int VerifyInputCmdHeaders()
{
return ((gInCmdBuffer[0] & 0x80) == 0x80) ? 0 : 1;
}
int GetInputCmdType()
{
return (gInCmdBuffer[0] & 0x80);
}
int GetRWFlag()//equivalent to endianness on the MAU in transmission
{
int ret = ((gInCmdBuffer[0] >> 6) & 0x1); //
return ret;
}
unsigned char* GetInCmdAddress()
{
unsigned char* addr = 0;
unsigned long addr_value = 0;
int i = 0;
int addressSize = 4; // always use 32bit address
for (; i < addressSize; i++)
{
addr_value |= (unsigned long)( gInCmdBuffer[1 + i] << 8 * (addressSize - 1 - i) ); //big endian
}
addr = (unsigned char*) addr_value;
return addr;
}
void WriteMAUToCOM(unsigned char d)
{
int MAUSize = GetSizeOfMAUIn8bitByte();
switch (MAUSize)
{
case 1:
Write8bitByteToCOM(d);
break;
case 2:
{
unsigned char MAU[2];
MAU[0] = (unsigned char)(d & 0xff);
MAU[1] = (unsigned char)(d >> 8);
if (GetTargetEndianness() == LITTLE_ENDIAN)
{
Write8bitByteToCOM(MAU[0]);
Write8bitByteToCOM(MAU[1]);
} else {
Write8bitByteToCOM(MAU[1]);
Write8bitByteToCOM(MAU[0]);
}
}
break;
default://only handles 8bit, 16bit MAU
break;
}
}
unsigned char GetWriteCmdDataMAU(int idx)
{
unsigned char startIdx = 1 + 4;
unsigned char val = 0;
int MAUSize = GetSizeOfMAUIn8bitByte();
int byteOffset = idx*MAUSize;
switch (MAUSize)
{
case 1:
val = gInCmdBuffer[startIdx + byteOffset];
break;
case 2:
if (GetTargetEndianness() == LITTLE_ENDIAN)
{
val = ( gInCmdBuffer[startIdx + byteOffset + 1] << 8 ) | gInCmdBuffer[startIdx + byteOffset];
} else {
val = ( gInCmdBuffer[startIdx + byteOffset] | gInCmdBuffer[startIdx + byteOffset + 1] << 8 );
}
break;
default://only handles 8bit, 16bit MAU
break;
}
return val;
}
void ClearBufferRelatedParam()
{
gInCmdSkipCount = 0;
gInCmdBufferIdx = 0;
}
void MemAccessCmd(int RW)
{
unsigned short MAUsToRead = 0;
unsigned char dataChar = 0;
unsigned char* addr = GetInCmdAddress();
unsigned short i, j;
for ( j = 0; j < 1; j++ )
{
Write8bitByteToCOM(gInCmdBuffer[j]);
}
MAUsToRead = GetTransferSizeInMAU();
for ( i = 0; i < MAUsToRead; i++ )
{
if (RW == READ)
{
dataChar = *(addr + i);
WriteMAUToCOM(dataChar);
} else { //WRITE
dataChar = GetWriteCmdDataMAU(i);
*(addr + i) = dataChar;
}
}
}
int ProcessCommand()
{
if ( VerifyInputCmdHeaders() )
{
return 1;
}
switch ( GetInputCmdType() )
{
case RW_CMD:
MemAccessCmd(GetRWFlag());
break;
default:
return 1;
}
return 0;
}
void receivedDataCommand(unsigned char d) // only lower byte will be used even if MAU is bigger than 1 byte
{
WriteByteToInCmdBuffer(d);
if (gInCmdSkipCount > 0)
{
gInCmdSkipCount--;
return;
}
if (gInCmdBufferIdx > 0 && gInCmdSkipCount == 0)
{ //wrong input header, clear cmd buffer
if ( VerifyInputCmdHeaders() )
{
ClearBufferRelatedParam();
return;
}
if (gInCmdBufferIdx == 1) {
if (GetRWFlag() == WRITE)
{
gInCmdSkipCount = 4 - 1 + GetTransferSizeInMAU() * GetSizeOfMAUIn8bitByte();
} else {
gInCmdSkipCount = 4 - 1 ;
}
} else {
ProcessCommand();
ClearBufferRelatedParam();
}
return;
}
}
|
ben5en/MSP430_sensorlessBLDC
|
F5529_sensorlessBLDC/bldc/openLoop.h
|
#ifndef BLDC_OPENLOOP_H_
#define BLDC_OPENLOOP_H_
#ifdef __cplusplus
extern "C" {
#endif
// ----------------------------------------------------------------------
// info and license
// ----------------------------------------------------------------------
//
// filename: openLoop.h
//
// MIT License
//
// Copyright (c) 2019 <NAME>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// target: Texas Instruments MSP430
//
// This file is mainly build up on the Texas Instruments "maths-blocks" found
// in the C2000 control suite and adopted to work with Q-Formats and MPS430 types.
//
// ----------------------------------------------------------------------
// history
// ----------------------------------------------------------------------
// 08.09.2019 - initial programming
// ----------------------------------------------------------------------
// header files
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// #defines
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// global variables
// ----------------------------------------------------------------------
typedef volatile struct
{
uint16_t Delay; // Parameter: ramp delay for next iteration
uint16_t DelayCnt; // Variable: Counter for delay
uint16_t Counter; // Variable: Period counter
uint16_t TargetValue; // Input: target period
uint16_t SetpointValue; // Output: current ramp value
uint16_t Min; // Parameter: Minimum ramp output
bool Trigger; // Output: commutation trigger flag
bool DoneFlag; // Output: Flag output if ramp reached its obj->TargetValue value
} OPENLOOP_t;
// ----------------------------------------------------------------------
// functions
// ----------------------------------------------------------------------
// function to set default values for the object
inline void OPENLOOP_objectInit(volatile OPENLOOP_t *ramp3_obj)
{
OPENLOOP_t *obj = (OPENLOOP_t*)ramp3_obj;
obj->Delay = 0;
obj->DelayCnt = 0;
obj->Counter = 0;
obj->SetpointValue = 0;
obj->Min = 50;
obj->Trigger = false;
obj->DoneFlag = false;
}
// ----------------------------------------------------------------------
// this is a ramp-down function for open-loop start up.
// the function triggers with a decreasing period.
inline void OPENLOOP_run(volatile OPENLOOP_t *ramp3_obj)
{
OPENLOOP_t *obj = (OPENLOOP_t*)ramp3_obj;
obj->Trigger = false;
if (obj->SetpointValue == obj->TargetValue)
{
obj->DoneFlag = true;
}
else
{
obj->DelayCnt++; // ramp down delay counter
if (obj->DelayCnt >= obj->Delay)
{
obj->DelayCnt = 0;
obj->SetpointValue--; // decreasing of trigger period
if (obj->SetpointValue < obj->Min)
{
obj->SetpointValue = obj->Min; // limit to min period
}
}
}
if(++obj->Counter >= obj->SetpointValue)
{
obj->Trigger = true;
obj->Counter = 0;
}
}
// ----------------------------------------------------------------------
// something...
// ----------------------------------------------------------------------
// ----------------------------------------------------------------------
// end of file
// ----------------------------------------------------------------------
#ifdef __cplusplus
}
#endif /* extern "C" */
#endif /* BLDC_OPENLOOP_H_ */
|
JavalParel/AEM
|
Newton-Raphson.c
|
#include<stdio.h>
float expression(float x)
{
//enter your expression here
//For power - pow(base, power)
//for base 10 use- log10(x)
return (pow(x,4)-12*x+7);
}
float intigration(float x)
{
//enter your intigrated expression here
//For power - pow(base, power)
//for base 10 use- log10(x)
return (4*pow(x,3)-12);
}
int main(){
int sel,j;
float eq,x0,f[100],fi[100],start,x[100];
printf("1 For x0\n2 For enter starting point\n");
scanf("%d",&sel);
if(sel==1)
{
printf("Enter x0 :- ");
scanf("%f",&x0);
}
else if(sel==2)
{
printf("Enter starting point :- ");
scanf("%f",&start);
if(expression(start)>=0){
do{
x0=start;
j=start;
eq=expression(x0);
printf("f(%d) = %.2f\n",j,expression(x0) );
if(eq>0)
{
x0=start;
}
start++;
j++;
}while(eq>=0);
}
else{
do{
x0=start;
eq=expression(x0);
printf("f(%d) = %.2f\n",x0,expression(x0) );
if(eq>0)
{
x0=start;
}
start++;
}while(eq<0);}
}
printf("x0 = %.0f\n",x0);
for (int i = 0; i < 10; ++i)
{
printf("f(%d) = %f \tf'(%d) = %f\t",i,expression(x0),i,intigration(x0) );
x[i]=x0-(expression(x0)/intigration(x0));
printf("x%d = %f\n",i,x[i]);
x0=x[i];
}
}
|
JavalParel/AEM
|
Bi-Section.c
|
#include<stdio.h>
#include<math.h>
float expression(float x)
{
//enter your expression here
//For power use like that - pow(base, exp)
return (pow(x,5)-3*x*x+6*x-15);
}
int main(){
int x,itr,start,a,b,j;
float xn[100],f[100],a_new,b_new,eq;
printf("Enter starting point :- ");
scanf("%d",&start);
printf("Enter Number of Iteration :- ");
scanf("%d",&itr);
if(expression(start)>=0){
do{
x=start;
j=start;
eq=expression(x);
printf("f(%d) = %.2f\n",j,expression(x) );
if(eq>0)
{
a=start-1;
b=start;
}
start++;
j++;
}while(eq>=0);
}
else{
do{
x=start;
eq=expression(x);
printf("f(%d) = %.2f\n",x,expression(x) );
if(eq>0)
{
a=start-1;
b=start;
}
start++;
}while(eq<0);}
printf("a = %d\tb = %d\n",a,b);
a_new=a;
b_new=b;
for (int i = 1; i <= itr; i++)
{
xn[i]=(a_new+b_new)/2;
eq=expression(xn[i]);
printf("x%d = %f\t ",i,xn[i]);
if(eq<0)
a_new=xn[i];
else
b_new=xn[i];
printf("a = %f\t b = %f\t ",a_new,b_new);
f[i]=eq;
printf("f(%d) = %f\n",i,f[i] );
}
printf("Iteration\tx\t\tf(x)\n");
for (int i = 1; i <= itr; ++i)
{
printf(" %d\t\t%f\t%f\n",i,xn[i],f[i] );
}
}
|
JavalParel/AEM
|
Elulers.c
|
#include<stdio.h>
#include<math.h>
float equation(float x,float y)
{
return ((y-x)/(y+x));
}
int main(){
float x[100],y[100],dydx[100],y_new[100],h;
printf("Enter value of y :-");
scanf("%f",&y[0]);
printf("Enter value of x :-");
scanf("%f",&x[0]);
printf("Enter value of h :-");
scanf("%f",&h);
y_new[0]=y[0];
printf("Itt \t h \t\t x \t\t y \t\t dy/dx \t\t y_new\n");
for (int i = 0; i < 11; ++i)
{
dydx[i+1]=equation(x[i],y[i]);
y_new[i+1]=y_new[i]+h*dydx[i+1];
printf("%d \t %f \t %f \t %f \t %f \t %f\n",i,h,x[i],y[i],dydx[i+1],y_new[i+1] );
x[i+1]=h+x[i];
y[i+1]=y_new[i+1];
}
}
|
JavalParel/AEM
|
Gauss-Seidal.c
|
<reponame>JavalParel/AEM<filename>Gauss-Seidal.c
#include<stdio.h>
int main(){
int a[5],b[5],c[5],d[5];
float x[100],y[100],z[100],xn,yn,zn;
xn=yn=zn=0;
printf("Eg\na1*x+b1*y+c1*z=d1\na2*x+b2*y+c2*z=d2\na3*x+b3*y+c3*z=d3\n");
for (int i = 0; i < 3; i++)
{
printf("Enter a%d :- ",i+1 );
scanf("%d",&a[i]);
printf("Enter b%d :- ",i+1 );
scanf("%d",&b[i]);
printf("Enter c%d :- ",i+1 );
scanf("%d",&c[i]);
printf("Enter d%d :- ",i+1 );
scanf("%d",&d[i]);
}
for (int i = 0; i < 3; i++)
{
printf("%d*x+%d*y+%d*z=%d\n",a[i],b[i],c[i],d[i]);
}
for (int i = 0; i < 60; i++)
{
x[i]=(d[0]-b[0]*yn-c[0]*zn)/a[0];
y[i]=(d[1]-a[1]*xn-c[1]*zn)/b[1];
z[i]=(d[2]-a[2]*xn-b[2]*yn)/c[2];
printf("x%d = %f \ty%d = %f \tz%d = %f\n",i+1,x[i],i+1,y[i],i+1,z[i] );
xn=x[i];
yn=y[i];
zn=z[i];
}
}
|
ServError/Revive
|
ReviveXR/Common.h
|
#pragma once
#include "OVR_CAPI.h"
#include "microprofile.h"
#include <openxr/openxr.h>
#include <openxr/openxr_reflection.h>
#include <assert.h>
#include <string>
#if 0
#include <Windows.h>
#define REV_TRACE(x) OutputDebugStringA("Revive: " #x "\n");
#else
#define REV_TRACE(x) MICROPROFILE_SCOPEI("Revive", #x, 0xff0000);
#endif
#define XR_ENUM_CASE_STR(name, val) case name: return L#name;
constexpr const wchar_t* ResultToString(XrResult e)
{
switch (e)
{
XR_LIST_ENUM_XrResult(XR_ENUM_CASE_STR)
default: return L"Unknown";
}
}
extern XrResult g_LastResult;
#ifdef NDEBUG
#define assertmsg(expression, message) ((void)0)
#else
#define assertmsg(expression, message) (void)( \
(!!(expression)) || \
(_wassert(message, _CRT_WIDE(__FILE__), (unsigned)(__LINE__)), 0) \
)
#endif
#define CHK_XR(x) \
{ \
g_LastResult = (x); \
assertmsg(XR_SUCCEEDED(g_LastResult), ResultToString(g_LastResult)); \
if (XR_FAILED(g_LastResult)) return ResultToOvrResult(g_LastResult); \
}
#define CHK_OVR(x) \
{ \
ovrResult __LastResult = (x); \
assert(OVR_SUCCESS(__LastResult)); \
if (OVR_FAILURE(__LastResult)) return __LastResult; \
}
#define XR_TYPE(x) { XR_TYPE_##x, nullptr }
#define XR_FUNCTION(instance, func) \
static PFN_xr##func func = nullptr; \
if (!func) \
CHK_XR(xrGetInstanceProcAddr(instance, "xr" #func, (PFN_xrVoidFunction*)&##func));
ovrResult ResultToOvrResult(XrResult error);
XrTime AbsTimeToXrTime(XrInstance instance, double absTime);
XrPath GetXrPath(const char* path);
XrPath GetXrPath(std::string path);
|
ServError/Revive
|
ReviveXR/Session.h
|
<reponame>ServError/Revive<gh_stars>1000+
#pragma once
#include "OVR_CAPI.h"
#include "Extras/OVR_Math.h"
#include <openxr/openxr.h>
#include <atomic>
#include <condition_variable>
#include <map>
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <list>
#include <vector>
#include <utility>
class Runtime;
class InputManager;
struct SessionStatusBits {
bool IsVisible : 1;
bool HmdPresent : 1;
bool HmdMounted : 1;
bool DisplayLost : 1;
bool ShouldQuit : 1;
bool ShouldRecenter : 1;
bool HasInputFocus : 1;
bool OverlayPresent : 1;
};
typedef struct XrIndexedFrameState : public XrFrameState
{
long long frameIndex;
} XrIndexedFrameState;
typedef std::pair<std::vector<XrVector2f>,
std::vector<uint32_t>> VisibilityMask;
struct ovrHmdStruct
{
std::map<void**, void*> HookedFunctions;
// Synchronization
std::pair<std::mutex,
std::condition_variable> Running;
std::shared_mutex TrackingMutex;
// System handles
XrInstance Instance;
XrSystemId System;
XrSession Session;
// Tracking handles
XrSpace ViewSpace;
std::atomic<ovrTrackingOrigin> TrackingOrigin;
XrSpace OriginSpaces[ovrTrackingOrigin_Count];
XrSpace TrackingSpaces[ovrTrackingOrigin_Count];
// Frame state
XrIndexedFrameState FrameStats[ovrMaxProvidedFrameStats];
std::atomic<XrIndexedFrameState*> CurrentFrame;
ovrGraphicsLuid Adapter;
// OpenXR properties
XrSystemProperties SystemProperties;
XrViewConfigurationView ViewConfigs[ovrEye_Count];
XrViewConfigurationViewFovEPIC ViewFov[ovrEye_Count];
XrView ViewPoses[ovrEye_Count];
ovrVector2f PixelsPerTan[ovrEye_Count];
std::vector<int64_t> SupportedFormats;
// Session status
std::atomic<SessionStatusBits> SessionStatus;
// Field-of-view stencil
std::map<XrVisibilityMaskTypeKHR, VisibilityMask> VisibilityMasks[ovrEye_Count];
// Input
std::unique_ptr<InputManager> Input;
ovrResult InitSession(XrInstance instance);
ovrResult BeginSession(void* graphicsBinding, bool beginFrame = true);
ovrResult EndSession();
ovrResult UpdateStencil(ovrEyeType view, XrVisibilityMaskTypeKHR type);
ovrResult LocateViews(XrView out_Views[ovrEye_Count], XrViewStateFlags* out_Flags = nullptr) const;
ovrResult RecenterSpace(ovrTrackingOrigin origin, XrSpace anchor, ovrPosef offset = OVR::Posef::Identity());
bool SupportsFormat(int64_t format) const;
};
|
ServError/Revive
|
ReviveXR/Runtime.h
|
<reponame>ServError/Revive<filename>ReviveXR/Runtime.h<gh_stars>1000+
#pragma once
#include "Common.h"
#include "OVR_CAPI.h"
#include <openxr/openxr.h>
#include <map>
#include <vector>
class Runtime
{
public:
static Runtime& Get();
enum Hack
{
// Hack: SteamVR runtime doesn't support the Oculus Touch interaction profile.
// Use the Valve Index interaction profile instead.
HACK_VALVE_INDEX_PROFILE,
// Hack: WMR runtime doesn't support the Oculus Touch interaction profile.
// Use the WMR motion controller interaction profile instead.
HACK_WMR_PROFILE,
// Hack: Some games only call GetRenderDesc once before the session is fully initialized.
// Therefore we need to force the fallback field-of-view query so we get full ViewPoses.
HACK_FORCE_FOV_FALLBACK,
// Hack: SteamVR runtime has some inflexibilities in its swapchain creation.
// To work around that we hook the D3D11 texture creation function and force our own parameters.
HACK_HOOK_CREATE_TEXTURE,
// Hack: SteamVR runtime allocates a buffer that is too big for the visibility line loop.
// Causes the rest of the buffer to be filled with uninitialized coordinates.
HACK_BROKEN_LINE_LOOP,
// Hack: Oculus runtime visibility masks are in Normalized Device Coordinates.
// Simply set the projection matrix to the identity matrix as a workaround.
HACK_NDC_MASKS,
// Hack: SteamVR runtime ignore haptic pulses with a long duration.
// Set the duration to the minimum duration as a workaround.
HACK_MIN_HAPTIC_DURATION,
};
bool UseHack(Hack hack);
ovrResult CreateInstance(XrInstance* out_Instance, const ovrInitParams* params);
bool Supports(const char* extensionName);
bool VisibilityMask;
bool CompositionDepth;
bool CompositionCube;
bool CompositionCylinder;
uint32_t MinorVersion;
private:
struct HackInfo
{
const char* m_filename; // The filename of the main executable
const char* m_runtime; // The name of the runtime
Hack m_hack; // Which hack is it?
XrVersion m_versionstart; // When it started
XrVersion m_versionend; // When it ended
bool m_usehack; // Should it use the hack?
};
static const char* s_required_extensions[];
static const char* s_optional_extensions[];
static HackInfo s_known_hacks[];
std::map<Hack, HackInfo> m_hacks;
std::vector<const char*> m_extensions;
};
|
ServError/Revive
|
ReviveXR/SwapChain.h
|
#pragma once
#include "OVR_CAPI.h"
#include <openxr/openxr.h>
#define REV_DEFAULT_SWAPCHAIN_DEPTH 3
struct ovrTextureSwapChainData
{
ovrTextureSwapChainDesc Desc;
XrSwapchain Swapchain;
XrSwapchainImageBaseHeader* Images;
uint32_t Length;
uint32_t CurrentIndex;
};
struct ovrMirrorTextureData
{
ovrMirrorTextureDesc Desc;
ovrTextureSwapChain Dummy;
};
template<typename T>
ovrResult EnumerateImages(XrStructureType type, ovrTextureSwapChain swapChain)
{
CHK_XR(xrEnumerateSwapchainImages(swapChain->Swapchain, 0, &swapChain->Length, nullptr));
T* images = new T[swapChain->Length]();
for (uint32_t i = 0; i < swapChain->Length; i++)
images[i].type = type;
swapChain->Images = (XrSwapchainImageBaseHeader*)images;
uint32_t finalLength;
CHK_XR(xrEnumerateSwapchainImages(swapChain->Swapchain, swapChain->Length, &finalLength, swapChain->Images));
assert(swapChain->Length == finalLength);
return ovrSuccess;
}
ovrResult CreateSwapChain(XrSession session, const ovrTextureSwapChainDesc* desc, int64_t format, ovrTextureSwapChain* out);
|
nsscreencast/102-refactoring-view-controllers
|
CleanTableViews/CleanTableViews/FollowersViewController.h
|
<reponame>nsscreencast/102-refactoring-view-controllers<gh_stars>0
//
// FollowersViewController.h
// CleanTableViews
//
// Created by ben on 1/5/14.
// Copyright (c) 2014 NSScreencast. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface FollowersViewController : UIViewController
@property (nonatomic, strong) IBOutlet UITableView *tableView;
@end
|
nsscreencast/102-refactoring-view-controllers
|
CleanTableViews/CleanTableViews/TwitterAccountStore.h
|
//
// TwitterAccountStore.h
// CleanTableViews
//
// Created by ben on 1/6/14.
// Copyright (c) 2014 NSScreencast. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <Accounts/Accounts.h>
extern NSString * const TwitterAccountStoreErrorDomain;
NS_ENUM(NSInteger, TwitterAccountStoreErrorCodes) {
TwitterAccountStoreNoAccountsError = 0,
TwitterAccountStoreAccessDeniedError
};
@interface TwitterAccountStore : NSObject
- (instancetype)initWithAccountStore:(ACAccountStore *)accountStore;
- (void)fetchDefaultTwitterAccount:(void (^)(ACAccount *account, NSError *error))completion;
@end
|
nsscreencast/102-refactoring-view-controllers
|
CleanTableViews/CleanTableViews/TwitterAPIClient.h
|
//
// TwitterAPIClient.h
// CleanTableViews
//
// Created by ben on 1/6/14.
// Copyright (c) 2014 NSScreencast. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <Accounts/Accounts.h>
#import <Social/Social.h>
@interface TwitterAPIClient : NSObject
- (void)fetchFollowersForAccount:(ACAccount *)account
completion:(void (^)(NSArray *followers, NSError *error))completion;
@end
|
nsscreencast/102-refactoring-view-controllers
|
CleanTableViews/CleanTableViews/TwitterUserCell.h
|
<filename>CleanTableViews/CleanTableViews/TwitterUserCell.h<gh_stars>0
//
// TwitterUserCell.h
// CleanTableViews
//
// Created by ben on 1/5/14.
// Copyright (c) 2014 NSScreencast. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface TwitterUserCell : UITableViewCell
@property (nonatomic, strong) IBOutlet UILabel *nameLabel;
@property (nonatomic, strong) IBOutlet UILabel *screenNameLabel;
@property (nonatomic, strong) IBOutlet UIImageView *avatarImageView;
@end
|
corleonechensiyu/ncnn-8-12
|
src/layer/lstmnew.h
|
<reponame>corleonechensiyu/ncnn-8-12
#ifndef LAYER_LSTMNEW_H
#define LAYER_LSTMNEW_H
#include "layer.h"
namespace ncnn {
class LstmNew : public Layer
{
public:
LstmNew();
virtual int load_param(const ParamDict& pd);
virtual int load_model(const ModelBin& mb);
virtual int forward(const Mat& bottom_blob, Mat& top_blob, const Option& opt) const;
//virtual int forward(const std::vector<Mat>& bottom_blobs, std::vector<Mat>& top_blobs, const Option& opt) const;
public:
// param
int num_output;
int weight_data_size;
// model
Mat weight_i_data;
Mat weight_h_data;
Mat bias_c_data;
};
} // namespace ncnn
#endif // LAYER_LSTMNEW_H
|
corleonechensiyu/ncnn-8-12
|
src/layer/x86/convolution_3x3.h
|
<reponame>corleonechensiyu/ncnn-8-12<gh_stars>1-10
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
// Copyright (C) 2019 BUG1989. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
static void conv3x3s1_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const float* kernel = _kernel;
const float* bias = _bias;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=0; p<outch; p++)
{
Mat out = top_blob.channel(p);
const float bias0 = bias ? bias[p] : 0.f;
out.fill(bias0);
for (int q=0; q<inch; q++)
{
float* outptr = out;
float* outptr2 = outptr + outw;
const float* img0 = bottom_blob.channel(q);
const float* kernel0 = kernel + p*inch*9 + q*9;
const float* r0 = img0;
const float* r1 = img0 + w;
const float* r2 = img0 + w*2;
const float* r3 = img0 + w*3;
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
int i = 0;
for (; i+1 < outh; i+=2)
{
int remain = outw;
for (; remain>0; remain--)
{
float sum = 0;
float sum2 = 0;
sum += r0[0] * k0[0];
sum += r0[1] * k0[1];
sum += r0[2] * k0[2];
sum += r1[0] * k1[0];
sum += r1[1] * k1[1];
sum += r1[2] * k1[2];
sum += r2[0] * k2[0];
sum += r2[1] * k2[1];
sum += r2[2] * k2[2];
sum2 += r1[0] * k0[0];
sum2 += r1[1] * k0[1];
sum2 += r1[2] * k0[2];
sum2 += r2[0] * k1[0];
sum2 += r2[1] * k1[1];
sum2 += r2[2] * k1[2];
sum2 += r3[0] * k2[0];
sum2 += r3[1] * k2[1];
sum2 += r3[2] * k2[2];
*outptr += sum;
*outptr2 += sum2;
r0++;
r1++;
r2++;
r3++;
outptr++;
outptr2++;
}
r0 += 2 + w;
r1 += 2 + w;
r2 += 2 + w;
r3 += 2 + w;
outptr += outw;
outptr2 += outw;
}
for (; i < outh; i++)
{
int remain = outw;
for (; remain>0; remain--)
{
float sum = 0;
sum += r0[0] * k0[0];
sum += r0[1] * k0[1];
sum += r0[2] * k0[2];
sum += r1[0] * k1[0];
sum += r1[1] * k1[1];
sum += r1[2] * k1[2];
sum += r2[0] * k2[0];
sum += r2[1] * k2[1];
sum += r2[2] * k2[2];
*outptr += sum;
r0++;
r1++;
r2++;
outptr++;
}
r0 += 2;
r1 += 2;
r2 += 2;
}
}
}
}
static void conv3x3s1_winograd23_transform_kernel_sse(const Mat& kernel, Mat& kernel_tm, int inch, int outch)
{
kernel_tm.create(4*4, inch, outch);
// G
const float ktm[4][3] = {
{ 1.0f, 0.0f, 0.0f},
{ 1.0f/2, 1.0f/2, 1.0f/2},
{ 1.0f/2, -1.0f/2, 1.0f/2},
{ 0.0f, 0.0f, 1.0f}
};
#pragma omp parallel for
for (int p = 0; p<outch; p++)
{
for (int q = 0; q<inch; q++)
{
const float* kernel0 = (const float*)kernel + p*inch * 9 + q * 9;
float* kernel_tm0 = kernel_tm.channel(p).row(q);
// transform kernel
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
// h
float tmp[4][3];
for (int i=0; i<4; i++)
{
tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2];
tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2];
tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2];
}
// U
for (int j=0; j<4; j++)
{
float* tmpp = &tmp[j][0];
for (int i=0; i<4; i++)
{
kernel_tm0[j*4 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2];
}
}
}
}
}
static void conv3x3s1_winograd23_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
// pad to 2n+2, winograd F(2,3)
Mat bottom_blob_bordered = bottom_blob;
outw = (outw + 1) / 2 * 2;
outh = (outh + 1) / 2 * 2;
w = outw + 2;
h = outh + 2;
copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f, opt.workspace_allocator, opt.num_threads);
const float* bias = _bias;
// BEGIN transform input
Mat bottom_blob_tm;
{
int w_tm = outw / 2 * 4;
int h_tm = outh / 2 * 4;
int nColBlocks = h_tm/4; // may be the block num in Feathercnn
int nRowBlocks = w_tm/4;
const int tiles = nColBlocks * nRowBlocks;
bottom_blob_tm.create(4*4, tiles, inch, 4u, opt.workspace_allocator);
// BT
// const float itm[4][4] = {
// {1.0f, 0.0f, -1.0f, 0.0f},
// {0.0f, 1.0f, 1.00f, 0.0f},
// {0.0f, -1.0f, 1.00f, 0.0f},
// {0.0f, -1.0f, 0.00f, 1.0f}
// };
#pragma omp parallel for num_threads(opt.num_threads)
for (int q=0; q<inch; q++)
{
const float* img = bottom_blob_bordered.channel(q);
float* out_tm0 = bottom_blob_tm.channel(q);
for (int j = 0; j < nColBlocks; j++)
{
const float* r0 = img + w * j * 2;
const float* r1 = r0 + w;
const float* r2 = r1 + w;
const float* r3 = r2 + w;
for (int i = 0; i < nRowBlocks; i++)
{
#if __AVX__
__m128 _d0, _d1, _d2, _d3;
__m128 _w0, _w1, _w2, _w3;
// load
_d0 = _mm_loadu_ps(r0);
_d1 = _mm_loadu_ps(r1);
_d2 = _mm_loadu_ps(r2);
_d3 = _mm_loadu_ps(r3);
// w = B_t * d
_w0 = _mm_sub_ps(_d0, _d2);
_w1 = _mm_add_ps(_d1, _d2);
_w2 = _mm_sub_ps(_d2, _d1);
_w3 = _mm_sub_ps(_d3, _d1);
// transpose d to d_t
_MM_TRANSPOSE4_PS(_w0, _w1, _w2, _w3);
// d = B_t * d_t
_d0 = _mm_sub_ps(_w0, _w2);
_d1 = _mm_add_ps(_w1, _w2);
_d2 = _mm_sub_ps(_w2, _w1);
_d3 = _mm_sub_ps(_w3, _w1);
// save to out_tm
_mm_storeu_ps(out_tm0, _d0);
_mm_storeu_ps(out_tm0+4, _d1);
_mm_storeu_ps(out_tm0+8, _d2);
_mm_storeu_ps(out_tm0+12, _d3);
#else
float d0[4],d1[4],d2[4],d3[4];
float w0[4],w1[4],w2[4],w3[4];
float t0[4],t1[4],t2[4],t3[4];
// load
for (int n = 0; n < 4; n++)
{
d0[n] = r0[n];
d1[n] = r1[n];
d2[n] = r2[n];
d3[n] = r3[n];
}
// w = B_t * d
for (int n = 0; n < 4; n++)
{
w0[n] = d0[n] - d2[n];
w1[n] = d1[n] + d2[n];
w2[n] = d2[n] - d1[n];
w3[n] = d3[n] - d1[n];
}
// transpose d to d_t
{
t0[0]=w0[0]; t1[0]=w0[1]; t2[0]=w0[2]; t3[0]=w0[3];
t0[1]=w1[0]; t1[1]=w1[1]; t2[1]=w1[2]; t3[1]=w1[3];
t0[2]=w2[0]; t1[2]=w2[1]; t2[2]=w2[2]; t3[2]=w2[3];
t0[3]=w3[0]; t1[3]=w3[1]; t2[3]=w3[2]; t3[3]=w3[3];
}
// d = B_t * d_t
for (int n = 0; n < 4; n++)
{
d0[n] = t0[n] - t2[n];
d1[n] = t1[n] + t2[n];
d2[n] = t2[n] - t1[n];
d3[n] = t3[n] - t1[n];
}
// save to out_tm
for (int n = 0; n < 4; n++)
{
out_tm0[n ] = d0[n];
out_tm0[n+ 4] = d1[n];
out_tm0[n+ 8] = d2[n];
out_tm0[n+12] = d3[n];
}
#endif
r0 += 2;
r1 += 2;
r2 += 2;
r3 += 2;
out_tm0 += 16;
}
}
}
}
bottom_blob_bordered = Mat();
// BEGIN dot
Mat top_blob_tm;
{
int w_tm = outw / 2 * 4;
int h_tm = outh / 2 * 4;
int nColBlocks = h_tm/4; // may be the block num in Feathercnn
int nRowBlocks = w_tm/4;
const int tiles = nColBlocks * nRowBlocks;
top_blob_tm.create(16, tiles, outch, 4u, opt.workspace_allocator);
int nn_outch = outch >> 2;
int remain_outch_start = nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp<nn_outch; pp++)
{
int p = pp * 4;
Mat out0_tm = top_blob_tm.channel(p);
Mat out1_tm = top_blob_tm.channel(p+1);
Mat out2_tm = top_blob_tm.channel(p+2);
Mat out3_tm = top_blob_tm.channel(p+3);
const Mat kernel0_tm = kernel_tm.channel(p);
const Mat kernel1_tm = kernel_tm.channel(p+1);
const Mat kernel2_tm = kernel_tm.channel(p+2);
const Mat kernel3_tm = kernel_tm.channel(p+3);
for (int i=0; i<tiles; i++)
{
float* output0_tm = out0_tm.row(i);
float* output1_tm = out1_tm.row(i);
float* output2_tm = out2_tm.row(i);
float* output3_tm = out3_tm.row(i);
#if __AVX__
float zero_val = 0.f;
__m256 _sum0 = _mm256_broadcast_ss(&zero_val);
__m256 _sum0n = _mm256_broadcast_ss(&zero_val);
__m256 _sum1 = _mm256_broadcast_ss(&zero_val);
__m256 _sum1n = _mm256_broadcast_ss(&zero_val);
__m256 _sum2 = _mm256_broadcast_ss(&zero_val);
__m256 _sum2n = _mm256_broadcast_ss(&zero_val);
__m256 _sum3 = _mm256_broadcast_ss(&zero_val);
__m256 _sum3n = _mm256_broadcast_ss(&zero_val);
int q = 0;
for (; q+3<inch; q+=4)
{
const float* r0 = bottom_blob_tm.channel(q).row(i);
const float* r1 = bottom_blob_tm.channel(q+1).row(i);
const float* r2 = bottom_blob_tm.channel(q+2).row(i);
const float* r3 = bottom_blob_tm.channel(q+3).row(i);
const float* k0 = kernel0_tm.row(q);
const float* k1 = kernel1_tm.row(q);
const float* k2 = kernel2_tm.row(q);
const float* k3 = kernel3_tm.row(q);
__m256 _r0 = _mm256_loadu_ps(r0);
__m256 _r0n = _mm256_loadu_ps(r0+8);
// k0
__m256 _k0 = _mm256_loadu_ps(k0);
__m256 _k0n = _mm256_loadu_ps(k0+8);
__m256 _k1 = _mm256_loadu_ps(k1);
__m256 _k1n = _mm256_loadu_ps(k1+8);
__m256 _k2 = _mm256_loadu_ps(k2);
__m256 _k2n = _mm256_loadu_ps(k2+8);
__m256 _k3 = _mm256_loadu_ps(k3);
__m256 _k3n = _mm256_loadu_ps(k3+8);
_sum0 = _mm256_fmadd_ps(_r0, _k0, _sum0);
_sum0n = _mm256_fmadd_ps(_r0n, _k0n, _sum0n);
_sum1 = _mm256_fmadd_ps(_r0, _k1, _sum1);
_sum1n = _mm256_fmadd_ps(_r0n, _k1n, _sum1n);
_sum2 = _mm256_fmadd_ps(_r0, _k2, _sum2);
_sum2n = _mm256_fmadd_ps(_r0n, _k2n, _sum2n);
_sum3 = _mm256_fmadd_ps(_r0, _k3, _sum3);
_sum3n = _mm256_fmadd_ps(_r0n, _k3n, _sum3n);
// k1
_r0 = _mm256_loadu_ps(r1);
_r0n = _mm256_loadu_ps(r1+8);
_k0 = _mm256_loadu_ps(k0+16);
_k0n = _mm256_loadu_ps(k0+24);
_k1 = _mm256_loadu_ps(k1+16);
_k1n = _mm256_loadu_ps(k1+24);
_k2 = _mm256_loadu_ps(k2+16);
_k2n = _mm256_loadu_ps(k2+24);
_k3 = _mm256_loadu_ps(k3+16);
_k3n = _mm256_loadu_ps(k3+24);
_sum0 = _mm256_fmadd_ps(_r0, _k0, _sum0);
_sum0n = _mm256_fmadd_ps(_r0n, _k0n, _sum0n);
_sum1 = _mm256_fmadd_ps(_r0, _k1, _sum1);
_sum1n = _mm256_fmadd_ps(_r0n, _k1n, _sum1n);
_sum2 = _mm256_fmadd_ps(_r0, _k2, _sum2);
_sum2n = _mm256_fmadd_ps(_r0n, _k2n, _sum2n);
_sum3 = _mm256_fmadd_ps(_r0, _k3, _sum3);
_sum3n = _mm256_fmadd_ps(_r0n, _k3n, _sum3n);
// k2
_r0 = _mm256_loadu_ps(r2);
_r0n = _mm256_loadu_ps(r2+8);
_k0 = _mm256_loadu_ps(k0+32);
_k0n = _mm256_loadu_ps(k0+40);
_k1 = _mm256_loadu_ps(k1+32);
_k1n = _mm256_loadu_ps(k1+40);
_k2 = _mm256_loadu_ps(k2+32);
_k2n = _mm256_loadu_ps(k2+40);
_k3 = _mm256_loadu_ps(k3+32);
_k3n = _mm256_loadu_ps(k3+40);
_sum0 = _mm256_fmadd_ps(_r0, _k0, _sum0);
_sum0n = _mm256_fmadd_ps(_r0n, _k0n, _sum0n);
_sum1 = _mm256_fmadd_ps(_r0, _k1, _sum1);
_sum1n = _mm256_fmadd_ps(_r0n, _k1n, _sum1n);
_sum2 = _mm256_fmadd_ps(_r0, _k2, _sum2);
_sum2n = _mm256_fmadd_ps(_r0n, _k2n, _sum2n);
_sum3 = _mm256_fmadd_ps(_r0, _k3, _sum3);
_sum3n = _mm256_fmadd_ps(_r0n, _k3n, _sum3n);
// k3
_r0 = _mm256_loadu_ps(r3);
_r0n = _mm256_loadu_ps(r3+8);
_k0 = _mm256_loadu_ps(k0+48);
_k0n = _mm256_loadu_ps(k0+56);
_k1 = _mm256_loadu_ps(k1+48);
_k1n = _mm256_loadu_ps(k1+56);
_k2 = _mm256_loadu_ps(k2+48);
_k2n = _mm256_loadu_ps(k2+56);
_k3 = _mm256_loadu_ps(k3+48);
_k3n = _mm256_loadu_ps(k3+56);
_sum0 = _mm256_fmadd_ps(_r0, _k0, _sum0);
_sum0n = _mm256_fmadd_ps(_r0n, _k0n, _sum0n);
_sum1 = _mm256_fmadd_ps(_r0, _k1, _sum1);
_sum1n = _mm256_fmadd_ps(_r0n, _k1n, _sum1n);
_sum2 = _mm256_fmadd_ps(_r0, _k2, _sum2);
_sum2n = _mm256_fmadd_ps(_r0n, _k2n, _sum2n);
_sum3 = _mm256_fmadd_ps(_r0, _k3, _sum3);
_sum3n = _mm256_fmadd_ps(_r0n, _k3n, _sum3n);
}
for (; q<inch; q++)
{
const float* r0 = bottom_blob_tm.channel(q).row(i);
const float* k0 = kernel0_tm.row(q);
const float* k1 = kernel1_tm.row(q);
const float* k2 = kernel2_tm.row(q);
const float* k3 = kernel3_tm.row(q);
__m256 _r0 = _mm256_loadu_ps(r0);
__m256 _r0n = _mm256_loadu_ps(r0+8);
__m256 _k0 = _mm256_loadu_ps(k0);
__m256 _k0n = _mm256_loadu_ps(k0+8);
__m256 _k1 = _mm256_loadu_ps(k1);
__m256 _k1n = _mm256_loadu_ps(k1+8);
__m256 _k2 = _mm256_loadu_ps(k2);
__m256 _k2n = _mm256_loadu_ps(k2+8);
__m256 _k3 = _mm256_loadu_ps(k3);
__m256 _k3n = _mm256_loadu_ps(k3+8);
_sum0 = _mm256_fmadd_ps(_r0, _k0, _sum0);
_sum0n = _mm256_fmadd_ps(_r0n, _k0n, _sum0n);
_sum1 = _mm256_fmadd_ps(_r0, _k1, _sum1);
_sum1n = _mm256_fmadd_ps(_r0n, _k1n, _sum1n);
_sum2 = _mm256_fmadd_ps(_r0, _k2, _sum2);
_sum2n = _mm256_fmadd_ps(_r0n, _k2n, _sum2n);
_sum3 = _mm256_fmadd_ps(_r0, _k3, _sum3);
_sum3n = _mm256_fmadd_ps(_r0n, _k3n, _sum3n);
}
_mm256_storeu_ps(output0_tm, _sum0);
_mm256_storeu_ps(output0_tm+8, _sum0n);
_mm256_storeu_ps(output1_tm, _sum1);
_mm256_storeu_ps(output1_tm+8, _sum1n);
_mm256_storeu_ps(output2_tm, _sum2);
_mm256_storeu_ps(output2_tm+8, _sum2n);
_mm256_storeu_ps(output3_tm, _sum3);
_mm256_storeu_ps(output3_tm+8, _sum3n);
#else
float sum0[16] = {0.0f};
float sum1[16] = {0.0f};
float sum2[16] = {0.0f};
float sum3[16] = {0.0f};
int q = 0;
for (; q+3<inch; q+=4)
{
const float* r0 = bottom_blob_tm.channel(q).row(i);
const float* r1 = bottom_blob_tm.channel(q+1).row(i);
const float* r2 = bottom_blob_tm.channel(q+2).row(i);
const float* r3 = bottom_blob_tm.channel(q+3).row(i);
const float* k0 = kernel0_tm.row(q);
const float* k1 = kernel1_tm.row(q);
const float* k2 = kernel2_tm.row(q);
const float* k3 = kernel3_tm.row(q);
for (int n=0; n<16; n++)
{
sum0[n] += r0[n] * k0[n];
k0 += 16;
sum0[n] += r1[n] * k0[n];
k0 += 16;
sum0[n] += r2[n] * k0[n];
k0 += 16;
sum0[n] += r3[n] * k0[n];
k0 -= 16 * 3;
sum1[n] += r0[n] * k1[n];
k1 += 16;
sum1[n] += r1[n] * k1[n];
k1 += 16;
sum1[n] += r2[n] * k1[n];
k1 += 16;
sum1[n] += r3[n] * k1[n];
k1 -= 16 * 3;
sum2[n] += r0[n] * k2[n];
k2 += 16;
sum2[n] += r1[n] * k2[n];
k2 += 16;
sum2[n] += r2[n] * k2[n];
k2 += 16;
sum2[n] += r3[n] * k2[n];
k2 -= 16 * 3;
sum3[n] += r0[n] * k3[n];
k3 += 16;
sum3[n] += r1[n] * k3[n];
k3 += 16;
sum3[n] += r2[n] * k3[n];
k3 += 16;
sum3[n] += r3[n] * k3[n];
k3 -= 16 * 3;
}
}
for (; q<inch; q++)
{
const float* r0 = bottom_blob_tm.channel(q).row(i);
const float* k0 = kernel0_tm.row(q);
const float* k1 = kernel1_tm.row(q);
const float* k2 = kernel2_tm.row(q);
const float* k3 = kernel3_tm.row(q);
for (int n=0; n<16; n++)
{
sum0[n] += r0[n] * k0[n];
sum1[n] += r0[n] * k1[n];
sum2[n] += r0[n] * k2[n];
sum3[n] += r0[n] * k3[n];
}
}
for (int n=0; n<16; n++)
{
output0_tm[n] = sum0[n];
output1_tm[n] = sum1[n];
output2_tm[n] = sum2[n];
output3_tm[n] = sum3[n];
}
#endif
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=remain_outch_start; p<outch; p++)
{
Mat out0_tm = top_blob_tm.channel(p);
const Mat kernel0_tm = kernel_tm.channel(p);
for (int i=0; i<tiles; i++)
{
float* output0_tm = out0_tm.row(i);
float sum0[16] = {0.0f};
int q = 0;
for (; q+3<inch; q+=4)
{
const float* r0 = bottom_blob_tm.channel(q).row(i);
const float* r1 = bottom_blob_tm.channel(q+1).row(i);
const float* r2 = bottom_blob_tm.channel(q+2).row(i);
const float* r3 = bottom_blob_tm.channel(q+3).row(i);
const float* k0 = kernel0_tm.row(q);
const float* k1 = kernel0_tm.row(q+1);
const float* k2 = kernel0_tm.row(q+2);
const float* k3 = kernel0_tm.row(q+3);
for (int n=0; n<16; n++)
{
sum0[n] += r0[n] * k0[n];
sum0[n] += r1[n] * k1[n];
sum0[n] += r2[n] * k2[n];
sum0[n] += r3[n] * k3[n];
}
}
for (; q<inch; q++)
{
const float* r0 = bottom_blob_tm.channel(q).row(i);
const float* k0 = kernel0_tm.row(q);
for (int n=0; n<16; n++)
{
sum0[n] += r0[n] * k0[n];
}
}
for (int n=0; n<16; n++)
{
output0_tm[n] = sum0[n];
}
}
}
}
bottom_blob_tm = Mat();
// END dot
// BEGIN transform output
Mat top_blob_bordered;
top_blob_bordered.create(outw, outh, outch, 4u, opt.workspace_allocator);
{
// AT
// const float itm[2][4] = {
// {1.0f, 1.0f, 1.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 1.0f}
// };
int w_tm = outw / 2 * 4;
int h_tm = outh / 2 * 4;
int nColBlocks = h_tm/4; // may be the block num in Feathercnn
int nRowBlocks = w_tm/4;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=0; p<outch; p++)
{
Mat out_tm = top_blob_tm.channel(p);
Mat out = top_blob_bordered.channel(p);
const float bias0 = bias ? bias[p] : 0.f;
for (int j=0; j<nColBlocks; j++)
{
float* outRow0 = out.row(j*2);
float* outRow1 = out.row(j*2+1);
for(int i=0; i<nRowBlocks; i++)
{
float* out_tile = out_tm.row(j*nRowBlocks + i);
float s0[4],s1[4],s2[4],s3[4];
float w0[4],w1[4];
float d0[2],d1[2],d2[2],d3[2];
float o0[2],o1[2];
// load
for (int n = 0; n < 4; n++)
{
s0[n] = out_tile[n];
s1[n] = out_tile[n+ 4];
s2[n] = out_tile[n+ 8];
s3[n] = out_tile[n+12];
}
// w = A_T * W
for (int n = 0; n < 4; n++)
{
w0[n] = s0[n] + s1[n] + s2[n];
w1[n] = s1[n] - s2[n] + s3[n];
}
// transpose w to w_t
{
d0[0] = w0[0]; d0[1] = w1[0];
d1[0] = w0[1]; d1[1] = w1[1];
d2[0] = w0[2]; d2[1] = w1[2];
d3[0] = w0[3]; d3[1] = w1[3];
}
// Y = A_T * w_t
for (int n = 0; n < 2; n++)
{
o0[n] = d0[n] + d1[n] + d2[n] + bias0;
o1[n] = d1[n] - d2[n] + d3[n] + bias0;
}
// save to top blob tm
outRow0[0] = o0[0];
outRow0[1] = o0[1];
outRow1[0] = o1[0];
outRow1[1] = o1[1];
outRow0 += 2;
outRow1 += 2;
}
}
}
}
// END transform output
// cut result pad
copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt.blob_allocator, opt.num_threads);
}
static void conv3x3s1_winograd43_transform_kernel_sse(const Mat& kernel, std::vector<Mat> &kernel_tm2, int inch, int outch)
{
Mat kernel_tm(6*6, inch, outch);
// G
const float ktm[6][3] = {
{ 1.0f/4, 0.0f, 0.0f},
{ -1.0f/6, -1.0f/6, -1.0f/6},
{ -1.0f/6, 1.0f/6, -1.0f/6},
{ 1.0f/24, 1.0f/12, 1.0f/6},
{ 1.0f/24, -1.0f/12, 1.0f/6},
{ 0.0f, 0.0f, 1.0f}
};
#pragma omp parallel for
for (int p = 0; p<outch; p++)
{
for (int q = 0; q<inch; q++)
{
const float* kernel0 = (const float*)kernel + p*inch * 9 + q * 9;
float* kernel_tm0 = kernel_tm.channel(p).row(q);
// transform kernel
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
// h
float tmp[6][3];
for (int i=0; i<6; i++)
{
tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2];
tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2];
tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2];
}
// U
for (int j=0; j<6; j++)
{
float* tmpp = &tmp[j][0];
for (int i=0; i<6; i++)
{
kernel_tm0[j*6 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2];
}
}
}
}
for (int r=0; r<9; r++)
{
Mat kernel_tm_test(4*8, inch, outch/8 + (outch%8)/4 + outch%4);
int p = 0;
for (; p+7<outch; p+=8)
{
const float* kernel0 = (const float*)kernel_tm.channel(p);
const float* kernel1 = (const float*)kernel_tm.channel(p+1);
const float* kernel2 = (const float*)kernel_tm.channel(p+2);
const float* kernel3 = (const float*)kernel_tm.channel(p+3);
const float* kernel4 = (const float*)kernel_tm.channel(p+4);
const float* kernel5 = (const float*)kernel_tm.channel(p+5);
const float* kernel6 = (const float*)kernel_tm.channel(p+6);
const float* kernel7 = (const float*)kernel_tm.channel(p+7);
float* ktmp = kernel_tm_test.channel(p/8);
for (int q=0; q<inch; q++)
{
ktmp[0] = kernel0[r*4+0];
ktmp[1] = kernel0[r*4+1];
ktmp[2] = kernel0[r*4+2];
ktmp[3] = kernel0[r*4+3];
ktmp[4] = kernel1[r*4+0];
ktmp[5] = kernel1[r*4+1];
ktmp[6] = kernel1[r*4+2];
ktmp[7] = kernel1[r*4+3];
ktmp[8] = kernel2[r*4+0];
ktmp[9] = kernel2[r*4+1];
ktmp[10] = kernel2[r*4+2];
ktmp[11] = kernel2[r*4+3];
ktmp[12] = kernel3[r*4+0];
ktmp[13] = kernel3[r*4+1];
ktmp[14] = kernel3[r*4+2];
ktmp[15] = kernel3[r*4+3];
ktmp[16] = kernel4[r*4+0];
ktmp[17] = kernel4[r*4+1];
ktmp[18] = kernel4[r*4+2];
ktmp[19] = kernel4[r*4+3];
ktmp[20] = kernel5[r*4+0];
ktmp[21] = kernel5[r*4+1];
ktmp[22] = kernel5[r*4+2];
ktmp[23] = kernel5[r*4+3];
ktmp[24] = kernel6[r*4+0];
ktmp[25] = kernel6[r*4+1];
ktmp[26] = kernel6[r*4+2];
ktmp[27] = kernel6[r*4+3];
ktmp[28] = kernel7[r*4+0];
ktmp[29] = kernel7[r*4+1];
ktmp[30] = kernel7[r*4+2];
ktmp[31] = kernel7[r*4+3];
ktmp += 32;
kernel0 += 36;
kernel1 += 36;
kernel2 += 36;
kernel3 += 36;
kernel4 += 36;
kernel5 += 36;
kernel6 += 36;
kernel7 += 36;
}
}
for (; p+3<outch; p+=4)
{
const float* kernel0 = (const float*)kernel_tm.channel(p);
const float* kernel1 = (const float*)kernel_tm.channel(p+1);
const float* kernel2 = (const float*)kernel_tm.channel(p+2);
const float* kernel3 = (const float*)kernel_tm.channel(p+3);
float* ktmp = kernel_tm_test.channel(p/8 + (p%8)/4);
for (int q=0; q<inch; q++)
{
ktmp[0] = kernel0[r*4+0];
ktmp[1] = kernel0[r*4+1];
ktmp[2] = kernel0[r*4+2];
ktmp[3] = kernel0[r*4+3];
ktmp[4] = kernel1[r*4+0];
ktmp[5] = kernel1[r*4+1];
ktmp[6] = kernel1[r*4+2];
ktmp[7] = kernel1[r*4+3];
ktmp[8] = kernel2[r*4+0];
ktmp[9] = kernel2[r*4+1];
ktmp[10] = kernel2[r*4+2];
ktmp[11] = kernel2[r*4+3];
ktmp[12] = kernel3[r*4+0];
ktmp[13] = kernel3[r*4+1];
ktmp[14] = kernel3[r*4+2];
ktmp[15] = kernel3[r*4+3];
ktmp += 16;
kernel0 += 36;
kernel1 += 36;
kernel2 += 36;
kernel3 += 36;
}
}
for (; p<outch; p++)
{
const float* kernel0 = (const float*)kernel_tm.channel(p);
float* ktmp = kernel_tm_test.channel(p/8 + (p%8)/4 + p%4);
for (int q=0; q<inch; q++)
{
ktmp[0] = kernel0[r*4+0];
ktmp[1] = kernel0[r*4+1];
ktmp[2] = kernel0[r*4+2];
ktmp[3] = kernel0[r*4+3];
ktmp += 4;
kernel0 += 36;
}
}
kernel_tm2.push_back(kernel_tm_test);
}
}
static void conv3x3s1_winograd43_sse(const Mat& bottom_blob, Mat& top_blob, const std::vector<Mat> &kernel_tm_test, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int h = bottom_blob.h;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
size_t elemsize = bottom_blob.elemsize;
const float* bias = _bias;
// pad to 4n+2, winograd F(4,3)
Mat bottom_blob_bordered = bottom_blob;
outw = (outw + 3) / 4 * 4;
outh = (outh + 3) / 4 * 4;
w = outw + 2;
h = outh + 2;
copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f, opt.workspace_allocator, opt.num_threads);
// BEGIN transform input
Mat bottom_blob_tm;
{
int w_tm = outw / 4 * 6;
int h_tm = outh / 4 * 6;
int nColBlocks = h_tm/6; // may be the block num in Feathercnn
int nRowBlocks = w_tm/6;
const int tiles = nColBlocks * nRowBlocks;
bottom_blob_tm.create(4, inch, tiles*9, elemsize, opt.workspace_allocator);
// BT
// const float itm[4][4] = {
// {4.0f, 0.0f, -5.0f, 0.0f, 1.0f, 0.0f},
// {0.0f,-4.0f, -4.0f, 1.0f, 1.0f, 0.0f},
// {0.0f, 4.0f, -4.0f,-1.0f, 1.0f, 0.0f},
// {0.0f,-2.0f, -1.0f, 2.0f, 1.0f, 0.0f},
// {0.0f, 2.0f, -1.0f,-2.0f, 1.0f, 0.0f},
// {0.0f, 4.0f, 0.0f,-5.0f, 0.0f, 1.0f}
// };
// 0 = 4 * r00 - 5 * r02 + r04
// 1 = -4 * (r01 + r02) + r03 + r04
// 2 = 4 * (r01 - r02) - r03 + r04
// 3 = -2 * r01 - r02 + 2 * r03 + r04
// 4 = 2 * r01 - r02 - 2 * r03 + r04
// 5 = 4 * r01 - 5 * r03 + r05
// 0 = 4 * r00 - 5 * r02 + r04
// 1 = -4 * (r01 + r02) + r03 + r04
// 2 = 4 * (r01 - r02) - r03 + r04
// 3 = -2 * r01 - r02 + 2 * r03 + r04
// 4 = 2 * r01 - r02 - 2 * r03 + r04
// 5 = 4 * r01 - 5 * r03 + r05
#if __AVX__
__m256 _1_n = _mm256_set1_ps(-1);
__m256 _2_p = _mm256_set1_ps(2);
__m256 _2_n = _mm256_set1_ps(-2);
__m256 _4_p = _mm256_set1_ps(4);
__m256 _4_n = _mm256_set1_ps(-4);
__m256 _5_n = _mm256_set1_ps(-5);
#endif
#pragma omp parallel for num_threads(opt.num_threads)
for (int q=0; q<inch; q++)
{
const float* img = bottom_blob_bordered.channel(q);
for (int j = 0; j < nColBlocks; j++)
{
const float* r0 = img + w * j * 4;
const float* r1 = r0 + w;
const float* r2 = r1 + w;
const float* r3 = r2 + w;
const float* r4 = r3 + w;
const float* r5 = r4 + w;
for (int i = 0; i < nRowBlocks; i++)
{
float* out_tm0 = bottom_blob_tm.channel(tiles*0+j*nRowBlocks+i).row(q);
float* out_tm1 = bottom_blob_tm.channel(tiles*1+j*nRowBlocks+i).row(q);
float* out_tm2 = bottom_blob_tm.channel(tiles*2+j*nRowBlocks+i).row(q);
float* out_tm3 = bottom_blob_tm.channel(tiles*3+j*nRowBlocks+i).row(q);
float* out_tm4 = bottom_blob_tm.channel(tiles*4+j*nRowBlocks+i).row(q);
float* out_tm5 = bottom_blob_tm.channel(tiles*5+j*nRowBlocks+i).row(q);
float* out_tm6 = bottom_blob_tm.channel(tiles*6+j*nRowBlocks+i).row(q);
float* out_tm7 = bottom_blob_tm.channel(tiles*7+j*nRowBlocks+i).row(q);
float* out_tm8 = bottom_blob_tm.channel(tiles*8+j*nRowBlocks+i).row(q);
#if __AVX__
__m256 _d0, _d1, _d2, _d3, _d4, _d5;
__m256 _w0, _w1, _w2, _w3, _w4, _w5;
__m256 _t0, _t1, _t2, _t3, _t4, _t5;
__m256 _n0, _n1, _n2, _n3, _n4, _n5;
// load
_d0 = _mm256_loadu_ps(r0);
_d1 = _mm256_loadu_ps(r1);
_d2 = _mm256_loadu_ps(r2);
_d3 = _mm256_loadu_ps(r3);
_d4 = _mm256_loadu_ps(r4);
_d5 = _mm256_loadu_ps(r5);
// w = B_t * d
_w0 = _mm256_mul_ps(_d0, _4_p);
_w0 = _mm256_fmadd_ps(_d2, _5_n, _w0);
_w0 = _mm256_add_ps(_w0, _d4);
_w1 = _mm256_mul_ps(_d1, _4_n);
_w1 = _mm256_fmadd_ps(_d2, _4_n, _w1);
_w1 = _mm256_add_ps(_w1, _d3);
_w1 = _mm256_add_ps(_w1, _d4);
_w2 = _mm256_mul_ps(_d1, _4_p);
_w2 = _mm256_fmadd_ps(_d2, _4_n, _w2);
_w2 = _mm256_fmadd_ps(_d3, _1_n, _w2);
_w2 = _mm256_add_ps(_w2, _d4);
_w3 = _mm256_mul_ps(_d1, _2_n);
_w3 = _mm256_fmadd_ps(_d2, _1_n, _w3);
_w3 = _mm256_fmadd_ps(_d3, _2_p, _w3);
_w3 = _mm256_add_ps(_w3, _d4);
_w4 = _mm256_mul_ps(_d1, _2_p);
_w4 = _mm256_fmadd_ps(_d2, _1_n, _w4);
_w4 = _mm256_fmadd_ps(_d3, _2_n, _w4);
_w4 = _mm256_add_ps(_w4, _d4);
_w5 = _mm256_mul_ps(_d1, _4_p);
_w5 = _mm256_fmadd_ps(_d3, _5_n, _w5);
_w5 = _mm256_add_ps(_w5, _d5);
// transpose d to d_t
{
_t0[0]=_w0[0]; _t1[0]=_w0[1]; _t2[0]=_w0[2]; _t3[0]=_w0[3]; _t4[0]=_w0[4]; _t5[0]=_w0[5];
_t0[1]=_w1[0]; _t1[1]=_w1[1]; _t2[1]=_w1[2]; _t3[1]=_w1[3]; _t4[1]=_w1[4]; _t5[1]=_w1[5];
_t0[2]=_w2[0]; _t1[2]=_w2[1]; _t2[2]=_w2[2]; _t3[2]=_w2[3]; _t4[2]=_w2[4]; _t5[2]=_w2[5];
_t0[3]=_w3[0]; _t1[3]=_w3[1]; _t2[3]=_w3[2]; _t3[3]=_w3[3]; _t4[3]=_w3[4]; _t5[3]=_w3[5];
_t0[4]=_w4[0]; _t1[4]=_w4[1]; _t2[4]=_w4[2]; _t3[4]=_w4[3]; _t4[4]=_w4[4]; _t5[4]=_w4[5];
_t0[5]=_w5[0]; _t1[5]=_w5[1]; _t2[5]=_w5[2]; _t3[5]=_w5[3]; _t4[5]=_w5[4]; _t5[5]=_w5[5];
}
// d = B_t * d_t
_n0 = _mm256_mul_ps(_t0, _4_p);
_n0 = _mm256_fmadd_ps(_t2, _5_n, _n0);
_n0 = _mm256_add_ps(_n0, _t4);
_n1 = _mm256_mul_ps(_t1, _4_n);
_n1 = _mm256_fmadd_ps(_t2, _4_n, _n1);
_n1 = _mm256_add_ps(_n1, _t3);
_n1 = _mm256_add_ps(_n1, _t4);
_n2 = _mm256_mul_ps(_t1, _4_p);
_n2 = _mm256_fmadd_ps(_t2, _4_n, _n2);
_n2 = _mm256_fmadd_ps(_t3, _1_n, _n2);
_n2 = _mm256_add_ps(_n2, _t4);
_n3 = _mm256_mul_ps(_t1, _2_n);
_n3 = _mm256_fmadd_ps(_t2, _1_n, _n3);
_n3 = _mm256_fmadd_ps(_t3, _2_p, _n3);
_n3 = _mm256_add_ps(_n3, _t4);
_n4 = _mm256_mul_ps(_t1, _2_p);
_n4 = _mm256_fmadd_ps(_t2, _1_n, _n4);
_n4 = _mm256_fmadd_ps(_t3, _2_n, _n4);
_n4 = _mm256_add_ps(_n4, _t4);
_n5 = _mm256_mul_ps(_t1, _4_p);
_n5 = _mm256_fmadd_ps(_t3, _5_n, _n5);
_n5 = _mm256_add_ps(_n5, _t5);
// save to out_tm
out_tm0[0]=_n0[0];out_tm0[1]=_n0[1];out_tm0[2]=_n0[2];out_tm0[3]=_n0[3];
out_tm1[0]=_n0[4];out_tm1[1]=_n0[5];out_tm1[2]=_n1[0];out_tm1[3]=_n1[1];
out_tm2[0]=_n1[2];out_tm2[1]=_n1[3];out_tm2[2]=_n1[4];out_tm2[3]=_n1[5];
out_tm3[0]=_n2[0];out_tm3[1]=_n2[1];out_tm3[2]=_n2[2];out_tm3[3]=_n2[3];
out_tm4[0]=_n2[4];out_tm4[1]=_n2[5];out_tm4[2]=_n3[0];out_tm4[3]=_n3[1];
out_tm5[0]=_n3[2];out_tm5[1]=_n3[3];out_tm5[2]=_n3[4];out_tm5[3]=_n3[5];
out_tm6[0]=_n4[0];out_tm6[1]=_n4[1];out_tm6[2]=_n4[2];out_tm6[3]=_n4[3];
out_tm7[0]=_n4[4];out_tm7[1]=_n4[5];out_tm7[2]=_n5[0];out_tm7[3]=_n5[1];
out_tm8[0]=_n5[2];out_tm8[1]=_n5[3];out_tm8[2]=_n5[4];out_tm8[3]=_n5[5];
#else
float d0[6],d1[6],d2[6],d3[6],d4[6],d5[6];
float w0[6],w1[6],w2[6],w3[6],w4[6],w5[6];
float t0[6],t1[6],t2[6],t3[6],t4[6],t5[6];
// load
for (int n = 0; n < 6; n++)
{
d0[n] = r0[n];
d1[n] = r1[n];
d2[n] = r2[n];
d3[n] = r3[n];
d4[n] = r4[n];
d5[n] = r5[n];
}
// w = B_t * d
for (int n = 0; n < 6; n++)
{
w0[n] = 4*d0[n] - 5*d2[n] + d4[n];
w1[n] = -4*d1[n] - 4*d2[n] + d3[n] + d4[n];
w2[n] = 4*d1[n] - 4*d2[n] - d3[n] + d4[n];
w3[n] = -2*d1[n] - d2[n] + 2*d3[n] + d4[n];
w4[n] = 2*d1[n] - d2[n] - 2*d3[n] + d4[n];
w5[n] = 4*d1[n] - 5*d3[n] + d5[n];
}
// transpose d to d_t
{
t0[0]=w0[0]; t1[0]=w0[1]; t2[0]=w0[2]; t3[0]=w0[3]; t4[0]=w0[4]; t5[0]=w0[5];
t0[1]=w1[0]; t1[1]=w1[1]; t2[1]=w1[2]; t3[1]=w1[3]; t4[1]=w1[4]; t5[1]=w1[5];
t0[2]=w2[0]; t1[2]=w2[1]; t2[2]=w2[2]; t3[2]=w2[3]; t4[2]=w2[4]; t5[2]=w2[5];
t0[3]=w3[0]; t1[3]=w3[1]; t2[3]=w3[2]; t3[3]=w3[3]; t4[3]=w3[4]; t5[3]=w3[5];
t0[4]=w4[0]; t1[4]=w4[1]; t2[4]=w4[2]; t3[4]=w4[3]; t4[4]=w4[4]; t5[4]=w4[5];
t0[5]=w5[0]; t1[5]=w5[1]; t2[5]=w5[2]; t3[5]=w5[3]; t4[5]=w5[4]; t5[5]=w5[5];
}
// d = B_t * d_t
for (int n = 0; n < 6; n++)
{
d0[n] = 4*t0[n] - 5*t2[n] + t4[n];
d1[n] = - 4*t1[n] - 4*t2[n] + t3[n] + t4[n];
d2[n] = 4*t1[n] - 4*t2[n] - t3[n] + t4[n];
d3[n] = - 2*t1[n] - t2[n] + 2*t3[n] + t4[n];
d4[n] = 2*t1[n] - t2[n] - 2*t3[n] + t4[n];
d5[n] = 4*t1[n] - 5*t3[n] + t5[n];
}
// save to out_tm
{
out_tm0[0]=d0[0];out_tm0[1]=d0[1];out_tm0[2]=d0[2];out_tm0[3]=d0[3];
out_tm1[0]=d0[4];out_tm1[1]=d0[5];out_tm1[2]=d1[0];out_tm1[3]=d1[1];
out_tm2[0]=d1[2];out_tm2[1]=d1[3];out_tm2[2]=d1[4];out_tm2[3]=d1[5];
out_tm3[0]=d2[0];out_tm3[1]=d2[1];out_tm3[2]=d2[2];out_tm3[3]=d2[3];
out_tm4[0]=d2[4];out_tm4[1]=d2[5];out_tm4[2]=d3[0];out_tm4[3]=d3[1];
out_tm5[0]=d3[2];out_tm5[1]=d3[3];out_tm5[2]=d3[4];out_tm5[3]=d3[5];
out_tm6[0]=d4[0];out_tm6[1]=d4[1];out_tm6[2]=d4[2];out_tm6[3]=d4[3];
out_tm7[0]=d4[4];out_tm7[1]=d4[5];out_tm7[2]=d5[0];out_tm7[3]=d5[1];
out_tm8[0]=d5[2];out_tm8[1]=d5[3];out_tm8[2]=d5[4];out_tm8[3]=d5[5];
}
#endif // __AVX__
r0 += 4;
r1 += 4;
r2 += 4;
r3 += 4;
r4 += 4;
r5 += 4;
}
}
}
}
bottom_blob_bordered = Mat();
// BEGIN dot
Mat top_blob_tm;
{
int w_tm = outw / 4 * 6;
int h_tm = outh / 4 * 6;
int nColBlocks = h_tm/6; // may be the block num in Feathercnn
int nRowBlocks = w_tm/6;
const int tiles = nColBlocks * nRowBlocks;
top_blob_tm.create(36, tiles, outch, elemsize, opt.workspace_allocator);
#pragma omp parallel for num_threads(opt.num_threads)
for (int r=0; r<9; r++)
{
int nn_outch = 0;
int remain_outch_start = 0;
nn_outch = outch >> 3;
remain_outch_start = nn_outch << 3;
for (int pp=0; pp<nn_outch; pp++)
{
int p = pp * 8;
float* output0_tm = top_blob_tm.channel(p);
float* output1_tm = top_blob_tm.channel(p+1);
float* output2_tm = top_blob_tm.channel(p+2);
float* output3_tm = top_blob_tm.channel(p+3);
float* output4_tm = top_blob_tm.channel(p+4);
float* output5_tm = top_blob_tm.channel(p+5);
float* output6_tm = top_blob_tm.channel(p+6);
float* output7_tm = top_blob_tm.channel(p+7);
output0_tm = output0_tm + r*4;
output1_tm = output1_tm + r*4;
output2_tm = output2_tm + r*4;
output3_tm = output3_tm + r*4;
output4_tm = output4_tm + r*4;
output5_tm = output5_tm + r*4;
output6_tm = output6_tm + r*4;
output7_tm = output7_tm + r*4;
for (int i=0; i<tiles; i++)
{
const float* kptr = kernel_tm_test[r].channel(p/8);
const float* r0 = bottom_blob_tm.channel(tiles*r+i);
#if __AVX__ || __SSE__
#if __AVX__
float zero_val = 0.f;
__m128 _sum0 = _mm_broadcast_ss(&zero_val);
__m128 _sum1 = _mm_broadcast_ss(&zero_val);
__m128 _sum2 = _mm_broadcast_ss(&zero_val);
__m128 _sum3 = _mm_broadcast_ss(&zero_val);
__m128 _sum4 = _mm_broadcast_ss(&zero_val);
__m128 _sum5 = _mm_broadcast_ss(&zero_val);
__m128 _sum6 = _mm_broadcast_ss(&zero_val);
__m128 _sum7 = _mm_broadcast_ss(&zero_val);
#else
__m128 _sum0 = _mm_set1_ps(0.f);
__m128 _sum1 = _mm_set1_ps(0.f);
__m128 _sum2 = _mm_set1_ps(0.f);
__m128 _sum3 = _mm_set1_ps(0.f);
__m128 _sum4 = _mm_set1_ps(0.f);
__m128 _sum5 = _mm_set1_ps(0.f);
__m128 _sum6 = _mm_set1_ps(0.f);
__m128 _sum7 = _mm_set1_ps(0.f);
#endif
int q=0;
for (; q+3<inch; q=q+4)
{
__m128 _r0 = _mm_loadu_ps(r0);
__m128 _r1 = _mm_loadu_ps(r0+4);
__m128 _r2 = _mm_loadu_ps(r0+8);
__m128 _r3 = _mm_loadu_ps(r0+12);
__m128 _k0 = _mm_loadu_ps(kptr);
__m128 _k1 = _mm_loadu_ps(kptr+4);
__m128 _k2 = _mm_loadu_ps(kptr+8);
__m128 _k3 = _mm_loadu_ps(kptr+12);
__m128 _k4 = _mm_loadu_ps(kptr+16);
__m128 _k5 = _mm_loadu_ps(kptr+20);
__m128 _k6 = _mm_loadu_ps(kptr+24);
__m128 _k7 = _mm_loadu_ps(kptr+28);
#if __AVX__
_sum0 = _mm_fmadd_ps(_r0, _k0, _sum0);
_sum1 = _mm_fmadd_ps(_r0, _k1, _sum1);
_sum2 = _mm_fmadd_ps(_r0, _k2, _sum2);
_sum3 = _mm_fmadd_ps(_r0, _k3, _sum3);
_sum4 = _mm_fmadd_ps(_r0, _k4, _sum4);
_sum5 = _mm_fmadd_ps(_r0, _k5, _sum5);
_sum6 = _mm_fmadd_ps(_r0, _k6, _sum6);
_sum7 = _mm_fmadd_ps(_r0, _k7, _sum7);
#else
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r0, _k0));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r0, _k1));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r0, _k2));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r0, _k3));
_sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r0, _k4));
_sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r0, _k5));
_sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r0, _k6));
_sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r0, _k7));
#endif
kptr += 32;
_k0 = _mm_loadu_ps(kptr);
_k1 = _mm_loadu_ps(kptr+4);
_k2 = _mm_loadu_ps(kptr+8);
_k3 = _mm_loadu_ps(kptr+12);
_k4 = _mm_loadu_ps(kptr+16);
_k5 = _mm_loadu_ps(kptr+20);
_k6 = _mm_loadu_ps(kptr+24);
_k7 = _mm_loadu_ps(kptr+28);
#if __AVX__
_sum0 = _mm_fmadd_ps(_r1, _k0, _sum0);
_sum1 = _mm_fmadd_ps(_r1, _k1, _sum1);
_sum2 = _mm_fmadd_ps(_r1, _k2, _sum2);
_sum3 = _mm_fmadd_ps(_r1, _k3, _sum3);
_sum4 = _mm_fmadd_ps(_r1, _k4, _sum4);
_sum5 = _mm_fmadd_ps(_r1, _k5, _sum5);
_sum6 = _mm_fmadd_ps(_r1, _k6, _sum6);
_sum7 = _mm_fmadd_ps(_r1, _k7, _sum7);
#else
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r1, _k0));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r1, _k1));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r1, _k2));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r1, _k3));
_sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r1, _k4));
_sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r1, _k5));
_sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r1, _k6));
_sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r1, _k7));
#endif
kptr += 32;
_k0 = _mm_loadu_ps(kptr);
_k1 = _mm_loadu_ps(kptr+4);
_k2 = _mm_loadu_ps(kptr+8);
_k3 = _mm_loadu_ps(kptr+12);
_k4 = _mm_loadu_ps(kptr+16);
_k5 = _mm_loadu_ps(kptr+20);
_k6 = _mm_loadu_ps(kptr+24);
_k7 = _mm_loadu_ps(kptr+28);
#if __AVX__
_sum0 = _mm_fmadd_ps(_r2, _k0, _sum0);
_sum1 = _mm_fmadd_ps(_r2, _k1, _sum1);
_sum2 = _mm_fmadd_ps(_r2, _k2, _sum2);
_sum3 = _mm_fmadd_ps(_r2, _k3, _sum3);
_sum4 = _mm_fmadd_ps(_r2, _k4, _sum4);
_sum5 = _mm_fmadd_ps(_r2, _k5, _sum5);
_sum6 = _mm_fmadd_ps(_r2, _k6, _sum6);
_sum7 = _mm_fmadd_ps(_r2, _k7, _sum7);
#else
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r2, _k0));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r2, _k1));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r2, _k2));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r2, _k3));
_sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r2, _k4));
_sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r2, _k5));
_sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r2, _k6));
_sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r2, _k7));
#endif
kptr += 32;
_k0 = _mm_loadu_ps(kptr);
_k1 = _mm_loadu_ps(kptr+4);
_k2 = _mm_loadu_ps(kptr+8);
_k3 = _mm_loadu_ps(kptr+12);
_k4 = _mm_loadu_ps(kptr+16);
_k5 = _mm_loadu_ps(kptr+20);
_k6 = _mm_loadu_ps(kptr+24);
_k7 = _mm_loadu_ps(kptr+28);
#if __AVX__
_sum0 = _mm_fmadd_ps(_r3, _k0, _sum0);
_sum1 = _mm_fmadd_ps(_r3, _k1, _sum1);
_sum2 = _mm_fmadd_ps(_r3, _k2, _sum2);
_sum3 = _mm_fmadd_ps(_r3, _k3, _sum3);
_sum4 = _mm_fmadd_ps(_r3, _k4, _sum4);
_sum5 = _mm_fmadd_ps(_r3, _k5, _sum5);
_sum6 = _mm_fmadd_ps(_r3, _k6, _sum6);
_sum7 = _mm_fmadd_ps(_r3, _k7, _sum7);
#else
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r3, _k0));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r3, _k1));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r3, _k2));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r3, _k3));
_sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r3, _k4));
_sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r3, _k5));
_sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r3, _k6));
_sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r3, _k7));
#endif
kptr += 32;
r0 += 16;
}
for (; q<inch; q++)
{
__m128 _r0 = _mm_loadu_ps(r0);
__m128 _k0 = _mm_loadu_ps(kptr);
__m128 _k1 = _mm_loadu_ps(kptr+4);
__m128 _k2 = _mm_loadu_ps(kptr+8);
__m128 _k3 = _mm_loadu_ps(kptr+12);
__m128 _k4 = _mm_loadu_ps(kptr+16);
__m128 _k5 = _mm_loadu_ps(kptr+20);
__m128 _k6 = _mm_loadu_ps(kptr+24);
__m128 _k7 = _mm_loadu_ps(kptr+28);
#if __AVX__
_sum0 = _mm_fmadd_ps(_r0, _k0, _sum0);
_sum1 = _mm_fmadd_ps(_r0, _k1, _sum1);
_sum2 = _mm_fmadd_ps(_r0, _k2, _sum2);
_sum3 = _mm_fmadd_ps(_r0, _k3, _sum3);
_sum4 = _mm_fmadd_ps(_r0, _k4, _sum4);
_sum5 = _mm_fmadd_ps(_r0, _k5, _sum5);
_sum6 = _mm_fmadd_ps(_r0, _k6, _sum6);
_sum7 = _mm_fmadd_ps(_r0, _k7, _sum7);
#else
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r0, _k0));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r0, _k1));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r0, _k2));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r0, _k3));
_sum4 = _mm_add_ps(_sum4, _mm_mul_ps(_r0, _k4));
_sum5 = _mm_add_ps(_sum5, _mm_mul_ps(_r0, _k5));
_sum6 = _mm_add_ps(_sum6, _mm_mul_ps(_r0, _k6));
_sum7 = _mm_add_ps(_sum7, _mm_mul_ps(_r0, _k7));
#endif
kptr += 32;
r0 += 4;
}
_mm_storeu_ps(output0_tm, _sum0);
_mm_storeu_ps(output1_tm, _sum1);
_mm_storeu_ps(output2_tm, _sum2);
_mm_storeu_ps(output3_tm, _sum3);
_mm_storeu_ps(output4_tm, _sum4);
_mm_storeu_ps(output5_tm, _sum5);
_mm_storeu_ps(output6_tm, _sum6);
_mm_storeu_ps(output7_tm, _sum7);
#else
float sum0[4] = {0};
float sum1[4] = {0};
float sum2[4] = {0};
float sum3[4] = {0};
float sum4[4] = {0};
float sum5[4] = {0};
float sum6[4] = {0};
float sum7[4] = {0};
for (int q=0; q<inch; q++)
{
for (int n=0; n<4; n++)
{
sum0[n] += r0[n] * kptr[n];
sum1[n] += r0[n] * kptr[n+4];
sum2[n] += r0[n] * kptr[n+8];
sum3[n] += r0[n] * kptr[n+12];
sum4[n] += r0[n] * kptr[n+16];
sum5[n] += r0[n] * kptr[n+20];
sum6[n] += r0[n] * kptr[n+24];
sum7[n] += r0[n] * kptr[n+28];
}
kptr += 32;
r0 += 4;
}
for (int n=0; n<4; n++)
{
output0_tm[n] = sum0[n];
output1_tm[n] = sum1[n];
output2_tm[n] = sum2[n];
output3_tm[n] = sum3[n];
output4_tm[n] = sum4[n];
output5_tm[n] = sum5[n];
output6_tm[n] = sum6[n];
output7_tm[n] = sum7[n];
}
#endif // __AVX__
output0_tm += 36;
output1_tm += 36;
output2_tm += 36;
output3_tm += 36;
output4_tm += 36;
output5_tm += 36;
output6_tm += 36;
output7_tm += 36;
}
}
nn_outch = (outch - remain_outch_start) >> 2;
for (int pp=0; pp<nn_outch; pp++)
{
int p = remain_outch_start + pp * 4;
float* output0_tm = top_blob_tm.channel(p);
float* output1_tm = top_blob_tm.channel(p+1);
float* output2_tm = top_blob_tm.channel(p+2);
float* output3_tm = top_blob_tm.channel(p+3);
output0_tm = output0_tm + r*4;
output1_tm = output1_tm + r*4;
output2_tm = output2_tm + r*4;
output3_tm = output3_tm + r*4;
for (int i=0; i<tiles; i++)
{
const float* kptr = kernel_tm_test[r].channel(p/8 + (p%8)/4);
const float* r0 = bottom_blob_tm.channel(tiles*r+i);
#if __AVX__ || __SSE__
#if __AVX__
float zero_val = 0.f;
__m128 _sum0 = _mm_broadcast_ss(&zero_val);
__m128 _sum1 = _mm_broadcast_ss(&zero_val);
__m128 _sum2 = _mm_broadcast_ss(&zero_val);
__m128 _sum3 = _mm_broadcast_ss(&zero_val);
#else
__m128 _sum0 = _mm_set1_ps(0.f);
__m128 _sum1 = _mm_set1_ps(0.f);
__m128 _sum2 = _mm_set1_ps(0.f);
__m128 _sum3 = _mm_set1_ps(0.f);
#endif
for (int q=0; q<inch; q++)
{
__m128 _r0 = _mm_loadu_ps(r0);
__m128 _k0 = _mm_loadu_ps(kptr);
__m128 _k1 = _mm_loadu_ps(kptr+4);
__m128 _k2 = _mm_loadu_ps(kptr+8);
__m128 _k3 = _mm_loadu_ps(kptr+12);
#if __AVX__
_sum0 = _mm_fmadd_ps(_r0, _k0, _sum0);
_sum1 = _mm_fmadd_ps(_r0, _k1, _sum1);
_sum2 = _mm_fmadd_ps(_r0, _k2, _sum2);
_sum3 = _mm_fmadd_ps(_r0, _k3, _sum3);
#else
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r0, _k0));
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_r0, _k1));
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_r0, _k2));
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_r0, _k3));
#endif
kptr += 16;
r0 += 4;
}
_mm_storeu_ps(output0_tm, _sum0);
_mm_storeu_ps(output1_tm, _sum1);
_mm_storeu_ps(output2_tm, _sum2);
_mm_storeu_ps(output3_tm, _sum3);
#else
float sum0[4] = {0};
float sum1[4] = {0};
float sum2[4] = {0};
float sum3[4] = {0};
for (int q=0; q<inch; q++)
{
for (int n=0; n<4; n++)
{
sum0[n] += r0[n] * kptr[n];
sum1[n] += r0[n] * kptr[n+4];
sum2[n] += r0[n] * kptr[n+8];
sum3[n] += r0[n] * kptr[n+12];
}
kptr += 16;
r0 += 4;
}
for (int n=0; n<4; n++)
{
output0_tm[n] = sum0[n];
output1_tm[n] = sum1[n];
output2_tm[n] = sum2[n];
output3_tm[n] = sum3[n];
}
#endif // __AVX__
output0_tm += 36;
output1_tm += 36;
output2_tm += 36;
output3_tm += 36;
}
}
remain_outch_start += nn_outch << 2;
for (int p=remain_outch_start; p<outch; p++)
{
float* output0_tm = top_blob_tm.channel(p);
output0_tm = output0_tm + r*4;
for (int i=0; i<tiles; i++)
{
const float* kptr = kernel_tm_test[r].channel(p/8 + (p%8)/4 + p%4);
const float* r0 = bottom_blob_tm.channel(tiles*r+i);
#if __AVX__ || __SSE__
#if __AVX__
float zero_val = 0.f;
__m128 _sum0 = _mm_broadcast_ss(&zero_val);
#else
__m128 _sum0 = _mm_set1_ps(0.f);
#endif
for (int q=0; q<inch; q++)
{
__m128 _r0 = _mm_loadu_ps(r0);
__m128 _k0 = _mm_loadu_ps(kptr);
#if __AVX__
_sum0 = _mm_fmadd_ps(_r0, _k0, _sum0);
#else
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_r0, _k0));
#endif
kptr += 16;
r0 += 4;
}
_mm_storeu_ps(output0_tm, _sum0);
#else
float sum0[4] = {0};
for (int q=0; q<inch; q++)
{
for (int n=0; n<4; n++)
{
sum0[n] += (int)r0[n] * kptr[n];
}
kptr += 4;
r0 += 4;
}
for (int n=0; n<4; n++)
{
output0_tm[n] = sum0[n];
}
#endif // __AVX__ || __SSE__
output0_tm += 36;
}
}
// for (int p=0; p<outch; p++)
// {
// Mat out0_tm = top_blob_tm.channel(p);
// const Mat kernel0_tm = kernel_tm.channel(p);
// for (int i=0; i<tiles; i++)
// {
// float* output0_tm = out0_tm.row<int>(i);
// int sum0[36] = {0};
// for (int q=0; q<inch; q++)
// {
// const float* r0 = bottom_blob_tm.channel(q).row<float>(i);
// const float* k0 = kernel0_tm.row<float>(q);
// for (int n=0; n<36; n++)
// {
// sum0[n] += (int)r0[n] * k0[n];
// }
// }
// for (int n=0; n<36; n++)
// {
// output0_tm[n] = sum0[n];
// }
// }
// }
}
}
bottom_blob_tm = Mat();
// END dot
// BEGIN transform output
Mat top_blob_bordered;
top_blob_bordered.create(outw, outh, outch, elemsize, opt.workspace_allocator);
{
// AT
// const float itm[4][6] = {
// {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 0.0f},
// {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 0.0f},
// {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 1.0f}
// };
// 0 = r00 + r01 + r02 + r03 + r04
// 1 = r01 - r02 + 2 * (r03 - r04)
// 2 = r01 + r02 + 4 * (r03 + r04)
// 3 = r01 - r02 + 8 * (r03 - r04) + r05
int w_tm = outw / 4 * 6;
int h_tm = outh / 4 * 6;
int nColBlocks = h_tm/6; // may be the block num in Feathercnn
int nRowBlocks = w_tm/6;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=0; p<outch; p++)
{
float* out_tile = top_blob_tm.channel(p);
float* outRow0 = top_blob_bordered.channel(p);
float* outRow1 = outRow0 + outw;
float* outRow2 = outRow0 + outw * 2;
float* outRow3 = outRow0 + outw * 3;
const float bias0 = bias ? bias[p] : 0.f;
for (int j=0; j<nColBlocks; j++)
{
for(int i=0; i<nRowBlocks; i++)
{
// TODO AVX2
float s0[6],s1[6],s2[6],s3[6],s4[6],s5[6];
float w0[6],w1[6],w2[6],w3[6];
float d0[4],d1[4],d2[4],d3[4],d4[4],d5[4];
float o0[4],o1[4],o2[4],o3[4];
// load
for (int n = 0; n < 6; n++)
{
s0[n] = out_tile[n];
s1[n] = out_tile[n+ 6];
s2[n] = out_tile[n+12];
s3[n] = out_tile[n+18];
s4[n] = out_tile[n+24];
s5[n] = out_tile[n+30];
}
// w = A_T * W
for (int n = 0; n < 6; n++)
{
w0[n] = s0[n] + s1[n] + s2[n] + s3[n] + s4[n];
w1[n] = s1[n] - s2[n] + 2*s3[n] - 2*s4[n];
w2[n] = s1[n] + s2[n] + 4*s3[n] + 4*s4[n];
w3[n] = s1[n] - s2[n] + 8*s3[n] - 8*s4[n] + s5[n];
}
// transpose w to w_t
{
d0[0] = w0[0]; d0[1] = w1[0]; d0[2] = w2[0]; d0[3] = w3[0];
d1[0] = w0[1]; d1[1] = w1[1]; d1[2] = w2[1]; d1[3] = w3[1];
d2[0] = w0[2]; d2[1] = w1[2]; d2[2] = w2[2]; d2[3] = w3[2];
d3[0] = w0[3]; d3[1] = w1[3]; d3[2] = w2[3]; d3[3] = w3[3];
d4[0] = w0[4]; d4[1] = w1[4]; d4[2] = w2[4]; d4[3] = w3[4];
d5[0] = w0[5]; d5[1] = w1[5]; d5[2] = w2[5]; d5[3] = w3[5];
}
// Y = A_T * w_t
for (int n = 0; n < 4; n++)
{
o0[n] = d0[n] + d1[n] + d2[n] + d3[n] + d4[n];
o1[n] = d1[n] - d2[n] + 2*d3[n] - 2*d4[n];
o2[n] = d1[n] + d2[n] + 4*d3[n] + 4*d4[n];
o3[n] = d1[n] - d2[n] + 8*d3[n] - 8*d4[n] + d5[n];
}
// save to top blob tm
for (int n = 0; n < 4; n++)
{
outRow0[n] = o0[n] + bias0;
outRow1[n] = o1[n] + bias0;
outRow2[n] = o2[n] + bias0;
outRow3[n] = o3[n] + bias0;
}
out_tile += 36;
outRow0 += 4;
outRow1 += 4;
outRow2 += 4;
outRow3 += 4;
}
outRow0 += outw * 3;
outRow1 += outw * 3;
outRow2 += outw * 3;
outRow3 += outw * 3;
}
}
}
// END transform output
// cut result pad
copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt.blob_allocator, opt.num_threads);
}
static void conv3x3s2_sse(const Mat &bottom_blob, Mat &top_blob, const Mat &_kernel, const Mat& _bias, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const int tailstep = w - 2 * outw + w;
const float* kernel = _kernel;
const float* bias = _bias;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p = 0; p < outch; p++)
{
Mat out = top_blob.channel(p);
const float bias0 = bias ? bias[p] : 0.f;
out.fill(bias0);
for (int q = 0; q < inch; q++)
{
float *outptr = out;
const float *img = bottom_blob.channel(q);
const float* kernel0 = kernel + p*inch*9 + q*9;
const float *r0 = img;
const float *r1 = img + w;
const float *r2 = img + w * 2;
const float* k0 = kernel0;
const float* k1 = kernel0 + 3;
const float* k2 = kernel0 + 6;
for (int i = 0; i < outh; i++)
{
int remain = outw;
for (; remain > 0; remain--)
{
float sum = 0;
sum += r0[0] * k0[0];
sum += r0[1] * k0[1];
sum += r0[2] * k0[2];
sum += r1[0] * k1[0];
sum += r1[1] * k1[1];
sum += r1[2] * k1[2];
sum += r2[0] * k2[0];
sum += r2[1] * k2[1];
sum += r2[2] * k2[2];
*outptr += sum;
r0 += 2;
r1 += 2;
r2 += 2;
outptr++;
}
r0 += tailstep;
r1 += tailstep;
r2 += tailstep;
}
}
}
}
|
corleonechensiyu/ncnn-8-12
|
src/layer/reverse.h
|
#ifndef LAYER_REVERSE_H
#define LAYER_REVERSE_H
#include "layer.h"
namespace ncnn {
class Reverse : public Layer
{
public:
Reverse();
// virtual int forward_inplace(Mat& bottom_top_blob, const Option& opt) const;
virtual int forward(const Mat& bottom_blob, Mat& top_blob, const Option& opt) const;
};
} // namespace ncnn
#endif // LAYER_REVERSE_H
|
corleonechensiyu/ncnn-8-12
|
examples/ocr.h
|
#include <stdio.h>
#include <vector>
#include "platform.h"
#include "net.h"
#include <iostream>
#include <string>
#include "benchmark.h"
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <cpu.h>
#include <unistd.h>
using namespace std;
static int detect(const cv::Mat& bgr , vector<float>& scores)
{
ncnn::Net ocr;
ocr.load_param("dd-v3.param");
ocr.load_model("dd-v3.bin");
ncnn::Mat in = ncnn::Mat::from_pixels_resize(bgr.data,ncnn::Mat::PIXEL_BGR,bgr.cols,bgr.rows,64,32);
const float mean_vals[3]={141.f,135.f,122.f};
in.substract_mean_normalize(mean_vals, 0);
double start = ncnn::get_current_time();
ncnn::Extractor ex = ocr.create_extractor();
ex.set_num_threads(2);
//ncnn::set_cpu_powersave(2);
ex.input("data",in);
ncnn::Mat out;
ex.extract("result",out);
double end = ncnn::get_current_time();
double time = end - start;
static const char* ocr_names[]={"blank","0","1","2","3","4","5","6","7","8","9","."};
string str;
scores.resize(5);
for(int j=0;j<5;j++)
{
//scores[j]=out[j];
if(0<=out[j]-1 && out[j]<12)
{
scores[j]=out[j];
int index=scores[j];
str += ocr_names[index];
}
}
cout<<str<<endl;
cout<<time<<endl;
return 0;
}
|
corleonechensiyu/ncnn-8-12
|
src/layer/x86/convolution_sgemm.h
|
<filename>src/layer/x86/convolution_sgemm.h
// BUG1989 is pleased to support the open source community by supporting ncnn available.
//
// Copyright (C) 2019 BUG1989. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#if __AVX__
static void conv_im2col_sgemm_transform_kernel_sse(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_size)
{
const float* kernel = _kernel;
// kernel memory packed 8 x 8
kernel_tm.create(8*kernel_size, inch, outch/8 + (outch%8)/4 + outch%4);
int nn_outch = 0;
int remain_outch_start = 0;
nn_outch = outch >> 3;
remain_outch_start = nn_outch << 3;
for (int pp=0; pp<nn_outch; pp++)
{
int p = pp * 8;
const float* k0 = kernel + (p+0)*inch*kernel_size;
const float* k1 = kernel + (p+1)*inch*kernel_size;
const float* k2 = kernel + (p+2)*inch*kernel_size;
const float* k3 = kernel + (p+3)*inch*kernel_size;
const float* k4 = kernel + (p+4)*inch*kernel_size;
const float* k5 = kernel + (p+5)*inch*kernel_size;
const float* k6 = kernel + (p+6)*inch*kernel_size;
const float* k7 = kernel + (p+7)*inch*kernel_size;
float* ktmp = kernel_tm.channel(p/8);
for (int q=0; q<inch*kernel_size; q++)
{
ktmp[0] = k0[0];
ktmp[1] = k1[0];
ktmp[2] = k2[0];
ktmp[3] = k3[0];
ktmp[4] = k4[0];
ktmp[5] = k5[0];
ktmp[6] = k6[0];
ktmp[7] = k7[0];
ktmp += 8;
k0 += 1;
k1 += 1;
k2 += 1;
k3 += 1;
k4 += 1;
k5 += 1;
k6 += 1;
k7 += 1;
}
}
nn_outch = (outch - remain_outch_start) >> 2;
for (int pp=0; pp<nn_outch; pp++)
{
int p = remain_outch_start + pp * 4;
const float* k0 = kernel + (p+0)*inch*kernel_size;
const float* k1 = kernel + (p+1)*inch*kernel_size;
const float* k2 = kernel + (p+2)*inch*kernel_size;
const float* k3 = kernel + (p+3)*inch*kernel_size;
float* ktmp = kernel_tm.channel(p/8 + (p%8)/4);
for (int q=0; q<inch*kernel_size; q++)
{
ktmp[0] = k0[0];
ktmp[1] = k1[0];
ktmp[2] = k2[0];
ktmp[3] = k3[0];
ktmp += 4;
k0 += 1;
k1 += 1;
k2 += 1;
k3 += 1;
}
}
remain_outch_start += nn_outch << 2;
for (int p=remain_outch_start; p<outch; p++)
{
const float* k0 = kernel + (p+0)*inch*kernel_size;
float* ktmp = kernel_tm.channel(p/8 + (p%8)/4 + p%4);
for (int q=0; q<inch*kernel_size; q++)
{
ktmp[0] = k0[0];
ktmp++;
k0++;
}
}
}
static void conv_im2col_sgemm_sse(const Mat &bottom_blob, Mat &top_blob, const Mat & kernel_tm, const Mat& _bias, \
const int kernel_w, const int kernel_h, const int stride_w, const int stride_h, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
size_t elemsize = bottom_blob.elemsize;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const float* bias = _bias;
// im2col
Mat bottom_im2col(outw*outh, kernel_h*kernel_w*inch, elemsize, opt.workspace_allocator);
{
const int stride = kernel_h*kernel_w*outw*outh;
float* ret = (float*)bottom_im2col;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=0; p<inch; p++)
{
const float* input = bottom_blob.channel(p);
int retID = stride * p;
for (int u=0; u<kernel_h; u++)
{
for (int v=0; v<kernel_w; v++)
{
for (int i=0; i<outh; i++)
{
for (int j=0; j<outw; j++)
{
int row = u + i * stride_h;
int col = v + j * stride_w;
int index = row * w + col;
ret[retID] = input[index];
retID++;
}
}
}
}
}
}
int kernel_size = kernel_w * kernel_h;
int out_size = outw * outh;
// bottom_im2col memory packed 8 x 8
Mat bottom_tm(8*kernel_size, inch, out_size/8 + out_size%8, elemsize, opt.workspace_allocator);
{
int nn_size = out_size >> 3;
int remain_size_start = nn_size << 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii=0; ii<nn_size; ii++)
{
int i = ii * 8;
const float* img0 = bottom_im2col.channel(0);
img0 += i;
float* tmpptr = bottom_tm.channel(i/8);
for (int q=0; q<inch*kernel_size; q++)
{
#if __AVX__
_mm256_storeu_ps(tmpptr, _mm256_loadu_ps(img0));
#else
tmpptr[0] = img0[0];
tmpptr[1] = img0[1];
tmpptr[2] = img0[2];
tmpptr[3] = img0[3];
tmpptr[4] = img0[4];
tmpptr[5] = img0[5];
tmpptr[6] = img0[6];
tmpptr[7] = img0[7];
#endif // __SSE__
tmpptr += 8;
img0 += out_size;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int i=remain_size_start; i<out_size; i++)
{
const float* img0 = bottom_im2col.channel(0);
img0 += i;
float* tmpptr = bottom_tm.channel(i/8 + i%8);
for (int q=0; q<inch*kernel_size; q++)
{
tmpptr[0] = img0[0];
tmpptr += 1;
img0 += out_size;
}
}
}
// sgemm(int M, int N, int L, float* A, float* B, float* C)
{
//int M = outch; // outch
int N = outw * outh; // outsize or out stride
int L = kernel_w * kernel_h * inch; // ksize * inch
int nn_outch = 0;
int remain_outch_start = 0;
nn_outch = outch >> 3;
remain_outch_start = nn_outch << 3;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp<nn_outch; pp++)
{
int i = pp * 8;
float* output0 = top_blob.channel(i);
float* output1 = top_blob.channel(i+1);
float* output2 = top_blob.channel(i+2);
float* output3 = top_blob.channel(i+3);
float* output4 = top_blob.channel(i+4);
float* output5 = top_blob.channel(i+5);
float* output6 = top_blob.channel(i+6);
float* output7 = top_blob.channel(i+7);
const float zeros[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + i : zeros;
int j=0;
for (; j+7<N; j=j+8)
{
const float* vb = bottom_tm.channel(j/8);
const float* va = kernel_tm.channel(i/8);
#if __AVX__
__m256 _sum0 = _mm256_broadcast_ss(biasptr);
__m256 _sum1 = _mm256_broadcast_ss(biasptr+1);
__m256 _sum2 = _mm256_broadcast_ss(biasptr+2);
__m256 _sum3 = _mm256_broadcast_ss(biasptr+3);
__m256 _sum4 = _mm256_broadcast_ss(biasptr+4);
__m256 _sum5 = _mm256_broadcast_ss(biasptr+5);
__m256 _sum6 = _mm256_broadcast_ss(biasptr+6);
__m256 _sum7 = _mm256_broadcast_ss(biasptr+7);
int k=0;
for (; k+3<L; k=k+4)
{
// k0
__m256 _va0 = _mm256_broadcast_ss(va);
__m256 _va1 = _mm256_broadcast_ss(va+1);
__m256 _va2 = _mm256_broadcast_ss(va+2);
__m256 _va3 = _mm256_broadcast_ss(va+3);
__m256 _vb0 = _mm256_loadu_ps(vb);
__m256 _vb1 = _mm256_loadu_ps(vb+8);
__m256 _vb2 = _mm256_loadu_ps(vb+16);
__m256 _vb3 = _mm256_loadu_ps(vb+24);
_sum0 = _mm256_fmadd_ps(_vb0, _va0, _sum0); // sum0 = (a00-a07) * k00
_sum1 = _mm256_fmadd_ps(_vb0, _va1, _sum1); // sum1 = (a00-a07) * k10
_sum2 = _mm256_fmadd_ps(_vb0, _va2, _sum2); // sum2 = (a00-a07) * k20
_sum3 = _mm256_fmadd_ps(_vb0, _va3, _sum3); // sum3 = (a00-a07) * k30
_va0 = _mm256_broadcast_ss(va+4);
_va1 = _mm256_broadcast_ss(va+5);
_va2 = _mm256_broadcast_ss(va+6);
_va3 = _mm256_broadcast_ss(va+7);
_sum4 = _mm256_fmadd_ps(_vb0, _va0, _sum4); // sum4 = (a00-a07) * k40
_sum5 = _mm256_fmadd_ps(_vb0, _va1, _sum5); // sum5 = (a00-a07) * k50
_sum6 = _mm256_fmadd_ps(_vb0, _va2, _sum6); // sum6 = (a00-a07) * k60
_sum7 = _mm256_fmadd_ps(_vb0, _va3, _sum7); // sum7 = (a00-a07) * k70
va += 8;
// k1
_va0 = _mm256_broadcast_ss(va);
_va1 = _mm256_broadcast_ss(va+1);
_va2 = _mm256_broadcast_ss(va+2);
_va3 = _mm256_broadcast_ss(va+3);
_sum0 = _mm256_fmadd_ps(_vb1, _va0, _sum0); // sum0 += (a10-a17) * k01
_sum1 = _mm256_fmadd_ps(_vb1, _va1, _sum1); // sum1 += (a10-a17) * k11
_sum2 = _mm256_fmadd_ps(_vb1, _va2, _sum2); // sum2 += (a10-a17) * k21
_sum3 = _mm256_fmadd_ps(_vb1, _va3, _sum3); // sum3 += (a10-a17) * k31
_va0 = _mm256_broadcast_ss(va+4);
_va1 = _mm256_broadcast_ss(va+5);
_va2 = _mm256_broadcast_ss(va+6);
_va3 = _mm256_broadcast_ss(va+7);
_sum4 = _mm256_fmadd_ps(_vb1, _va0, _sum4); // sum4 += (a10-a17) * k41
_sum5 = _mm256_fmadd_ps(_vb1, _va1, _sum5); // sum5 += (a10-a17) * k51
_sum6 = _mm256_fmadd_ps(_vb1, _va2, _sum6); // sum6 += (a10-a17) * k61
_sum7 = _mm256_fmadd_ps(_vb1, _va3, _sum7); // sum7 += (a10-a17) * k71
va += 8;
// k2
_va0 = _mm256_broadcast_ss(va);
_va1 = _mm256_broadcast_ss(va+1);
_va2 = _mm256_broadcast_ss(va+2);
_va3 = _mm256_broadcast_ss(va+3);
_sum0 = _mm256_fmadd_ps(_vb2, _va0, _sum0); // sum0 += (a20-a27) * k02
_sum1 = _mm256_fmadd_ps(_vb2, _va1, _sum1); // sum1 += (a20-a27) * k12
_sum2 = _mm256_fmadd_ps(_vb2, _va2, _sum2); // sum2 += (a20-a27) * k22
_sum3 = _mm256_fmadd_ps(_vb2, _va3, _sum3); // sum3 += (a20-a27) * k32
_va0 = _mm256_broadcast_ss(va+4);
_va1 = _mm256_broadcast_ss(va+5);
_va2 = _mm256_broadcast_ss(va+6);
_va3 = _mm256_broadcast_ss(va+7);
_sum4 = _mm256_fmadd_ps(_vb2, _va0, _sum4); // sum4 += (a20-a27) * k42
_sum5 = _mm256_fmadd_ps(_vb2, _va1, _sum5); // sum5 += (a20-a27) * k52
_sum6 = _mm256_fmadd_ps(_vb2, _va2, _sum6); // sum6 += (a20-a27) * k62
_sum7 = _mm256_fmadd_ps(_vb2, _va3, _sum7); // sum7 += (a20-a27) * k72
va += 8;
// k3
_va0 = _mm256_broadcast_ss(va);
_va1 = _mm256_broadcast_ss(va+1);
_va2 = _mm256_broadcast_ss(va+2);
_va3 = _mm256_broadcast_ss(va+3);
_sum0 = _mm256_fmadd_ps(_vb3, _va0, _sum0); // sum0 += (a30-a37) * k03
_sum1 = _mm256_fmadd_ps(_vb3, _va1, _sum1); // sum1 += (a30-a37) * k13
_sum2 = _mm256_fmadd_ps(_vb3, _va2, _sum2); // sum2 += (a30-a37) * k23
_sum3 = _mm256_fmadd_ps(_vb3, _va3, _sum3); // sum3 += (a30-a37) * k33
_va0 = _mm256_broadcast_ss(va+4);
_va1 = _mm256_broadcast_ss(va+5);
_va2 = _mm256_broadcast_ss(va+6);
_va3 = _mm256_broadcast_ss(va+7);
_sum4 = _mm256_fmadd_ps(_vb3, _va0, _sum4); // sum4 += (a30-a37) * k43
_sum5 = _mm256_fmadd_ps(_vb3, _va1, _sum5); // sum5 += (a30-a37) * k53
_sum6 = _mm256_fmadd_ps(_vb3, _va2, _sum6); // sum6 += (a30-a37) * k63
_sum7 = _mm256_fmadd_ps(_vb3, _va3, _sum7); // sum7 += (a30-a37) * k73
va += 8;
vb += 32;
}
for (; k<L; k++)
{
// k0
__m256 _va0 = _mm256_broadcast_ss(va);
__m256 _va1 = _mm256_broadcast_ss(va+1);
__m256 _va2 = _mm256_broadcast_ss(va+2);
__m256 _va3 = _mm256_broadcast_ss(va+3);
__m256 _va4 = _mm256_broadcast_ss(va+4);
__m256 _va5 = _mm256_broadcast_ss(va+5);
__m256 _va6 = _mm256_broadcast_ss(va+6);
__m256 _va7 = _mm256_broadcast_ss(va+7);
__m256 _vb0 = _mm256_loadu_ps(vb);
_sum0 = _mm256_fmadd_ps(_vb0, _va0, _sum0); // sum0 = (a00-a07) * k00
_sum1 = _mm256_fmadd_ps(_vb0, _va1, _sum1); // sum1 = (a00-a07) * k10
_sum2 = _mm256_fmadd_ps(_vb0, _va2, _sum2); // sum2 = (a00-a07) * k20
_sum3 = _mm256_fmadd_ps(_vb0, _va3, _sum3); // sum3 = (a00-a07) * k30
_sum4 = _mm256_fmadd_ps(_vb0, _va4, _sum4); // sum4 = (a00-a07) * k40
_sum5 = _mm256_fmadd_ps(_vb0, _va5, _sum5); // sum5 = (a00-a07) * k50
_sum6 = _mm256_fmadd_ps(_vb0, _va6, _sum6); // sum6 = (a00-a07) * k60
_sum7 = _mm256_fmadd_ps(_vb0, _va7, _sum7); // sum7 = (a00-a07) * k70
va += 8;
vb += 8;
}
_mm256_storeu_ps(output0, _sum0);
_mm256_storeu_ps(output1, _sum1);
_mm256_storeu_ps(output2, _sum2);
_mm256_storeu_ps(output3, _sum3);
_mm256_storeu_ps(output4, _sum4);
_mm256_storeu_ps(output5, _sum5);
_mm256_storeu_ps(output6, _sum6);
_mm256_storeu_ps(output7, _sum7);
#else
float sum0[8] = {0};
float sum1[8] = {0};
float sum2[8] = {0};
float sum3[8] = {0};
float sum4[8] = {0};
float sum5[8] = {0};
float sum6[8] = {0};
float sum7[8] = {0};
int k=0;
for (; k+7<L; k=k+8)
{
for (int n=0; n<8; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
sum4[n] += va[4] * vb[n];
sum5[n] += va[5] * vb[n];
sum6[n] += va[6] * vb[n];
sum7[n] += va[7] * vb[n];
va += 8;
sum0[n] += va[0] * vb[n+8];
sum1[n] += va[1] * vb[n+8];
sum2[n] += va[2] * vb[n+8];
sum3[n] += va[3] * vb[n+8];
sum4[n] += va[4] * vb[n+8];
sum5[n] += va[5] * vb[n+8];
sum6[n] += va[6] * vb[n+8];
sum7[n] += va[7] * vb[n+8];
va += 8;
sum0[n] += va[0] * vb[n+16];
sum1[n] += va[1] * vb[n+16];
sum2[n] += va[2] * vb[n+16];
sum3[n] += va[3] * vb[n+16];
sum4[n] += va[4] * vb[n+16];
sum5[n] += va[5] * vb[n+16];
sum6[n] += va[6] * vb[n+16];
sum7[n] += va[7] * vb[n+16];
va += 8;
sum0[n] += va[0] * vb[n+24];
sum1[n] += va[1] * vb[n+24];
sum2[n] += va[2] * vb[n+24];
sum3[n] += va[3] * vb[n+24];
sum4[n] += va[4] * vb[n+24];
sum5[n] += va[5] * vb[n+24];
sum6[n] += va[6] * vb[n+24];
sum7[n] += va[7] * vb[n+24];
va += 8;
sum0[n] += va[0] * vb[n+32];
sum1[n] += va[1] * vb[n+32];
sum2[n] += va[2] * vb[n+32];
sum3[n] += va[3] * vb[n+32];
sum4[n] += va[4] * vb[n+32];
sum5[n] += va[5] * vb[n+32];
sum6[n] += va[6] * vb[n+32];
sum7[n] += va[7] * vb[n+32];
va += 8;
sum0[n] += va[0] * vb[n+40];
sum1[n] += va[1] * vb[n+40];
sum2[n] += va[2] * vb[n+40];
sum3[n] += va[3] * vb[n+40];
sum4[n] += va[4] * vb[n+40];
sum5[n] += va[5] * vb[n+40];
sum6[n] += va[6] * vb[n+40];
sum7[n] += va[7] * vb[n+40];
va += 8;
sum0[n] += va[0] * vb[n+48];
sum1[n] += va[1] * vb[n+48];
sum2[n] += va[2] * vb[n+48];
sum3[n] += va[3] * vb[n+48];
sum4[n] += va[4] * vb[n+48];
sum5[n] += va[5] * vb[n+48];
sum6[n] += va[6] * vb[n+48];
sum7[n] += va[7] * vb[n+48];
va += 8;
sum0[n] += va[0] * vb[n+56];
sum1[n] += va[1] * vb[n+56];
sum2[n] += va[2] * vb[n+56];
sum3[n] += va[3] * vb[n+56];
sum4[n] += va[4] * vb[n+56];
sum5[n] += va[5] * vb[n+56];
sum6[n] += va[6] * vb[n+56];
sum7[n] += va[7] * vb[n+56];
va -= 56;
}
va += 64;
vb += 64;
}
for (; k<L; k++)
{
for (int n=0; n<8; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
sum4[n] += va[4] * vb[n];
sum5[n] += va[5] * vb[n];
sum6[n] += va[6] * vb[n];
sum7[n] += va[7] * vb[n];
}
va += 8;
vb += 8;
}
for (int n=0; n<8; n++)
{
output0[n] = sum0[n] + biasptr[0];
output1[n] = sum1[n] + biasptr[1];
output2[n] = sum2[n] + biasptr[2];
output3[n] = sum3[n] + biasptr[3];
output4[n] = sum4[n] + biasptr[4];
output5[n] = sum5[n] + biasptr[5];
output6[n] = sum6[n] + biasptr[6];
output7[n] = sum7[n] + biasptr[7];
}
#endif // __AVX__
output0 += 8;
output1 += 8;
output2 += 8;
output3 += 8;
output4 += 8;
output5 += 8;
output6 += 8;
output7 += 8;
}
for (; j<N; j++)
{
const float* vb = bottom_tm.channel(j/8 + j%8);
const float* va = kernel_tm.channel(i/8);
#if __AVX__
__m256 _sum0_7 = _mm256_loadu_ps(biasptr);
__m256 _sum0 = _mm256_set1_ps(0.0);
__m256 _sum1 = _mm256_set1_ps(0.0);
__m256 _sum2 = _mm256_set1_ps(0.0);
__m256 _sum3 = _mm256_set1_ps(0.0);
int k=0;
for (; k+3<L; k=k+4)
{
__m256 _vb0 = _mm256_broadcast_ss(vb);
__m256 _vb1 = _mm256_broadcast_ss(vb+1);
__m256 _vb2 = _mm256_broadcast_ss(vb+2);
__m256 _vb3 = _mm256_broadcast_ss(vb+3);
__m256 _va0 = _mm256_loadu_ps(va);
__m256 _va1 = _mm256_loadu_ps(va+8);
__m256 _va2 = _mm256_loadu_ps(va+16);
__m256 _va3 = _mm256_loadu_ps(va+24);
_sum0 = _mm256_fmadd_ps(_va0, _vb0, _sum0);// sum0 += (k00-k70) * a00
_sum1 = _mm256_fmadd_ps(_va1, _vb1, _sum1);// sum1 += (k01-k71) * a10
_sum2 = _mm256_fmadd_ps(_va2, _vb2, _sum2);// sum2 += (k02-k72) * a20
_sum3 = _mm256_fmadd_ps(_va3, _vb3, _sum3);// sum3 += (k03-k73) * a30
va += 32;
vb += 4;
}
_sum0 = _mm256_add_ps(_sum0, _sum1);
_sum2 = _mm256_add_ps(_sum2, _sum3);
_sum0_7 = _mm256_add_ps(_sum0_7, _sum0);
_sum0_7 = _mm256_add_ps(_sum0_7, _sum2);
for (; k<L; k++)
{
__m256 _vb0 = _mm256_broadcast_ss(vb);
__m256 _va = _mm256_loadu_ps(va);
_sum0_7 = _mm256_fmadd_ps(_va, _vb0, _sum0_7);// sum0 += (k00-k70) * a00
va += 8;
vb += 1;
}
output0[0] = _sum0_7[0];
output1[0] = _sum0_7[1];
output2[0] = _sum0_7[2];
output3[0] = _sum0_7[3];
output4[0] = _sum0_7[4];
output5[0] = _sum0_7[5];
output6[0] = _sum0_7[6];
output7[0] = _sum0_7[7];
#else
float sum0 = biasptr[0];
float sum1 = biasptr[1];
float sum2 = biasptr[2];
float sum3 = biasptr[3];
float sum4 = biasptr[4];
float sum5 = biasptr[5];
float sum6 = biasptr[6];
float sum7 = biasptr[7];
for (int k=0; k<L; k++)
{
sum0 += va[0] * vb[0];
sum1 += va[1] * vb[0];
sum2 += va[2] * vb[0];
sum3 += va[3] * vb[0];
sum4 += va[4] * vb[0];
sum5 += va[5] * vb[0];
sum6 += va[6] * vb[0];
sum7 += va[7] * vb[0];
va += 8;
vb += 1;
}
output0[0] = sum0;
output1[0] = sum1;
output2[0] = sum2;
output3[0] = sum3;
output4[0] = sum4;
output5[0] = sum5;
output6[0] = sum6;
output7[0] = sum7;
#endif // __AVX__
output0++;
output1++;
output2++;
output3++;
output4++;
output5++;
output6++;
output7++;
}
}
nn_outch = (outch - remain_outch_start) >> 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp<nn_outch; pp++)
{
int i = remain_outch_start + pp * 4;
float* output0 = top_blob.channel(i);
float* output1 = top_blob.channel(i+1);
float* output2 = top_blob.channel(i+2);
float* output3 = top_blob.channel(i+3);
const float zeros[4] = {0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + i : zeros;
int j=0;
for (; j+7<N; j=j+8)
{
const float* vb = bottom_tm.channel(j/8);
const float* va = kernel_tm.channel(i/8 + (i%8)/4);
#if __AVX__
__m256 _sum0 = _mm256_broadcast_ss(biasptr);
__m256 _sum1 = _mm256_broadcast_ss(biasptr+1);
__m256 _sum2 = _mm256_broadcast_ss(biasptr+2);
__m256 _sum3 = _mm256_broadcast_ss(biasptr+3);
int k=0;
for (; k+3<L; k=k+4)
{
// k0
__m256 _va0 = _mm256_broadcast_ss(va);
__m256 _va1 = _mm256_broadcast_ss(va+1);
__m256 _va2 = _mm256_broadcast_ss(va+2);
__m256 _va3 = _mm256_broadcast_ss(va+3);
__m256 _vb0 = _mm256_loadu_ps(vb);
__m256 _vb1 = _mm256_loadu_ps(vb+8);
__m256 _vb2 = _mm256_loadu_ps(vb+16);
__m256 _vb3 = _mm256_loadu_ps(vb+24);
_sum0 = _mm256_fmadd_ps(_vb0, _va0, _sum0); // sum0 = (a00-a07) * k00
_sum1 = _mm256_fmadd_ps(_vb0, _va1, _sum1); // sum1 = (a00-a07) * k10
_sum2 = _mm256_fmadd_ps(_vb0, _va2, _sum2); // sum2 = (a00-a07) * k20
_sum3 = _mm256_fmadd_ps(_vb0, _va3, _sum3); // sum3 = (a00-a07) * k30
va += 4;
// k1
_va0 = _mm256_broadcast_ss(va);
_va1 = _mm256_broadcast_ss(va+1);
_va2 = _mm256_broadcast_ss(va+2);
_va3 = _mm256_broadcast_ss(va+3);
_sum0 = _mm256_fmadd_ps(_vb1, _va0, _sum0); // sum0 += (a10-a17) * k01
_sum1 = _mm256_fmadd_ps(_vb1, _va1, _sum1); // sum1 += (a10-a17) * k11
_sum2 = _mm256_fmadd_ps(_vb1, _va2, _sum2); // sum2 += (a10-a17) * k21
_sum3 = _mm256_fmadd_ps(_vb1, _va3, _sum3); // sum3 += (a10-a17) * k31
va += 4;
// k2
_va0 = _mm256_broadcast_ss(va);
_va1 = _mm256_broadcast_ss(va+1);
_va2 = _mm256_broadcast_ss(va+2);
_va3 = _mm256_broadcast_ss(va+3);
_sum0 = _mm256_fmadd_ps(_vb2, _va0, _sum0); // sum0 += (a20-a27) * k02
_sum1 = _mm256_fmadd_ps(_vb2, _va1, _sum1); // sum1 += (a20-a27) * k12
_sum2 = _mm256_fmadd_ps(_vb2, _va2, _sum2); // sum2 += (a20-a27) * k22
_sum3 = _mm256_fmadd_ps(_vb2, _va3, _sum3); // sum3 += (a20-a27) * k32
va += 4;
// k3
_va0 = _mm256_broadcast_ss(va);
_va1 = _mm256_broadcast_ss(va+1);
_va2 = _mm256_broadcast_ss(va+2);
_va3 = _mm256_broadcast_ss(va+3);
_sum0 = _mm256_fmadd_ps(_vb3, _va0, _sum0); // sum0 += (a30-a37) * k03
_sum1 = _mm256_fmadd_ps(_vb3, _va1, _sum1); // sum1 += (a30-a37) * k13
_sum2 = _mm256_fmadd_ps(_vb3, _va2, _sum2); // sum2 += (a30-a37) * k23
_sum3 = _mm256_fmadd_ps(_vb3, _va3, _sum3); // sum3 += (a30-a37) * k33
va += 4;
vb += 32;
}
for (; k<L; k++)
{
// k0
__m256 _va0 = _mm256_broadcast_ss(va);
__m256 _va1 = _mm256_broadcast_ss(va+1);
__m256 _va2 = _mm256_broadcast_ss(va+2);
__m256 _va3 = _mm256_broadcast_ss(va+3);
__m256 _vb0 = _mm256_loadu_ps(vb);
_sum0 = _mm256_fmadd_ps(_vb0, _va0, _sum0); // sum0 = (a00-a07) * k00
_sum1 = _mm256_fmadd_ps(_vb0, _va1, _sum1); // sum1 = (a00-a07) * k10
_sum2 = _mm256_fmadd_ps(_vb0, _va2, _sum2); // sum2 = (a00-a07) * k20
_sum3 = _mm256_fmadd_ps(_vb0, _va3, _sum3); // sum3 = (a00-a07) * k30
va += 4;
vb += 4;
}
_mm256_storeu_ps(output0, _sum0);
_mm256_storeu_ps(output1, _sum1);
_mm256_storeu_ps(output2, _sum2);
_mm256_storeu_ps(output3, _sum3);
#else
float sum0[8] = {0};
float sum1[8] = {0};
float sum2[8] = {0};
float sum3[8] = {0};
int k=0;
for (; k+7<L; k=k+8)
{
for (int n=0; n<8; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
va += 4;
sum0[n] += va[0] * vb[n+8];
sum1[n] += va[1] * vb[n+8];
sum2[n] += va[2] * vb[n+8];
sum3[n] += va[3] * vb[n+8];
va += 4;
sum0[n] += va[0] * vb[n+16];
sum1[n] += va[1] * vb[n+16];
sum2[n] += va[2] * vb[n+16];
sum3[n] += va[3] * vb[n+16];
va += 4;
sum0[n] += va[0] * vb[n+24];
sum1[n] += va[1] * vb[n+24];
sum2[n] += va[2] * vb[n+24];
sum3[n] += va[3] * vb[n+24];
va += 4;
sum0[n] += va[0] * vb[n+32];
sum1[n] += va[1] * vb[n+32];
sum2[n] += va[2] * vb[n+32];
sum3[n] += va[3] * vb[n+32];
va += 4;
sum0[n] += va[0] * vb[n+40];
sum1[n] += va[1] * vb[n+40];
sum2[n] += va[2] * vb[n+40];
sum3[n] += va[3] * vb[n+40];
va += 4;
sum0[n] += va[0] * vb[n+48];
sum1[n] += va[1] * vb[n+48];
sum2[n] += va[2] * vb[n+48];
sum3[n] += va[3] * vb[n+48];
va += 4;
sum0[n] += va[0] * vb[n+56];
sum1[n] += va[1] * vb[n+56];
sum2[n] += va[2] * vb[n+56];
sum3[n] += va[3] * vb[n+56];
va -= 28;
}
va += 32;
vb += 64;
}
for (; k<L; k++)
{
for (int n=0; n<8; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
}
va += 4;
vb += 8;
}
for (int n=0; n<8; n++)
{
output0[n] = sum0[n] + biasptr[0];
output1[n] = sum1[n] + biasptr[1];
output2[n] = sum2[n] + biasptr[2];
output3[n] = sum3[n] + biasptr[3];
}
#endif // __AVX__
output0 += 8;
output1 += 8;
output2 += 8;
output3 += 8;
}
for (; j<N; j++)
{
const float* vb = bottom_tm.channel(j/8 + j%8);
const float* va = kernel_tm.channel(i/8 + (i%8)/4);
#if __AVX__
__m128 _sum0_3 = _mm_loadu_ps(biasptr);
__m128 _sum0 = _mm_set1_ps(0.0);
__m128 _sum1 = _mm_set1_ps(0.0);
__m128 _sum2 = _mm_set1_ps(0.0);
__m128 _sum3 = _mm_set1_ps(0.0);
int k=0;
for (; k+3<L; k=k+4)
{
__m128 _vb0 = _mm_set1_ps(vb[0]);
__m128 _vb1 = _mm_set1_ps(vb[1]);
__m128 _vb2 = _mm_set1_ps(vb[2]);
__m128 _vb3 = _mm_set1_ps(vb[3]);
__m128 _va0 = _mm_loadu_ps(va);
__m128 _va1 = _mm_loadu_ps(va+4);
__m128 _va2 = _mm_loadu_ps(va+8);
__m128 _va3 = _mm_loadu_ps(va+12);
_sum0 = _mm_fmadd_ps(_va0, _vb0, _sum0);// sum0 += (k00-k30) * a00
_sum1 = _mm_fmadd_ps(_va1, _vb1, _sum1);// sum1 += (k01-k31) * a10
_sum2 = _mm_fmadd_ps(_va2, _vb2, _sum2);// sum2 += (k02-k32) * a20
_sum3 = _mm_fmadd_ps(_va3, _vb3, _sum3);// sum3 += (k03-k33) * a30
va += 16;
vb += 4;
}
_sum0 = _mm_add_ps(_sum0, _sum1);
_sum2 = _mm_add_ps(_sum2, _sum3);
_sum0_3 = _mm_add_ps(_sum0_3, _sum0);
_sum0_3 = _mm_add_ps(_sum0_3, _sum2);
for (; k<L; k++)
{
__m128 _vb0 = _mm_set1_ps(vb[0]);
__m128 _va = _mm_loadu_ps(va);
_sum0_3 = _mm_fmadd_ps(_va, _vb0, _sum0_3);// sum0 += (k00-k30) * a00
va += 4;
vb += 1;
}
output0[0] = _sum0_3[0];
output1[0] = _sum0_3[1];
output2[0] = _sum0_3[2];
output3[0] = _sum0_3[3];
#else
float sum0 = biasptr[0];
float sum1 = biasptr[1];
float sum2 = biasptr[2];
float sum3 = biasptr[3];
for (int k=0; k<L; k++)
{
sum0 += va[0] * vb[0];
sum1 += va[1] * vb[0];
sum2 += va[2] * vb[0];
sum3 += va[3] * vb[0];
va += 4;
vb += 1;
}
output0[0] = sum0;
output1[0] = sum1;
output2[0] = sum2;
output3[0] = sum3;
#endif // __AVX__
output0++;
output1++;
output2++;
output3++;
}
}
remain_outch_start += nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int i=remain_outch_start; i<outch; i++)
{
float* output = top_blob.channel(i);
const float bias0 = bias ? bias[i] : 0.f;
int j=0;
for (; j+7<N; j=j+8)
{
const float* vb = bottom_tm.channel(j/8);
const float* va = kernel_tm.channel(i/8 + (i%8)/4 + i%4);
#if __AVX__
__m256 _sum0 = _mm256_broadcast_ss(&bias0);
int k=0;
for (; k+3<L; k=k+4)
{
// k0
__m256 _va0 = _mm256_broadcast_ss(va);
__m256 _va1 = _mm256_broadcast_ss(va+1);
__m256 _va2 = _mm256_broadcast_ss(va+2);
__m256 _va3 = _mm256_broadcast_ss(va+3);
__m256 _vb0 = _mm256_loadu_ps(vb);
__m256 _vb1 = _mm256_loadu_ps(vb+8);
__m256 _vb2 = _mm256_loadu_ps(vb+16);
__m256 _vb3 = _mm256_loadu_ps(vb+24);
_sum0 = _mm256_fmadd_ps(_vb0, _va0, _sum0); // sum0 = (a00-a07) * k00
_sum0 = _mm256_fmadd_ps(_vb1, _va1, _sum0); // sum0 += (a10-a17) * k01
_sum0 = _mm256_fmadd_ps(_vb2, _va2, _sum0); // sum0 += (a20-a27) * k02
_sum0 = _mm256_fmadd_ps(_vb3, _va3, _sum0); // sum0 += (a30-a37) * k03
va += 4;
vb += 32;
}
for (; k<L; k++)
{
// k0
__m256 _va0 = _mm256_broadcast_ss(va);
__m256 _vb0 = _mm256_loadu_ps(vb);
_sum0 = _mm256_fmadd_ps(_vb0, _va0, _sum0); // sum0 = (a00-a07) * k00
va += 1;
vb += 4;
}
_mm256_storeu_ps(output, _sum0);
#else
float sum[8] = {0};
int k=0;
for (; k+7<L; k=k+8)
{
for (int n=0; n<8; n++)
{
sum[n] += va[0] * vb[n];
sum[n] += va[1] * vb[n+8];
sum[n] += va[2] * vb[n+16];
sum[n] += va[3] * vb[n+24];
sum[n] += va[4] * vb[n+32];
sum[n] += va[5] * vb[n+40];
sum[n] += va[6] * vb[n+48];
sum[n] += va[7] * vb[n+56];
}
va += 8;
vb += 64;
}
for (; k<L; k++)
{
for (int n=0; n<8; n++)
{
sum[n] += va[0] * vb[n];
}
va += 1;
vb += 8;
}
for (int n=0; n<8; n++)
{
output[n] = sum[n] + bias0;
}
#endif // __AVX__
output += 8;
}
for (; j<N; j++)
{
const float* vb = bottom_tm.channel(j/8 + j%8);
const float* va = kernel_tm.channel(i/8 + (i%8)/4 + i%4);
int k=0;
#if __AVX__
__m128 _sum0 = _mm_set1_ps(0.f);
for (; k+3<L; k+=4)
{
__m128 _p0 = _mm_loadu_ps(vb);
vb += 4;
__m128 _k0 = _mm_loadu_ps(va);
va += 4;
_sum0 = _mm_fmadd_ps(_p0, _k0, _sum0);
}
float sum0 = bias0 + _sum0[0] + _sum0[1] + _sum0[2] + _sum0[3];
#else
float sum0 = bias0;
#endif // __AVX__
for (; k<L; k++)
{
sum0 += va[0] * vb[0];
va += 1;
vb += 1;
}
output[0] = sum0;
output++;
}
}
}
}
#else
static void conv_im2col_sgemm_transform_kernel_sse(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_size)
{
const float* kernel = _kernel;
// kernel memory packed 4 x 4
kernel_tm.create(4*kernel_size, inch, outch/4 + outch%4);
int nn_outch = 0;
int remain_outch_start = 0;
nn_outch = outch >> 2;
remain_outch_start = nn_outch << 2;
for (int pp=0; pp<nn_outch; pp++)
{
int p = pp * 4;
const float* k0 = kernel + (p+0)*inch*kernel_size;
const float* k1 = kernel + (p+1)*inch*kernel_size;
const float* k2 = kernel + (p+2)*inch*kernel_size;
const float* k3 = kernel + (p+3)*inch*kernel_size;
float* ktmp = kernel_tm.channel(p/4);
for (int q=0; q<inch*kernel_size; q++)
{
ktmp[0] = k0[0];
ktmp[1] = k1[0];
ktmp[2] = k2[0];
ktmp[3] = k3[0];
ktmp += 4;
k0 += 1;
k1 += 1;
k2 += 1;
k3 += 1;
}
}
for (int p=remain_outch_start; p<outch; p++)
{
const float* k0 = kernel + (p+0)*inch*kernel_size;
float* ktmp = kernel_tm.channel(p/4 + p%4);
for (int q=0; q<inch*kernel_size; q++)
{
ktmp[0] = k0[0];
ktmp++;
k0++;
}
}
}
static void conv_im2col_sgemm_sse(const Mat &bottom_blob, Mat &top_blob, const Mat & kernel_tm, const Mat& _bias, \
const int kernel_w, const int kernel_h, const int stride_w, const int stride_h, const Option& opt)
{
int w = bottom_blob.w;
int inch = bottom_blob.c;
size_t elemsize = bottom_blob.elemsize;
int outw = top_blob.w;
int outh = top_blob.h;
int outch = top_blob.c;
const float* bias = _bias;
// im2col
Mat bottom_im2col(outw*outh, kernel_h*kernel_w*inch, elemsize, opt.workspace_allocator);
{
const int stride = kernel_h*kernel_w*outw*outh;
float* ret = (float*)bottom_im2col;
#pragma omp parallel for num_threads(opt.num_threads)
for (int p=0; p<inch; p++)
{
const float* input = bottom_blob.channel(p);
int retID = stride * p;
for (int u=0; u<kernel_h; u++)
{
for (int v=0; v<kernel_w; v++)
{
for (int i=0; i<outh; i++)
{
for (int j=0; j<outw; j++)
{
int row = u + i * stride_h;
int col = v + j * stride_w;
int index = row * w + col;
ret[retID] = input[index];
retID++;
}
}
}
}
}
}
int kernel_size = kernel_w * kernel_h;
int out_size = outw * outh;
// bottom_im2col memory packed 4 x 4
Mat bottom_tm(4*kernel_size, inch, out_size/4 + out_size%4, elemsize, opt.workspace_allocator);
{
int nn_size = out_size >> 2;
int remain_size_start = nn_size << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int ii=0; ii<nn_size; ii++)
{
int i = ii * 4;
const float* img0 = bottom_im2col.channel(0);
img0 += i;
float* tmpptr = bottom_tm.channel(i/4);
for (int q=0; q<inch*kernel_size; q++)
{
#if __SSE__
_mm_storeu_ps(tmpptr, _mm_loadu_ps(img0));
#else
tmpptr[0] = img0[0];
tmpptr[1] = img0[1];
tmpptr[2] = img0[2];
tmpptr[3] = img0[3];
#endif // __SSE__
tmpptr += 4;
img0 += out_size;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int i=remain_size_start; i<out_size; i++)
{
const float* img0 = bottom_im2col.channel(0);
img0 += i;
float* tmpptr = bottom_tm.channel(i/4 + i%4);
for (int q=0; q<inch*kernel_size; q++)
{
tmpptr[0] = img0[0];
tmpptr += 1;
img0 += out_size;
}
}
}
// sgemm(int M, int N, int L, float* A, float* B, float* C)
{
//int M = outch; // outch
int N = outw * outh; // outsize or out stride
int L = kernel_w * kernel_h * inch; // ksize * inch
int nn_outch = 0;
int remain_outch_start = 0;
nn_outch = outch >> 2;
remain_outch_start = nn_outch << 2;
#pragma omp parallel for num_threads(opt.num_threads)
for (int pp=0; pp<nn_outch; pp++)
{
int i = pp * 4;
float* output0 = top_blob.channel(i);
float* output1 = top_blob.channel(i+1);
float* output2 = top_blob.channel(i+2);
float* output3 = top_blob.channel(i+3);
const float zeros[4] = {0.f, 0.f, 0.f, 0.f};
const float* biasptr = bias ? bias + i : zeros;
int j=0;
for (; j+3<N; j=j+4)
{
const float* vb = bottom_tm.channel(j/4);
const float* va = kernel_tm.channel(i/4);
#if __SSE__
__m128 _sum0 = _mm_set1_ps(biasptr[0]);
__m128 _sum1 = _mm_set1_ps(biasptr[1]);
__m128 _sum2 = _mm_set1_ps(biasptr[2]);
__m128 _sum3 = _mm_set1_ps(biasptr[3]);
int k=0;
for (; k+3<L; k=k+4)
{
// k0
__m128 _vb = _mm_loadu_ps(vb);
__m128 _va0 = _mm_set1_ps(va[0]);
__m128 _va1 = _mm_set1_ps(va[1]);
__m128 _va2 = _mm_set1_ps(va[2]);
__m128 _va3 = _mm_set1_ps(va[3]);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb, _va0));// sum0 = (a00-a03) * k00
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_vb, _va1));// sum1 = (a00-a03) * k10
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_vb, _va2));// sum2 = (a00-a03) * k20
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_vb, _va3));// sum3 = (a00-a03) * k30
// k1
_vb = _mm_loadu_ps(vb+4);
_va0 = _mm_set1_ps(va[4]);
_va1 = _mm_set1_ps(va[5]);
_va2 = _mm_set1_ps(va[6]);
_va3 = _mm_set1_ps(va[7]);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb, _va0));// sum0 = (a10-a13) * k01
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_vb, _va1));// sum1 = (a10-a13) * k11
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_vb, _va2));// sum2 = (a10-a13) * k21
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_vb, _va3));// sum3 = (a10-a13) * k31
// k2
_vb = _mm_loadu_ps(vb+8);
_va0 = _mm_set1_ps(va[8]);
_va1 = _mm_set1_ps(va[9]);
_va2 = _mm_set1_ps(va[10]);
_va3 = _mm_set1_ps(va[11]);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb, _va0));// sum0 = (a20-a23) * k02
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_vb, _va1));// sum1 = (a20-a23) * k12
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_vb, _va2));// sum2 = (a20-a23) * k22
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_vb, _va3));// sum3 = (a20-a23) * k32
// k3
_vb = _mm_loadu_ps(vb+12);
_va0 = _mm_set1_ps(va[12]);
_va1 = _mm_set1_ps(va[13]);
_va2 = _mm_set1_ps(va[14]);
_va3 = _mm_set1_ps(va[15]);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb, _va0));// sum0 = (a30-a33) * k03
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_vb, _va1));// sum1 = (a30-a33) * k13
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_vb, _va2));// sum2 = (a30-a33) * k23
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_vb, _va3));// sum3 = (a30-a33) * k33
va += 16;
vb += 16;
}
for (; k<L; k++)
{
// k0
__m128 _vb = _mm_loadu_ps(vb);
__m128 _va0 = _mm_set1_ps(va[0]);
__m128 _va1 = _mm_set1_ps(va[1]);
__m128 _va2 = _mm_set1_ps(va[2]);
__m128 _va3 = _mm_set1_ps(va[3]);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb, _va0));// sum0 = (a00-a03) * k00
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_vb, _va1));// sum1 = (a00-a03) * k10
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_vb, _va2));// sum2 = (a00-a03) * k20
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_vb, _va3));// sum3 = (a00-a03) * k30
va += 4;
vb += 4;
}
_mm_storeu_ps(output0, _sum0);
_mm_storeu_ps(output1, _sum1);
_mm_storeu_ps(output2, _sum2);
_mm_storeu_ps(output3, _sum3);
#else
float sum0[4] = {0};
float sum1[4] = {0};
float sum2[4] = {0};
float sum3[4] = {0};
int k=0;
for (; k+7<L; k=k+8)
{
for (int n=0; n<4; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
va += 4;
sum0[n] += va[0] * vb[n+4];
sum1[n] += va[1] * vb[n+4];
sum2[n] += va[2] * vb[n+4];
sum3[n] += va[3] * vb[n+4];
va += 4;
sum0[n] += va[0] * vb[n+8];
sum1[n] += va[1] * vb[n+8];
sum2[n] += va[2] * vb[n+8];
sum3[n] += va[3] * vb[n+8];
va += 4;
sum0[n] += va[0] * vb[n+12];
sum1[n] += va[1] * vb[n+12];
sum2[n] += va[2] * vb[n+12];
sum3[n] += va[3] * vb[n+12];
va += 4;
sum0[n] += va[0] * vb[n+16];
sum1[n] += va[1] * vb[n+16];
sum2[n] += va[2] * vb[n+16];
sum3[n] += va[3] * vb[n+16];
va += 4;
sum0[n] += va[0] * vb[n+20];
sum1[n] += va[1] * vb[n+20];
sum2[n] += va[2] * vb[n+20];
sum3[n] += va[3] * vb[n+20];
va += 4;
sum0[n] += va[0] * vb[n+24];
sum1[n] += va[1] * vb[n+24];
sum2[n] += va[2] * vb[n+24];
sum3[n] += va[3] * vb[n+24];
va += 4;
sum0[n] += va[0] * vb[n+28];
sum1[n] += va[1] * vb[n+28];
sum2[n] += va[2] * vb[n+28];
sum3[n] += va[3] * vb[n+28];
va -= 28;
}
va += 32;
vb += 32;
}
for (; k<L; k++)
{
for (int n=0; n<4; n++)
{
sum0[n] += va[0] * vb[n];
sum1[n] += va[1] * vb[n];
sum2[n] += va[2] * vb[n];
sum3[n] += va[3] * vb[n];
}
va += 4;
vb += 4;
}
for (int n=0; n<4; n++)
{
output0[n] = sum0[n] + biasptr[0];
output1[n] = sum1[n] + biasptr[1];
output2[n] = sum2[n] + biasptr[2];
output3[n] = sum3[n] + biasptr[3];
}
#endif // __SSE__
output0 += 4;
output1 += 4;
output2 += 4;
output3 += 4;
}
for (; j<N; j++)
{
const float* vb = bottom_tm.channel(j/4 + j%4);
const float* va = kernel_tm.channel(i/4);
#if __SSE__
__m128 _sum0_3 = _mm_loadu_ps(biasptr);
__m128 _sum0 = _mm_set1_ps(0.0);
__m128 _sum1 = _mm_set1_ps(0.0);
__m128 _sum2 = _mm_set1_ps(0.0);
__m128 _sum3 = _mm_set1_ps(0.0);
int k=0;
for (; k+3<L; k=k+4)
{
__m128 _vb0 = _mm_set1_ps(vb[0]);
__m128 _vb1 = _mm_set1_ps(vb[1]);
__m128 _vb2 = _mm_set1_ps(vb[2]);
__m128 _vb3 = _mm_set1_ps(vb[3]);
__m128 _va0 = _mm_loadu_ps(va);
__m128 _va1 = _mm_loadu_ps(va+4);
__m128 _va2 = _mm_loadu_ps(va+8);
__m128 _va3 = _mm_loadu_ps(va+12);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_va0, _vb0));// sum0 += (k00-k30) * a00
_sum1 = _mm_add_ps(_sum1, _mm_mul_ps(_va1, _vb1));// sum1 += (k01-k31) * a10
_sum2 = _mm_add_ps(_sum2, _mm_mul_ps(_va2, _vb2));// sum2 += (k02-k32) * a20
_sum3 = _mm_add_ps(_sum3, _mm_mul_ps(_va3, _vb3));// sum3 += (k03-k33) * a30
va += 16;
vb += 4;
}
_sum0 = _mm_add_ps(_sum0, _sum1);
_sum2 = _mm_add_ps(_sum2, _sum3);
_sum0_3 = _mm_add_ps(_sum0_3, _sum0);
_sum0_3 = _mm_add_ps(_sum0_3, _sum2);
for (; k<L; k++)
{
__m128 _vb0 = _mm_set1_ps(vb[0]);
__m128 _va = _mm_loadu_ps(va);
_sum0_3 = _mm_add_ps(_sum0_3, _mm_mul_ps(_va, _vb0));// sum0 += (k00-k30) * a00
va += 4;
vb += 1;
}
output0[0] = _sum0_3[0];
output1[0] = _sum0_3[1];
output2[0] = _sum0_3[2];
output3[0] = _sum0_3[3];
#else
float sum0 = biasptr[0];
float sum1 = biasptr[1];
float sum2 = biasptr[2];
float sum3 = biasptr[3];
for (int k=0; k<L; k++)
{
sum0 += va[0] * vb[0];
sum1 += va[1] * vb[0];
sum2 += va[2] * vb[0];
sum3 += va[3] * vb[0];
va += 4;
vb += 1;
}
output0[0] = sum0;
output1[0] = sum1;
output2[0] = sum2;
output3[0] = sum3;
#endif // __SSE__
output0++;
output1++;
output2++;
output3++;
}
}
#pragma omp parallel for num_threads(opt.num_threads)
for (int i=remain_outch_start; i<outch; i++)
{
float* output = top_blob.channel(i);
const float bias0 = bias ? bias[i] : 0.f;
int j=0;
for (; j+3<N; j=j+4)
{
const float* vb = bottom_tm.channel(j/4);
const float* va = kernel_tm.channel(i/4 + i%4);
#if __SSE__
__m128 _sum0 = _mm_set1_ps(bias0);
int k=0;
for (; k+3<L; k=k+4)
{
// k0
__m128 _va0 = _mm_set1_ps(va[0]);
__m128 _va1 = _mm_set1_ps(va[1]);
__m128 _va2 = _mm_set1_ps(va[2]);
__m128 _va3 = _mm_set1_ps(va[3]);
__m128 _vb0 = _mm_loadu_ps(vb);
__m128 _vb1 = _mm_loadu_ps(vb+4);
__m128 _vb2 = _mm_loadu_ps(vb+8);
__m128 _vb3 = _mm_loadu_ps(vb+12);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb0, _va0));// sum0 = (a00-a03) * k00
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb1, _va1));// sum0 += (a10-a13) * k01
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb2, _va2));// sum0 += (a20-a23) * k02
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb3, _va3));// sum0 += (a30-a33) * k03
va += 4;
vb += 16;
}
for (; k<L; k++)
{
// k0
__m128 _va0 = _mm_set1_ps(va[0]);
__m128 _vb0 = _mm_loadu_ps(vb);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_vb0, _va0)); // sum0 = (a00-a03) * k00
va += 1;
vb += 4;
}
_mm_storeu_ps(output, _sum0);
#else
float sum[4] = {0};
int k=0;
for (; k+3<L; k=k+4)
{
for (int n=0; n<4; n++)
{
sum[n] += va[0] * vb[n];
sum[n] += va[1] * vb[n+4];
sum[n] += va[2] * vb[n+8];
sum[n] += va[3] * vb[n+12];
sum[n] += va[4] * vb[n+16];
sum[n] += va[5] * vb[n+20];
sum[n] += va[6] * vb[n+24];
sum[n] += va[7] * vb[n+28];
}
va += 8;
vb += 32;
}
for (; k<L; k++)
{
for (int n=0; n<4; n++)
{
sum[n] += va[0] * vb[n];
}
va += 1;
vb += 4;
}
for (int n=0; n<4; n++)
{
output[n] = sum[n] + bias0;
}
#endif // __SSE__
output += 4;
}
for (; j<N; j++)
{
const float* vb = bottom_tm.channel(j/4 + j%4);
const float* va = kernel_tm.channel(i/4 + i%4);
int k=0;
#if __SSE__
__m128 _sum0 = _mm_set1_ps(0.f);
for (; k+3<L; k+=4)
{
__m128 _p0 = _mm_loadu_ps(vb);
__m128 _k0 = _mm_loadu_ps(va);
_sum0 = _mm_add_ps(_sum0, _mm_mul_ps(_p0, _k0));
va += 4;
vb += 4;
}
float sum0 = bias0 + _sum0[0] + _sum0[1] + _sum0[2] + _sum0[3];
#else
float sum0 = bias0;
#endif // __SSE__
for (; k<L; k++)
{
sum0 += va[0] * vb[0];
va += 1;
vb += 1;
}
output[0] = sum0;
output++;
}
}
}
}
#endif
|
corleonechensiyu/ncnn-8-12
|
src/layer/ctcgreedydecoder.h
|
#ifndef LAYER_CTCDECODER_H
#define LAYER_CTCDECODER_H
#include "layer.h"
namespace ncnn{
class CTCGreedyDecoder : public Layer
{
public:
CTCGreedyDecoder();
virtual int load_param(const ParamDict& pd);
//virtual int forward_inplace(Mat& bottom_top_blob,const Option& opt) const;
virtual int forward(const Mat& bottom_blob,Mat& top_blob,const Option& opt) const;
public:
int blank;
};
}
#endif
|
SreejitS/dataStructures
|
codes/recursion/6combination.c
|
/*
nCr = n! /[ r!*(n-r)! ]
1. either compute each factorial recursively and then divide
2. use pascals triangle : nCr = n-1Cr-1 + n-1Cr
*/
#include <stdio.h>
int fact(int n)
{
if (n == 0)
return 1;
return fact(n - 1) * n;
}
int nCr(int n, int r)
{
int num, den;
num = fact(n);
den = fact(r) * fact(n - r);
return num / den;
}
int NCR(int n, int r)
{
if (n == r || r == 0)
return 1;
return NCR(n - 1, r - 1) + NCR(n - 1, r);
}
int main()
{
printf("%d \n", nCr(5, 3));
printf("%d \n", NCR(5, 3));
return 0;
}
|
SreejitS/dataStructures
|
codes/recursion/2factorial.c
|
<gh_stars>0
#include <stdio.h>
/*
fact(n) = fact(n-1)*n if n>0 or 1 if n == 0
This is tail recursion
*/
//large number problematic
//takes O(n) time and O(n) space
unsigned long factorial_recursive(unsigned int n)
{
if (n == 0)
{
return 1;
}
return factorial_recursive(n - 1) * (unsigned long)n;
}
int main()
{
printf("%lu ", factorial_recursive(25));
return 0;
}
|
SreejitS/dataStructures
|
codes/recursion/3power.c
|
#include <stdio.h>
/*
m^n = m^(n-1)*m if n>0 or 1 if n==0
This is nested recursion
the number of calling can be halved by checking if the n is odd or even.
if even: power(m*m,n/2)
if odd: m*power(m*m,(n-1)/2)
*/
//here the number of multiplications are n
unsigned long power(unsigned int m, unsigned int n)
{
if (n == 0)
{
return 1;
}
return power(m, n - 1) * (unsigned long)m;
}
//here the number of multiplications are n/2 by checking if n is odd/even
unsigned long power_optimised(unsigned int m, unsigned int n)
{
if (n == 0)
{
return 1;
}
if (n % 2 == 0)
{
return power_optimised(m * m, n / 2);
}
else
{
return (unsigned long)m * power_optimised(m * m, (n - 1) / 2);
}
}
int main()
{
printf("%lu ", power(3, 2));
printf("%lu ", power_optimised(3, 3));
printf("%lu ", power_optimised(3, 2));
return 0;
}
|
SreejitS/dataStructures
|
codes/arrays/array.c
|
<reponame>SreejitS/dataStructures
#include <stdio.h>
#include <stdlib.h>
struct Array
{
int array[10];
int length;
int size;
};
void display(struct Array arr)
{
for (int i = 0; i < arr.length; i++)
{
printf("%d ", arr.array[i]);
}
}
void append(struct Array *arr, int value)
{
if (arr->length < arr->size)
{
arr->array[arr->length++] = value;
}
}
void insert(struct Array *arr, int index, int value)
{
if (index >= 0 && index < arr->length)
{
for (int i = arr->length; i > index; i--)
{
arr->array[i] = arr->array[i - 1];
}
arr->array[index] = value;
arr->length++;
}
}
int delete (struct Array *arr, int index)
{
int value = arr->array[index];
if (index >= 0 && index < arr->length)
{
for (int i = index; i < arr->length - 1; i++)
{
arr->array[i] = arr->array[i + 1];
}
arr->length--;
return value;
}
return 0;
}
int main(void)
{
struct Array arr = {{12, 3, 53, 2, 1, 1}, 6, 10};
append(&arr, 45);
display(arr);
printf("\n");
insert(&arr, 1, 0);
display(arr);
printf("\n");
printf("%d \n", delete (&arr, 0));
display(arr);
return 0;
}
|
SreejitS/dataStructures
|
codes/recursion/1sumN.c
|
<reponame>SreejitS/dataStructures<gh_stars>0
#include <stdio.h>
/*
recursive definition
sum(n) = 0 if n=0 or sum(n-1)+n if n>0
better use n*(n+1)/2 as it takes O(1) constant time.
this is tail recursion
*/
//limited by stack depth, will give seg fault for large numbers
//This takes O(n) time and O(n) space
unsigned long sum_recursive(unsigned int n)
{
if (n == 0)
{
return 0;
}
return sum_recursive(n - 1) + (unsigned long)n;
}
// this gives right answer for even largest 32-bit integer 2^32-1
//type casting needed at the n+1.
unsigned long sum_constant_time(unsigned int n)
{
return (n * ((unsigned long)n + 1)) / 2;
}
int main()
{
printf("%lu ", sum_constant_time(4294967295));
return 0;
}
|
SreejitS/dataStructures
|
codes/recursion/4taylorSeries.c
|
<filename>codes/recursion/4taylorSeries.c
#include <stdio.h>
/*
e^x = 1 + (x/1) + (x^2/2!) + (x^3/3!) + .... n times
e(x,n) = 1, n=0 or r=e(x,n-1); p = p*x; f = f*n
*/
double e(unsigned int x, unsigned int n)
{
static double power = 1;
static double fact = 1;
if (n == 0)
{
return 1;
}
double result = e(x, n - 1);
power = power * x;
fact = fact * n;
return (result + power / fact);
}
double e_horner_formula(unsigned int x, unsigned int n)
{
static double sum = 0;
if (n == 0)
{
return sum;
}
sum = 1 + x * sum / n;
e_horner_formula(x, n - 1);
}
int main()
{
printf("%lf ", e(1, 10));
printf("%lf ", e_horner_formula(1, 10));
return 0;
}
|
mickey9801/MultiButtons
|
src/MultiButtons.h
|
/**
* MultiButtons Library
* Copyright (c) 2019 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Developed for Arduino-ESP32
* Created by <NAME> (developer AT comicparty.com)
*
*/
#ifndef MultiButtons_h
#define MultiButtons_h
#include "Arduino.h"
#define BTN_READ_PHASE_1ST_PASS 0
#define BTN_READ_PHASE_2ND_PASS 1
#define BTN_TRIGGER_EDGE_PRESS 0
#define BTN_TRIGGER_EDGE_RELEASE 1
class MultiButtons {
public:
typedef void (*callback_t)(MultiButtons *mb, int btnIndex);
/*
* Constructor
* Params:
* pin GPIO for button array
* buttonCount Number of buttons connected
* arrVoltageRanges Upper bound and Lower bound of voltage for each button
* callback Callback function of actions according to pressed button
* adcMax The maxmium value of ADC
* triggerEdge Which edge trigger button press event. On press (0) or on release (1)
*/
MultiButtons(int pin, int buttonCount, int arrVoltageRanges[][2], callback_t callback,
int adcMax=4095, int triggerEdge=BTN_TRIGGER_EDGE_PRESS);
~MultiButtons();
/*
* Prepare for button press detection
* Clear first reading and attach button handler with detect edge
*/
void begin();
/*
* Check analog pin reading for the buttons every 50 milliseconds
* Should be put in loop()
*/
void loop();
/*
* Print analog button pin reading via serial debug console
* when the reading greater than 100.
*/
static int printReading(int pin);
static bool isPressingAny(int pin);
/*
* Check button is being pressed
*/
bool isPressing();
bool isPressing(int btnIndex);
int getTriggerEdge();
bool setTriggerEdge(int edge);
private:
int _pin;
int _adcMax = 4095;
int **_arrVoltageRanges;
int _buttonCount = 0;
callback_t _callback;
int _triggerEdge = BTN_TRIGGER_EDGE_PRESS;
unsigned long _lastLoop = 0;
int _loopInterval = 50;
int _readPhase = BTN_READ_PHASE_1ST_PASS;
int _prevBtn = -1;
int _lastPressedBtn = -1;
/*
* Debounce button, check valid button press and
* pass the pressed button ID to handler function.
*/
void _getButton();
/*
* Read analog value from button array pin 4 times and
* return the avarage value for determine pressed button
*/
int _readButton();
};
#endif /* MultiButtons_h */
|
KalilDev/sway-borders
|
sway/commands/border_images.c
|
#include <wlr/render/wlr_renderer.h>
#include "cairo.h"
#include "log.h"
#include "sway/commands.h"
#include "sway/config.h"
#include "sway/output.h"
static void apply_border_textures_for_class(struct border_textures *class) {
struct sway_output *output = root->outputs->items[0];
struct wlr_renderer *renderer = wlr_backend_get_renderer(
output->wlr_output->backend);
class->texture = wlr_texture_from_pixels(renderer, WL_SHM_FORMAT_ARGB8888,
cairo_image_surface_get_width(class->image_surface) * 4,
cairo_image_surface_get_width(class->image_surface),
cairo_image_surface_get_height(class->image_surface),
cairo_image_surface_get_data(class->image_surface));
}
static struct cmd_results *handle_command(int argc, char **argv, char *cmd_name,
struct border_textures *class) {
if (!config->active) return cmd_results_new(CMD_DEFER, NULL);
struct cmd_results *error = NULL;
if ((error = checkarg(argc, cmd_name, EXPECTED_EQUAL_TO, 1))) {
return error;
}
class->image_surface = cairo_image_surface_create_from_png(argv[0]);
apply_border_textures_for_class(class);
return cmd_results_new(CMD_SUCCESS, NULL);
}
struct cmd_results *cmd_border_images_focused(int argc, char **argv) {
return handle_command(argc, argv, "border_images.focused",
&config->border_textures.focused);
}
struct cmd_results *cmd_border_images_focused_inactive(int argc, char **argv) {
return handle_command(argc, argv, "border_images.focused_inactive",
&config->border_textures.focused_inactive);
}
struct cmd_results *cmd_border_images_unfocused(int argc, char **argv) {
return handle_command(argc, argv, "border_images.unfocused",
&config->border_textures.unfocused);
}
struct cmd_results *cmd_border_images_urgent(int argc, char **argv) {
return handle_command(argc, argv, "border_images.urgent",
&config->border_textures.urgent);
}
|
justi-a-joao/minimap2
|
hit.c
|
<filename>hit.c
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include "mmpriv.h"
#include "kalloc.h"
#include "khash.h"
static inline void mm_cal_fuzzy_len(mm_reg1_t *r, const mm128_t *a)
{
int i;
r->mlen = r->blen = 0;
if (r->cnt <= 0) return;
r->mlen = r->blen = a[r->as].y>>32&0xff;
for (i = r->as + 1; i < r->as + r->cnt; ++i) {
int span = a[i].y>>32&0xff;
int tl = (int32_t)a[i].x - (int32_t)a[i-1].x;
int ql = (int32_t)a[i].y - (int32_t)a[i-1].y;
r->blen += tl > ql? tl : ql;
r->mlen += tl > span && ql > span? span : tl < ql? tl : ql;
}
}
static inline void mm_reg_set_coor(mm_reg1_t *r, int32_t qlen, const mm128_t *a, int is_qstrand)
{ // NB: r->as and r->cnt MUST BE set correctly for this function to work
int32_t k = r->as, q_span = (int32_t)(a[k].y>>32&0xff);
r->rev = a[k].x>>63;
r->rid = a[k].x<<1>>33;
r->rs = (int32_t)a[k].x + 1 > q_span? (int32_t)a[k].x + 1 - q_span : 0; // NB: target span may be shorter, so this test is necessary
r->re = (int32_t)a[k + r->cnt - 1].x + 1;
if (!r->rev || is_qstrand) {
r->qs = (int32_t)a[k].y + 1 - q_span;
r->qe = (int32_t)a[k + r->cnt - 1].y + 1;
} else {
r->qs = qlen - ((int32_t)a[k + r->cnt - 1].y + 1);
r->qe = qlen - ((int32_t)a[k].y + 1 - q_span);
}
mm_cal_fuzzy_len(r, a);
}
static inline uint64_t hash64(uint64_t key)
{
key = (~key + (key << 21));
key = key ^ key >> 24;
key = ((key + (key << 3)) + (key << 8));
key = key ^ key >> 14;
key = ((key + (key << 2)) + (key << 4));
key = key ^ key >> 28;
key = (key + (key << 31));
return key;
}
mm_reg1_t *mm_gen_regs(void *km, uint32_t hash, int qlen, int n_u, uint64_t *u, mm128_t *a, int is_qstrand) // convert chains to hits
{
mm128_t *z, tmp;
mm_reg1_t *r;
int i, k;
if (n_u == 0) return 0;
// sort by score
z = (mm128_t*)kmalloc(km, n_u * 16);
for (i = k = 0; i < n_u; ++i) {
uint32_t h;
h = (uint32_t)hash64((hash64(a[k].x) + hash64(a[k].y)) ^ hash);
z[i].x = u[i] ^ h; // u[i] -- higher 32 bits: chain score; lower 32 bits: number of seeds in the chain
z[i].y = (uint64_t)k << 32 | (int32_t)u[i];
k += (int32_t)u[i];
}
radix_sort_128x(z, z + n_u);
for (i = 0; i < n_u>>1; ++i) // reverse, s.t. larger score first
tmp = z[i], z[i] = z[n_u-1-i], z[n_u-1-i] = tmp;
// populate r[]
r = (mm_reg1_t*)calloc(n_u, sizeof(mm_reg1_t));
for (i = 0; i < n_u; ++i) {
mm_reg1_t *ri = &r[i];
ri->id = i;
ri->parent = MM_PARENT_UNSET;
ri->score = ri->score0 = z[i].x >> 32;
ri->hash = (uint32_t)z[i].x;
ri->cnt = (int32_t)z[i].y;
ri->as = z[i].y >> 32;
ri->div = -1.0f;
mm_reg_set_coor(ri, qlen, a, is_qstrand);
}
kfree(km, z);
return r;
}
void mm_mark_alt(const mm_idx_t *mi, int n, mm_reg1_t *r)
{
int i;
if (mi->n_alt == 0) return;
for (i = 0; i < n; ++i)
if (mi->seq[r[i].rid].is_alt)
r[i].is_alt = 1;
}
static inline int mm_alt_score(int score, float alt_diff_frac)
{
if (score < 0) return score;
score = (int)(score * (1.0 - alt_diff_frac) + .499);
return score > 0? score : 1;
}
void mm_split_reg(mm_reg1_t *r, mm_reg1_t *r2, int n, int qlen, mm128_t *a, int is_qstrand)
{
if (n <= 0 || n >= r->cnt) return;
*r2 = *r;
r2->id = -1;
r2->sam_pri = 0;
r2->p = 0;
r2->split_inv = 0;
r2->cnt = r->cnt - n;
r2->score = (int32_t)(r->score * ((float)r2->cnt / r->cnt) + .499);
r2->as = r->as + n;
if (r->parent == r->id) r2->parent = MM_PARENT_TMP_PRI;
mm_reg_set_coor(r2, qlen, a, is_qstrand);
r->cnt -= r2->cnt;
r->score -= r2->score;
mm_reg_set_coor(r, qlen, a, is_qstrand);
r->split |= 1, r2->split |= 2;
}
void mm_set_parent(void *km, float mask_level, int mask_len, int n, mm_reg1_t *r, int sub_diff, int hard_mask_level, float alt_diff_frac) // and compute mm_reg1_t::subsc
{
int i, j, k, *w;
uint64_t *cov;
if (n <= 0) return;
for (i = 0; i < n; ++i) r[i].id = i;
cov = (uint64_t*)kmalloc(km, n * sizeof(uint64_t));
w = (int*)kmalloc(km, n * sizeof(int));
w[0] = 0, r[0].parent = 0;
for (i = 1, k = 1; i < n; ++i) {
mm_reg1_t *ri = &r[i];
int si = ri->qs, ei = ri->qe, n_cov = 0, uncov_len = 0;
if (hard_mask_level) goto skip_uncov;
for (j = 0; j < k; ++j) { // traverse existing primary hits to find overlapping hits
mm_reg1_t *rp = &r[w[j]];
int sj = rp->qs, ej = rp->qe;
if (ej <= si || sj >= ei) continue;
if (sj < si) sj = si;
if (ej > ei) ej = ei;
cov[n_cov++] = (uint64_t)sj<<32 | ej;
}
if (n_cov == 0) {
goto set_parent_test; // no overlapping primary hits; then i is a new primary hit
} else if (n_cov > 0) { // there are overlapping primary hits; find the length not covered by existing primary hits
int j, x = si;
radix_sort_64(cov, cov + n_cov);
for (j = 0; j < n_cov; ++j) {
if ((int)(cov[j]>>32) > x) uncov_len += (cov[j]>>32) - x;
x = (int32_t)cov[j] > x? (int32_t)cov[j] : x;
}
if (ei > x) uncov_len += ei - x;
}
skip_uncov:
for (j = 0; j < k; ++j) { // traverse existing primary hits again
mm_reg1_t *rp = &r[w[j]];
int sj = rp->qs, ej = rp->qe, min, max, ol;
if (ej <= si || sj >= ei) continue; // no overlap
min = ej - sj < ei - si? ej - sj : ei - si;
max = ej - sj > ei - si? ej - sj : ei - si;
ol = si < sj? (ei < sj? 0 : ei < ej? ei - sj : ej - sj) : (ej < si? 0 : ej < ei? ej - si : ei - si); // overlap length; TODO: this can be simplified
if ((float)ol / min - (float)uncov_len / max > mask_level && uncov_len <= mask_len) { // then this is a secondary hit
int cnt_sub = 0, sci = ri->score;
ri->parent = rp->parent;
if (!rp->is_alt && ri->is_alt) sci = mm_alt_score(sci, alt_diff_frac);
rp->subsc = rp->subsc > sci? rp->subsc : sci;
if (ri->cnt >= rp->cnt) cnt_sub = 1;
if (rp->p && ri->p && (rp->rid != ri->rid || rp->rs != ri->rs || rp->re != ri->re || ol != min)) { // the last condition excludes identical hits after DP
sci = ri->p->dp_max;
if (!rp->is_alt && ri->is_alt) sci = mm_alt_score(sci, alt_diff_frac);
rp->p->dp_max2 = rp->p->dp_max2 > sci? rp->p->dp_max2 : sci;
if (rp->p->dp_max - ri->p->dp_max <= sub_diff) cnt_sub = 1;
}
if (cnt_sub) ++rp->n_sub;
break;
}
}
set_parent_test:
if (j == k) w[k++] = i, ri->parent = i, ri->n_sub = 0;
}
kfree(km, cov);
kfree(km, w);
}
void mm_hit_sort(void *km, int *n_regs, mm_reg1_t *r, float alt_diff_frac)
{
int32_t i, n_aux, n = *n_regs, has_cigar = 0, no_cigar = 0;
mm128_t *aux;
mm_reg1_t *t;
if (n <= 1) return;
aux = (mm128_t*)kmalloc(km, n * 16);
t = (mm_reg1_t*)kmalloc(km, n * sizeof(mm_reg1_t));
for (i = n_aux = 0; i < n; ++i) {
if (r[i].inv || r[i].cnt > 0) { // squeeze out elements with cnt==0 (soft deleted)
int score;
if (r[i].p) score = r[i].p->dp_max, has_cigar = 1;
else score = r[i].score, no_cigar = 1;
if (r[i].is_alt) score = mm_alt_score(score, alt_diff_frac);
aux[n_aux].x = (uint64_t)score << 32 | r[i].hash;
aux[n_aux++].y = i;
} else if (r[i].p) {
free(r[i].p);
r[i].p = 0;
}
}
assert(has_cigar + no_cigar == 1);
radix_sort_128x(aux, aux + n_aux);
for (i = n_aux - 1; i >= 0; --i)
t[n_aux - 1 - i] = r[aux[i].y];
memcpy(r, t, sizeof(mm_reg1_t) * n_aux);
*n_regs = n_aux;
kfree(km, aux);
kfree(km, t);
}
int mm_set_sam_pri(int n, mm_reg1_t *r)
{
int i, n_pri = 0;
for (i = 0; i < n; ++i)
if (r[i].id == r[i].parent) {
++n_pri;
r[i].sam_pri = (n_pri == 1);
} else r[i].sam_pri = 0;
return n_pri;
}
void mm_sync_regs(void *km, int n_regs, mm_reg1_t *regs) // keep mm_reg1_t::{id,parent} in sync; also reset id
{
int *tmp, i, max_id = -1, n_tmp;
if (n_regs <= 0) return;
for (i = 0; i < n_regs; ++i) // NB: doesn't work if mm_reg1_t::id is negative
max_id = max_id > regs[i].id? max_id : regs[i].id;
n_tmp = max_id + 1;
tmp = (int*)kmalloc(km, n_tmp * sizeof(int));
for (i = 0; i < n_tmp; ++i) tmp[i] = -1;
for (i = 0; i < n_regs; ++i)
if (regs[i].id >= 0) tmp[regs[i].id] = i;
for (i = 0; i < n_regs; ++i) {
mm_reg1_t *r = ®s[i];
r->id = i;
if (r->parent == MM_PARENT_TMP_PRI)
r->parent = i;
else if (r->parent >= 0 && tmp[r->parent] >= 0)
r->parent = tmp[r->parent];
else r->parent = MM_PARENT_UNSET;
}
kfree(km, tmp);
mm_set_sam_pri(n_regs, regs);
}
void mm_select_sub(void *km, float pri_ratio, int min_diff, int best_n, int check_strand, int min_strand_sc, int *n_, mm_reg1_t *r)
{
if (pri_ratio > 0.0f && *n_ > 0) {
int i, k, n = *n_, n_2nd = 0;
for (i = k = 0; i < n; ++i) {
int p = r[i].parent;
if (p == i || r[i].inv) { // primary or inversion
r[k++] = r[i];
} else if ((r[i].score >= r[p].score * pri_ratio || r[i].score + min_diff >= r[p].score) && n_2nd < best_n) {
if (!(r[i].qs == r[p].qs && r[i].qe == r[p].qe && r[i].rid == r[p].rid && r[i].rs == r[p].rs && r[i].re == r[p].re)) // not identical hits
r[k++] = r[i], ++n_2nd;
else if (r[i].p) free(r[i].p);
} else if (check_strand && n_2nd < best_n && r[i].score > min_strand_sc && r[i].rev != r[p].rev) {
r[i].strand_retained = 1;
r[k++] = r[i], ++n_2nd;
} else if (r[i].p) free(r[i].p);
}
if (k != n) mm_sync_regs(km, k, r); // removing hits requires sync()
*n_ = k;
}
}
int mm_filter_strand_retained(int n_regs, mm_reg1_t *r)
{
int i, k;
for (i = k = 0; i < n_regs; ++i) {
int p = r[i].parent;
if (!r[i].strand_retained || r[i].div < r[p].div * 5.0f) {
if (k < i) r[k++] = r[i];
else ++k;
}
}
return k;
}
void mm_filter_regs(const mm_mapopt_t *opt, int qlen, int *n_regs, mm_reg1_t *regs)
{ // NB: after this call, mm_reg1_t::parent can be -1 if its parent filtered out
int i, k;
for (i = k = 0; i < *n_regs; ++i) {
mm_reg1_t *r = ®s[i];
int flt = 0;
if (!r->inv && !r->seg_split && r->cnt < opt->min_cnt) flt = 1;
if (r->p) { // these filters are only applied when base-alignment is available
if (r->mlen < opt->min_chain_score) flt = 1;
else if (r->p->dp_max < opt->min_dp_max) flt = 1;
else if (r->qs > qlen * opt->max_clip_ratio && qlen - r->qe > qlen * opt->max_clip_ratio) flt = 1;
if (flt) free(r->p);
}
if (!flt) {
if (k < i) regs[k++] = regs[i];
else ++k;
}
}
*n_regs = k;
}
int mm_squeeze_a(void *km, int n_regs, mm_reg1_t *regs, mm128_t *a)
{ // squeeze out regions in a[] that are not referenced by regs[]
int i, as = 0;
uint64_t *aux;
aux = (uint64_t*)kmalloc(km, n_regs * 8);
for (i = 0; i < n_regs; ++i)
aux[i] = (uint64_t)regs[i].as << 32 | i;
radix_sort_64(aux, aux + n_regs);
for (i = 0; i < n_regs; ++i) {
mm_reg1_t *r = ®s[(int32_t)aux[i]];
if (r->as != as) {
memmove(&a[as], &a[r->as], r->cnt * 16);
r->as = as;
}
as += r->cnt;
}
kfree(km, aux);
return as;
}
mm_seg_t *mm_seg_gen(void *km, uint32_t hash, int n_segs, const int *qlens, int n_regs0, const mm_reg1_t *regs0, int *n_regs, mm_reg1_t **regs, const mm128_t *a)
{
int s, i, j, acc_qlen[MM_MAX_SEG+1], qlen_sum = 0;
mm_seg_t *seg;
assert(n_segs <= MM_MAX_SEG);
for (s = 1, acc_qlen[0] = 0; s < n_segs; ++s)
acc_qlen[s] = acc_qlen[s-1] + qlens[s-1];
qlen_sum = acc_qlen[n_segs - 1] + qlens[n_segs - 1];
seg = (mm_seg_t*)kcalloc(km, n_segs, sizeof(mm_seg_t));
for (s = 0; s < n_segs; ++s) {
seg[s].u = (uint64_t*)kmalloc(km, n_regs0 * 8);
for (i = 0; i < n_regs0; ++i)
seg[s].u[i] = (uint64_t)regs0[i].score << 32;
}
for (i = 0; i < n_regs0; ++i) {
const mm_reg1_t *r = ®s0[i];
for (j = 0; j < r->cnt; ++j) {
int sid = (a[r->as + j].y&MM_SEED_SEG_MASK)>>MM_SEED_SEG_SHIFT;
++seg[sid].u[i];
++seg[sid].n_a;
}
}
for (s = 0; s < n_segs; ++s) {
mm_seg_t *sr = &seg[s];
for (i = 0, sr->n_u = 0; i < n_regs0; ++i) // squeeze out zero-length per-segment chains
if ((int32_t)sr->u[i] != 0)
sr->u[sr->n_u++] = sr->u[i];
sr->a = (mm128_t*)kmalloc(km, sr->n_a * sizeof(mm128_t));
sr->n_a = 0;
}
for (i = 0; i < n_regs0; ++i) {
const mm_reg1_t *r = ®s0[i];
for (j = 0; j < r->cnt; ++j) {
int sid = (a[r->as + j].y&MM_SEED_SEG_MASK)>>MM_SEED_SEG_SHIFT;
mm128_t a1 = a[r->as + j];
// on reverse strand, the segment position is:
// x_for_cat = qlen_sum - 1 - (int32_t)a1.y - 1 + q_span
// (int32_t)new_a1.y = qlens[sid] - (x_for_cat - acc_qlen[sid] + 1 - q_span) - 1 = (int32_t)a1.y - (qlen_sum - (qlens[sid] + acc_qlen[sid]))
a1.y -= a1.x>>63? qlen_sum - (qlens[sid] + acc_qlen[sid]) : acc_qlen[sid];
seg[sid].a[seg[sid].n_a++] = a1;
}
}
for (s = 0; s < n_segs; ++s) {
regs[s] = mm_gen_regs(km, hash, qlens[s], seg[s].n_u, seg[s].u, seg[s].a, 0);
n_regs[s] = seg[s].n_u;
for (i = 0; i < n_regs[s]; ++i) {
regs[s][i].seg_split = 1;
regs[s][i].seg_id = s;
}
}
return seg;
}
void mm_seg_free(void *km, int n_segs, mm_seg_t *segs)
{
int i;
for (i = 0; i < n_segs; ++i) kfree(km, segs[i].u);
for (i = 0; i < n_segs; ++i) kfree(km, segs[i].a);
kfree(km, segs);
}
static void mm_set_inv_mapq(void *km, int n_regs, mm_reg1_t *regs)
{
int i, n_aux;
mm128_t *aux;
if (n_regs < 3) return;
for (i = 0; i < n_regs; ++i)
if (regs[i].inv) break;
if (i == n_regs) return; // no inversion hits
aux = (mm128_t*)kmalloc(km, n_regs * 16);
for (i = n_aux = 0; i < n_regs; ++i)
if (regs[i].parent == i || regs[i].parent < 0)
aux[n_aux].y = i, aux[n_aux++].x = (uint64_t)regs[i].rid << 32 | regs[i].rs;
radix_sort_128x(aux, aux + n_aux);
for (i = 1; i < n_aux - 1; ++i) {
mm_reg1_t *inv = ®s[aux[i].y];
if (inv->inv) {
mm_reg1_t *l = ®s[aux[i-1].y];
mm_reg1_t *r = ®s[aux[i+1].y];
inv->mapq = l->mapq < r->mapq? l->mapq : r->mapq;
}
}
kfree(km, aux);
}
void mm_set_mapq(void *km, int n_regs, mm_reg1_t *regs, int min_chain_sc, int match_sc, int rep_len, int is_sr)
{
static const float q_coef = 40.0f;
int64_t sum_sc = 0;
float uniq_ratio;
int i;
if (n_regs == 0) return;
for (i = 0; i < n_regs; ++i)
if (regs[i].parent == regs[i].id)
sum_sc += regs[i].score;
uniq_ratio = (float)sum_sc / (sum_sc + rep_len);
for (i = 0; i < n_regs; ++i) {
mm_reg1_t *r = ®s[i];
if (r->inv) {
r->mapq = 0;
} else if (r->parent == r->id) {
int mapq, subsc;
float pen_s1 = (r->score > 100? 1.0f : 0.01f * r->score) * uniq_ratio;
float pen_cm = r->cnt > 10? 1.0f : 0.1f * r->cnt;
pen_cm = pen_s1 < pen_cm? pen_s1 : pen_cm;
subsc = r->subsc > min_chain_sc? r->subsc : min_chain_sc;
if (r->p && r->p->dp_max2 > 0 && r->p->dp_max > 0) {
float identity = (float)r->mlen / r->blen;
float x = (float)r->p->dp_max2 * subsc / r->p->dp_max / r->score0;
mapq = (int)(identity * pen_cm * q_coef * (1.0f - x * x) * logf((float)r->p->dp_max / match_sc));
if (!is_sr) {
int mapq_alt = (int)(6.02f * identity * identity * (r->p->dp_max - r->p->dp_max2) / match_sc + .499f); // BWA-MEM like mapQ, mostly for short reads
mapq = mapq < mapq_alt? mapq : mapq_alt; // in case the long-read heuristic fails
}
} else {
float x = (float)subsc / r->score0;
if (r->p) {
float identity = (float)r->mlen / r->blen;
mapq = (int)(identity * pen_cm * q_coef * (1.0f - x) * logf((float)r->p->dp_max / match_sc));
} else {
mapq = (int)(pen_cm * q_coef * (1.0f - x) * logf(r->score));
}
}
mapq -= (int)(4.343f * logf(r->n_sub + 1) + .499f);
mapq = mapq > 0? mapq : 0;
r->mapq = mapq < 60? mapq : 60;
if (r->p && r->p->dp_max > r->p->dp_max2 && r->mapq == 0) r->mapq = 1;
} else r->mapq = 0;
}
mm_set_inv_mapq(km, n_regs, regs);
}
|
KhunLam/OC-weibo
|
OC_weibo/OC_weibo/Classes/Module/Main/View/LKVistorView.h
|
<gh_stars>0
//
// LKVistorView.h
// OC_weibo
//
// Created by lamkhun on 15/10/27.
// Copyright © 2015年 lamKhun. All rights reserved.
//
#import <UIKit/UIKit.h>
//设置代理
@protocol LKVistorViewDalegate <NSObject>
@optional
-(void)vistorViewRegistClick;
-(void)vistorViewLoginClick;
@end
@interface LKVistorView : UIView
///设置代理属性
@property (nonatomic,weak) id<LKVistorViewDalegate>vistorViewDelegate;
///设置访客视图内容
-(void)setupVistorViewWithImageName:(NSString*)imageName andMessage:(NSString*)message;
/// 转轮动画
-(void)startRotationAnimation;
/// 暂停旋转
-(void)pauseAnimation;
/// 恢复旋转
-(void)resumeAnimation;
@end
|
KhunLam/OC-weibo
|
OC_weibo/OC_weibo/Classes/Module/Home/Controller/LKHomeViewController.h
|
//
// LKHomeViewController.h
// OC_weibo
//
// Created by lamkhun on 15/10/27.
// Copyright © 2015年 lamKhun. All rights reserved.
//
#import "LKBaseTableViewController.h"
@interface LKHomeViewController : LKBaseTableViewController
@end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.