Blinky code for STM32F429I-DISC1

#include "stm32f4xx.h"
			
void myDelay(int value)
{
	while(value>0)
		value--;
}

int main(void)
{
	RCC->AHB1ENR |= RCC_AHB1ENR_GPIOCEN;

	//pc2 output mode
	GPIOC->MODER |= GPIO_MODER_MODER2_0;

	while(1)
	{
		GPIOC->ODR |=  GPIO_ODR_ODR_2;

		myDelay(500000);

		GPIOC->ODR &= ~GPIO_ODR_ODR_2;

		myDelay(500000);
	}
}

Conditional Check of #define values in C macros

This code shows condition checking of #define values and also token combining using ‘##’

#include <stdio.h>
#define REQMOTHERBOARD 11
#define BOARD_USERBOARD1 11
#define BOARD_USERBOARD2 12
#define MB(board) (REQMOTHERBOARD==BOARD_##board)

int main(void) {

   printf("Testing defines\n");

   #if MB(USERBOARD1)
      printf("Board available!");
   #else
      printf("Board not available");
   #endif

   return 0;
}

LED blink using STM32F769I discovery board

#include "stm32f7xx.h"

void myDelay(int value)
{
	volatile int i,j;
	
	for(i =0;i< value;i++){
		j++;
	}
}

int main(void)
{
	
	//Enable the GPIO clock using AHB and RCC (PIN : PJ 3)
	RCC->AHB1ENR |= RCC_AHB1ENR_GPIOJEN;
	
	//Set mode register to OUTPUT mode for pin D7
	GPIOJ->MODER |= GPIO_MODER_MODER3_0;
	
	//SET OTYPER TO PUSH-PULL
//	GPIOJ->OTYPER &= ~(GPIO_OTYPER_OT_3);
	
	//SET OSPEEDR
	//GPIOJ->OSPEEDR |= GPIO_OSPEEDER_OSPEEDR3_0;
	
	//PUPDR
//	GPIOJ->PUPDR &= ~(GPIO_PUPDR_PUPDR3); //~(11) = NO pullup/pulldown
	
	while(1)
	{
			//turn on led 
		GPIOJ->ODR |= GPIO_ODR_ODR_3;

		//WAIT
		myDelay(40000);
		
		GPIOJ->ODR &= ~ GPIO_ODR_ODR_3;
		
		myDelay(40000);
		
	}
}

Fast PWM using atmega2560 .

#define F_CPU 16000000
#include <avr/io.h>
#include <util/delay.h>
#define PIN_OCOB PG5

void initPWM();

int main(void)
{
	
     initPWM();	
		
    while (1) 
    {
	//set the duty cycle
	OCR0B = 128;//50% duty cycle
		
	_delay_ms(10);
    }
}

void initPWM()
{
	
	//        FAST PWM                | CLEAR OCOA ON COMPARE
	TCCR0A |= (1<<WGM01) | (1<<WGM00) | (1<<COM0B1) | (0<<COM0B0);
	
	//CS = NO PRESCALE  
	TCCR0B |= (1<<CS00) ;
	
	//Enable OCOA PWM pin	
	DDRG |= 1<<PIN_OCOB;
	
}

Running a stepper motor with arduino on RAMPS with drv8825 driver

#include <Stepper.h>

int enablePin = 24;
int dirPin = 28;
int stepPin = 26;

void setup() {
  pinMode(enablePin, OUTPUT);
  digitalWrite(enablePin, LOW);
  pinMode(dirPin, OUTPUT);
  pinMode(stepPin, OUTPUT);
}

void step(boolean dir, int steps)
{
  digitalWrite(dirPin, dir);
  delay(50);

  for( int i=0;i<steps;i++)
  {
    digitalWrite(stepPin, HIGH);
    delayMicroseconds(800);
    digitalWrite(stepPin, LOW);
    delayMicroseconds(800);

  }
}

void loop() {
  step(true, 1000);
  delay(50);
  step(false, 1000);
  delay(50);
}

