在嵌入式开发中,有一些常用的C语言代码片段被认为是宝藏级别的,因为它们在处理底层硬件和优化性能方面非常有用。以下是一些常见的宝藏级别的C语言代码和解释:
1.位操作代码//设置某个位为1 #define SET_BIT(reg, bit) ((reg) |= (1<<(bit))) //清除某个位为0 #define CLEAR_BIT(reg, bit) ((reg) &= ~(1<<(bit))) //切换某个位的状态 #define TOGGLE_BIT(reg, bit) ((reg) ^= (1<<(bit))) //读取某个位的值 #define READ_BIT(reg, bit) (((reg) >> (bit)) & 1)2.延迟函数
void delay_ms(unsigned int ms) { for(unsigned int i=0; i<ms; i++) { for(volatile unsigned int j=0; j<6000; j++) { //空循环一段时间 } } }3.外部中断处理
#include<avr/interrupt.h> void init_external_interrupt() { //配置外部中断触发条件 //... //启用外部中断 sei(); } ISR(INT0_vect) { //外部中断0中断处理程序 } ISR(INT1_vect) { //外部中断1中断处理程序 }4.字节序转换
uint16_t swap_bytes(uint16_t value) { return ((value << 8) | (value >> 8)); }5.CRC校验
uint16_t calc_CRC(const uint8_t *data, size_t len) { uint16_t crc=0; for(size_t i=0; i<len; i++) { crc ^= (uint16_t)data[i] << 8; for(uint8_t bit=0; bit<8; bit++) { if(crc & 0x8000) { crc = (crc<<1) ^ 0x8005; } else crc <<= 1; } } return crc; }6.位字段操作
struct { unsigned int flag1: 1; unsigned int flag2: 1; unsigned int flag3: 1; unsigned int flag4: 1; //... } status; void set_flag(unsigned int *flags, unsigned int pos) { *flags |= (1 << pos); } void clear_flag(unsigned int *flags, unsigned int pos) { *flags &= ~(1 << pos); } int check_flag(unsigned int *flags, unsigned int pos) { return (flags >> pos) & 1; }7.时钟周期计数
#include<stdint.h> uint32_t get_cycle_count() { uint32_t cycle_count; __asm__ volatile("rdcycle %0" : "=r"(cycle_count)); return cycle_count; }
标签:count,int,unsigned,嵌入式,中断,uint16,宝藏,级别,cycle From: https://www.cnblogs.com/lyfily-p-7439305/p/17533274.html