LED blink in STM32F4XX using embedded C.

#include "stm32f4xx.h"
void myDelay(int value)
{
	volatile int i,j;

	for(i =0;i< value;i++){ 
		j++; 	
        } 
} 
int main(void) 
{
 	//Enable the GPIO clock for PORT C using AHB and RCC
 	RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;

	//Set mode register
	GPIOA->MODER |= GPIO_MODER_MODE6_0;

	//SET OTYPER TO PUSH-PULL
	GPIOA->OTYPER &= ~(GPIO_OTYPER_OT_6);

	//SET OSPEEDR
	GPIOA->OSPEEDR |= GPIO_OSPEEDER_OSPEEDR6;

	//PUPDR
	GPIOA->PUPDR &= ~(GPIO_PUPDR_PUPDR6); //~(11) = NO pullup/pulldown

	while(1)
	{
		//turn on led
		GPIOA->ODR |= GPIO_ODR_OD6;

		//WAIT
		myDelay(50000);

		GPIOA->ODR &= ~GPIO_ODR_OD6;

		myDelay(50000);

	}
}

Function Pointers inside Struct in C

#include <stdio.h>

typedef struct{
	int x;
	int y;
	int (*addXPoints) (int x,int y);
	int (*subXPoints) (int x,int y);
}Point;

int addPoints_x(int p1, int p2)
{
		return (p1+p2);
}	

int subtracteXPoints(int p1,int p2)
{
		return (p1-p2);
}

void printPointDetails(Point* temp)
{
		printf("Point [x,y] : %d , %d \n", temp->x, temp->y);
}

int main()
{
	Point p1={30,30};
	
	//another way to initialize
	//p1.x=10; 
	//p1.y=20;
	p1.addXPoints=addPoints_x;
	p1.subXPoints=subtracteXPoints;
	
	printPointDetails(&p1);
	
	printf("Total X Value of p1,p2 : %d\n",p1.addXPoints(p1.x,p1.x));
	printf("Total X Value of p1,p2 : %d\n",p1.subXPoints(p1.x,p1.x));
	

	return 0;
}

Constant pointers and Pointers to constant in C

#include <stdio.h>
int main()
{
	int val = 250;
	int val2 =300;

        // ptrInt is a pointer to integer constant
        const int* ptrInt = &val; //Pointer to Constant

        // ptrInt1 is a constant pointer to integer
        int* const ptrInt1 = &val; //Constant Pointer

        *ptrInt = 500; //pointer to constant wont allow

	ptrInt1 = &val2; //constant pointer wont allow

	return 0;
}

Another version of a simple char driver (Using x86_64 VMware)

Once the module is Live, Use
HEAD -c {no.of.bytes} /dev/mycharDevice for read operation
echo “” > /dev/mycharDevice for write operation

#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/device.h>
#include <linux/kernel.h>
#include <asm/uaccess.h>
#define DEVICE_NAME "mycharDevice"
#define CLASS_NAME "mycharClass"

MODULE_LICENSE("GPL");
MODULE_AUTHOR("PraveenMax");

//Function prototypes for file_op
static int device_open(struct inode *, struct file *);
static int device_close(struct inode *, struct file *);
static ssize_t device_read(struct file *, char *, size_t , loff_t *);
static ssize_t device_write(struct file *, const char *, size_t , loff_t *);

static struct file_operations my_fops={
	.owner = THIS_MODULE,
	.read  = device_read,
	.write = device_write,
	.open  = device_open,
	.release = device_close,
};	

//module variables
static struct class* mycharClass = NULL;
static struct device* mycharDevice = NULL;
static int majorNumber;

static char myBuffer[100]={0};
static short readPos=0;
static int times = 0;

static int device_open(struct inode *inode, struct file *filep)
{
	times++;
	printk(KERN_ALERT "MYCHARDEVICE Device opened %d times \n",times);
	return 0;
}

static int device_close(struct inode *inode, struct file *fileop)
{
	printk(KERN_ALERT "MYCHARDEVICE Device closed\n");
	return 0;
}

//Read len length of data from kernel buffer and stores in userbuffer "buff"
static ssize_t device_read(struct file *fileop, char *buff, size_t len, loff_t *f_pos)
{
	printk(KERN_ALERT "Reading from the device of Data length : %d \n", len);
	
	int bytesRead = 0;
	
	while(len>0)
	{
		//copies the kernel buffer "myBuffer" into userbuffer buff
		put_user(myBuffer[readPos++], buff++);
		len--;
		bytesRead++;
	}
	
	return bytesRead;
}

//Writes the data from userbuffer "buff" of length "len" into kernel buffer "msg"s
static ssize_t device_write(struct file *fileop, const char *buff, size_t len, loff_t *off)
{
	printk(KERN_ALERT "Writing to the device. Data length : %d \n", len);
	
	int bytesWritten = 0; //also acts as buffer index
	memset(myBuffer,0,100); //reset the buffer values
	readPos=0;//reset kernelbuffer pointer
	
	while(len >0)
	{
		myBuffer[bytesWritten] = buff[bytesWritten];
		bytesWritten++;
		len--;
	}

	return bytesWritten;
}
 
static int __init load_module(void)
{
	printk(KERN_ALERT "Mychardriver :: Loading the module \n");

	//Dynamically get the Major Number
	majorNumber = register_chrdev(0, DEVICE_NAME, &my_fops);

	if(majorNumber < 0)
	{
		printk(KERN_ALERT "*** Unable to register MYCHARDRIVER driver : %d\n", majorNumber);
		return majorNumber;
	}
	
	printk(KERN_ALERT "Obtained a Major number !\n");

	//Create a device class for my char driver (appears in /sys/class )
	mycharClass = class_create(THIS_MODULE, CLASS_NAME);
	if(IS_ERR(mycharClass))
	{
		unregister_chrdev(majorNumber, DEVICE_NAME);
		printk(KERN_ALERT "Failed to register the char device \n");
		return PTR_ERR(mycharClass);
	}
	printk(KERN_ALERT "Device class created successfully!\n");

	
	//Create the device node and register it (appears in /dev/DEVICE_NAME )
	mycharDevice = device_create(mycharClass, NULL, MKDEV(majorNumber,0), NULL, DEVICE_NAME);
	if(IS_ERR(mycharDevice))
	{
		class_destroy(mycharClass);
		unregister_chrdev(majorNumber, DEVICE_NAME);
		printk(KERN_ALERT "Failed the create Device node ! \n");
		return PTR_ERR(mycharDevice);
	}
	printk(KERN_ALERT "Device node created successfully ! \n");

	//some initializations
	memset(myBuffer,0,100); //reset the buffer values


 	return 0;
}

static void __exit unload_module(void)
{
	device_destroy(mycharClass, MKDEV(majorNumber, 0) );//destroy the device
	class_unregister(mycharClass);						 //Unregister the device class
	class_destroy(mycharClass); 						 //destroy the class
	unregister_chrdev(majorNumber, DEVICE_NAME);    	 //Unregister the major number
	printk(KERN_ALERT "MYCHARDRIVER Module exited!!\n");
} 

module_init(load_module);
module_exit(unload_module);

A minimal char device driver for arm linux

/*
 * SimpleCharDevice.c
 *
 */

#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/device.h>
#include <asm/uaccess.h>
#include <linux/types.h>
#include <linux/kdev_t.h>
#include <linux/cdev.h>

#define DEVICE_NAME "SimpleCharDevice"
#define CLASS_NAME "SimpleCharDeviceClass"

MODULE_AUTHOR("PraveenMax");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("A simple char device driver for BBB");
MODULE_VERSION("0.1");

static int majorNumber;//For device driver
static int devOpenCount=0;
static struct class* simpleCharClass = NULL;
static struct device* simpleCharDevice = NULL;
static short size_of_message;//used to store the length of previously written string
static char message[256]={0};

//File operations prototypes
static int dev_open(struct inode *, struct file *);
static int dev_release(struct inode *, struct file *);
static ssize_t dev_read(struct file *, char *, size_t, loff_t *);
static ssize_t dev_write(struct file *,const char *, size_t, loff_t *);

//our custom file-operation struct.
static struct file_operations fops={
		.open=dev_open,
		.release=dev_release,
		.read=dev_read,
		.write=dev_write,
		.owner= THIS_MODULE,
};

static int __init loadModule(void){

	printk(KERN_ALERT "Initializing the SimpleChar LKM\n");

	//try to dynamically allocate the Major number
	majorNumber = register_chrdev(0, DEVICE_NAME, &fops);
	if(majorNumber < 0)
	{
		printk(KERN_ALERT "Failed to register a major number\n");
		return majorNumber;
	}

	printk(KERN_ALERT "Registered Successfully with major number : %d\n",majorNumber);

	//Register the device class
	simpleCharClass = class_create(THIS_MODULE, CLASS_NAME);
	if(IS_ERR(simpleCharClass)){
		//if error found, unregister it
		unregister_chrdev(majorNumber, DEVICE_NAME);
		printk(KERN_ALERT "Failed to register the device class\n");
		return PTR_ERR(simpleCharClass);
	}

	printk(KERN_ALERT "Device class registered successfully\n");

	//Register the device driver
	simpleCharDevice = device_create(simpleCharClass, NULL, MKDEV(majorNumber, 0), NULL, DEVICE_NAME);
	if( IS_ERR(simpleCharDevice)){
		class_destroy(simpleCharClass);
		unregister_chrdev(majorNumber, DEVICE_NAME);
		printk(KERN_ALERT "Failed to create the device\n");
		return PTR_ERR(simpleCharDevice);
	}

	printk(KERN_INFO "Device class created correctly\n");
	return 0;
}

static void __exit unloadModule(void){
	//device_destory(simpleCharClass, MKDEV(majorNumber,0));
	class_unregister(simpleCharClass);
	class_destroy(simpleCharClass);
	unregister_chrdev(majorNumber, DEVICE_NAME);
	printk(KERN_ALERT "Goodbye from SimpleCharDevice\n");
}

static int dev_open(struct inode *inodep, struct file *filep){
	devOpenCount++;
	printk(KERN_ALERT "SimpleCharDevice has been opened for %d times\n", devOpenCount);
	return 0;
}

static int dev_release(struct inode *inodep, struct file *filep){
	printk(KERN_ALERT "SimpleCharDevice successfully closed\n");
	return 0;
}

//Send char from KERNEL to USER
static ssize_t dev_read(struct file *filep, char *buffer, size_t len, loff_t *offset){
	int error_count = 0;

	error_count = copy_to_user(buffer, message, size_of_message);

	if(error_count==0){
		printk(KERN_ALERT "SimpleCharDevice :: Sent %d characters to the user\n", size_of_message);
		printk(KERN_ALERT "OUTPUT : %s", message);
		size_of_message = 0;//reset the size_of_message
		return 0;
	}
	else{
		printk(KERN_ALERT "SimpleCharDevice :: Failed to send %d characters to the user\n", error_count);
		return -EFAULT;
	}
}

//Send char from USER to KERNEL
static ssize_t dev_write(struct file *filep, const char *buffer, size_t len, loff_t *offset){
	/*
	sprintf(message, "%s(%zu letters)", buffer, len);
	size_of_message = strlen(message);
	printk(KERN_ALERT "SimpleCharDevice :: Received %d chars from USER \n", len);
	return len;
	*/

	if(copy_from_user(message, buffer, len )!=0)
	{
		printk(KERN_ALERT "SimpleCharDevice :: Write failed!!\n");
	}
	else
	{
		printk(KERN_ALERT "SimpleCharDevice :: Write succeeded\n");
		size_of_message = strlen(message);
	}

	return len;

}

module_init(loadModule);
module_exit(unloadModule);