text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```php
<?php
/*
Plugin Name: 91yun serverspeeder
Plugin URI:
Description: serverspeeder
Version: 0.0.1
Author: 91yun
Author URI:
Text Domain: 91yun.org
*/
//require_once("ss.php");
//echo var_dump($ss);
//exit;
class serverspeeder91yun{
//
function __construct() {
//
register_activation_hook( __FILE__, Array($this,'myplugin_activate'));
//
add_filter('the_content', array($this,'check_page'));
}
function check_page($text){
if(is_page("serverspeeder91yun")){
$release = $_GET["release"];
$releasever = $_GET["releasever"];
$kernel_result = $_GET["kernel_result"];
$bit = $_GET["bit"];
$serverspeederver = $_GET["serverspeederver"];
$binfile = $_GET["binfile"];
$text = file_get_contents("path_to_url");
return $text;
}
else
{
return $text;
}
}
//
function myplugin_activate(){
//pagepage
$soldout = get_page_by_title("");
if (Null == $soldout)
{
$page = array(
'post_title' => '',
'post_content' => '',
'post_name' => 'serverspeeder91yun',
'post_status' => 'publish',
'post_author' => 1,
'post_type' => 'page'
);
wp_insert_post($page);
}
}
}
$serverspeeder = new serverspeeder91yun();
?>
``` | /content/code_sandbox/91yun-serverspeeder.php | php | 2016-03-11T18:31:52 | 2024-08-15T10:09:17 | serverspeeder | 91yun/serverspeeder | 2,919 | 372 |
```shell
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
export PATH
#
#url
APX=path_to_url
#
INSTALLPACK=path_to_url
#
CHECKSYSTEM=path_to_url
#bin
BINURL=path_to_url
#
Get_Dist_Name()
{
if grep -Eqi "CentOS" /etc/issue || grep -Eq "CentOS" /etc/*-release; then
release='CentOS'
PM='yum'
elif grep -Eqi "Debian" /etc/issue || grep -Eq "Debian" /etc/*-release; then
release='Debian'
PM='apt'
elif grep -Eqi "Ubuntu" /etc/issue || grep -Eq "Ubuntu" /etc/*-release; then
release='Ubuntu'
PM='apt'
else
release='unknow'
fi
}
Get_OS_Bit()
{
if [[ `getconf WORD_BIT` = '32' && `getconf LONG_BIT` = '64' ]] ; then
bit='x64'
else
bit='x32'
fi
}
Get_Dist_Name
Get_OS_Bit
kernel=`uname -r`
kernel_result=""
echo -e "\r\n"
echo "===============System Info======================="
echo "$release "
echo "$kernel "
echo "$bit "
echo "================================================="
echo -e "\r\n"
#
wget $CHECKSYSTEM --no-check-certificate -O serverspeederbin.txt || { echo "Error downloading file, please try again later.";exit 1; }
#
grep -q "$release/[^/]*/$kernel/$bit" serverspeederbin.txt
if [ $? -eq 0 ]; then
#
kernel_result=$kernel
else
#
echo ">>>This kernel is not supported. Trying fuzzy matching..."
echo -e "\r\n"
#centosubuntucentos2.6.32-504.el6.x86_64504
if [ "$release" == "CentOS" ]; then
kernel1=`echo $kernel | awk -F '-' '{ print $1 }'`
kernel2=`echo $kernel | awk -F '-' '{ print $2 }' | awk -F '.' '{ print $1 }'`
elif [[ "$release" == "Ubuntu" ]] || [[ "$release" == "Debian" ]]; then
kernel1=`echo $kernel | awk -F '-' '{ print $1 }'`
kernel2=`echo $kernel | awk -F '-' '{ print $2 }'`
else
echo "This script only supports CentOS, Ubuntu and Debian."
exit 1
fi
grep -q "$release/[^/]*/$kernel1\(-\)\{0,1\}$kernel2[^/]*/$bit" serverspeederbin.txt
if [ $? -eq 1 ]; then
echo -e "\r\n"
echo -e "Serverspeeder is not supported on this kernel! View all supported systems and kernels here:\033[41;37m path_to_url \033[0m"
exit 1
else
#
echo "There is no exact match for this kernel, please choose the closest one below:"
echo -e "The current kernel is \033[41;37m $kernel \033[0m"
echo -e "\r\n"
cat serverspeederbin.txt | grep "$release/[^/]*/$kernel1\(-\)\{0,1\}$kernel2[^/]*/$bit" | awk -F '/' '{ print NR""$3 }'
echo -e "\r\n"
echo "Please enter the number of your option"
read cver2
if [ "$cver2" == "" ]; then
echo "You did not choose any kernel options. Installation terminated."
exit 1
fi
echo -e "\r\n"
cver2str="cat serverspeederbin.txt | grep \"$release/[^/]*/$kernel1\(-\)\{0,1\}$kernel2[^/]*/$bit\" | awk -F '/' '{ print NR\"\"\$3 }' | awk -F '' '/"$cver2"/{ print \$2 }' | awk 'NR==1{print \$1}'"
kernel_result=$(eval $cver2str)
fi
fi
if [ "$kernel_result" == "" ]; then
echo "Unable to get kernel information. Installtion terminated."
exit 1
fi
echo "Installing ServerSpeeder, please wait for a moment..."
#
serverspeederver=3.10.61.0
grep -q "$release/[^/]*/$kernel_result/$bit/$serverspeederver" serverspeederbin.txt
if [ $? == 1 ]; then
#
serverspeederverstr="grep \"$release/[^/]*/$kernel_result/$bit/\" serverspeederbin.txt | awk -F '/' 'NR==1{print \$5}'"
serverspeederver=$(eval $serverspeederverstr)
fi
BINFILESTR="cat serverspeederbin.txt | grep '$release/[^/]*/$kernel_result/$bit/$serverspeederver/0' | awk -F '/' '{ print \$1\"/\"\$2\"/\"\$3\"/\"\$4\"/\"\$5\"/\"\$7 }'"
BINFILE=$(eval $BINFILESTR)
if [ "$BINFILE" == "" ]; then
echo "Unable to get BINFILE. Installation terminated."
exit 1
fi
BIN=${BINURL}${BINFILE}
rm -rf serverspeederbin.txt
if [ "$1" == "" ]; then
MACSTR="LANG=C ifconfig eth0 | awk '/HWaddr/{ print \$5 }' "
MAC=$(eval $MACSTR)
if [ "$MAC" == "" ]; then
MACSTR="LANG=C ifconfig eth0 | awk '/ether/{ print \$2 }' "
MAC=$(eval $MACSTR)
fi
if [ "$MAC" == "" ]; then
echo "The name of network interface is not eth0, please retry after changing the name."
exit 1
fi
else
MAC=$1
fi
#
if [ "$MAC" = "" ]; then
echo "Unable to get MAC address. Installation terminated."
exit 1
fi
#
wget -N --no-check-certificate -O 91yunserverspeeder.tar.gz $INSTALLPACK
tar xfvz 91yunserverspeeder.tar.gz || { echo "Unable to download Installation package. Installation terminated.";exit 1; }
#
wget -N --no-check-certificate -O apx.lic "$APX?mac=$MAC" || { echo "Unable to download lic file, please check: $APX?mac=$MAC";exit 1;}
mv apx.lic 91yunserverspeeder/apxfiles/etc/
#
wget -N --no-check-certificate -O serverspeedersn.txt "$APX?mac=$MAC&sno"
SNO=$(cat serverspeedersn.txt)
rm -rf serverspeedersn.txt
sed -i "s/serial=\"sno\"/serial=\"$SNO\"/g" 91yunserverspeeder/apxfiles/etc/config
sed -i "s/apx-20341231/apx/g" 91yunserverspeeder/apxfiles/etc/config
rv=$release"_"$kernel_result
sed -i "s/acce-3.10.61.0-\[Debian_7_3.2.0-4-amd64\]/acce-$serverspeederver-[$rv]/g" 91yunserverspeeder/apxfiles/etc/config
#bin;
wget -N --no-check-certificate -O "acce-"$serverspeederver"-["$release"_"$kernel_result"]" $BIN
mv "acce-"$serverspeederver"-["$release"_"$kernel_result"]" 91yunserverspeeder/apxfiles/bin/
#
cd 91yunserverspeeder
bash install.sh
#
#chattr +i /serverspeeder/etc/apx*
bash /serverspeeder/bin/serverSpeeder.sh status
``` | /content/code_sandbox/serverspeeder.sh | shell | 2016-03-11T18:31:52 | 2024-08-15T10:09:17 | serverspeeder | 91yun/serverspeeder | 2,919 | 1,781 |
```php
<?php
if(!empty($_GET["release"])){
$release = $_GET["release"];
$releasever = $_GET["releasever"];
$kernel_result = $_GET["kernel_result"];
$bit = $_GET["bit"];
$serverspeederver = $_GET["serverspeederver"];
$binfile = $_GET["binfile"];
echo '';
echo '<br>';
echo '<pre class="lang:sh decode:true " style="overflow: auto; overflow-y:hidden">';
echo "wget -N --no-check-certificate path_to_url && bash serverspeeder-v.sh $release $releasever $kernel_result $bit $serverspeederver $binfile";
echo '</pre>';
echo "<BR>";
echo "<a href='?'></a>";
exit(0);
}
$c=file_get_contents("path_to_url");
$caar=preg_split("/\n/",$c);
echo "<BR>";
echo "<a href='path_to_url target=_blank>path_to_url";
echo "<BR>";
echo "<font color=red>Ctrl+F</font>";
echo "<BR>";
echo "<BR>";
for($i=0;$i<count($caar);$i++)
{
$pram=preg_split("/\//",$caar[$i]);
$release = $pram[0];
$releasever = $pram[1];
$kernel_result = $pram[2];
$bit = $pram[3];
$serverspeederver = $pram[4];
$binfile = $pram[6];
echo "<a href='?release=$release&releasever=$releasever&kernel_result=$kernel_result&bit=$bit&serverspeederver=$serverspeederver&binfile=$binfile'>";
echo $caar[$i];
echo "</a>";
echo "<BR>";
}
?>
``` | /content/code_sandbox/serverspeederlist.php | php | 2016-03-11T18:31:52 | 2024-08-15T10:09:17 | serverspeeder | 91yun/serverspeeder | 2,919 | 382 |
```shell
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
export PATH
#
#url
APX=path_to_url
#
INSTALLPACK=path_to_url
#
CHECKSYSTEM=path_to_url
#bin
BINURL=path_to_url
#
Get_Dist_Name()
{
if grep -Eqi "CentOS" /etc/issue || grep -Eq "CentOS" /etc/*-release; then
release='CentOS'
PM='yum'
elif grep -Eqi "Debian" /etc/issue || grep -Eq "Debian" /etc/*-release; then
release='Debian'
PM='apt'
elif grep -Eqi "Ubuntu" /etc/issue || grep -Eq "Ubuntu" /etc/*-release; then
release='Ubuntu'
PM='apt'
else
release='unknow'
fi
}
Get_OS_Bit()
{
if [[ `getconf WORD_BIT` = '32' && `getconf LONG_BIT` = '64' ]] ; then
bit='x64'
else
bit='x32'
fi
}
Get_Dist_Name
Get_OS_Bit
kernel=`uname -r`
kernel_result=""
echo -e "\r\n"
echo "===============System Info======================="
echo "$release "
echo "$kernel "
echo "$bit "
echo "================================================="
echo -e "\r\n"
release=$1
releasever=$2
kernel_result=$3
bit=$4
serverspeederver=$5
BINFILE=$1"/"$2"/"$3"/"$4"/"$5"/"$6
BIN=${BINURL}${BINFILE}
echo "installing ServerSpeeder, please wait for a moment..."
echo -e "\r\n"
MACSTR="LANG=C ifconfig eth0 | awk '/HWaddr/{ print \$5 }' "
MAC=$(eval $MACSTR)
if [ "$MAC" == "" ]; then
MACSTR="LANG=C ifconfig eth0 | awk '/ether/{ print \$2 }' "
MAC=$(eval $MACSTR)
fi
if [ "$MAC" == "" ]; then
echo "The name of network interface is not eth0, please retry after changing the name."
exit 1
fi
#
if [ "$MAC" = "" ]; then
echo "Unable to get MAC address. Installation terminated."
exit 1
fi
#
wget -N --no-check-certificate -O 91yunserverspeeder.tar.gz $INSTALLPACK > /dev/null 2>&1
tar xfvz 91yunserverspeeder.tar.gz > /dev/null 2>&1 || { echo "Unable to download Installation package. Installation terminated.";exit 1; }
#
wget -N --no-check-certificate -O apx.lic "$APX?mac=$MAC" > /dev/null 2>&1 || { echo "Unable to download lic file, please check: $APX?mac=$MAC";exit 1;}
mv apx.lic 91yunserverspeeder/apxfiles/etc/
#
wget -N --no-check-certificate -O serverspeedersn.txt "$APX?mac=$MAC&sno" > /dev/null 2>&1
SNO=$(cat serverspeedersn.txt)
rm -rf serverspeedersn.txt
sed -i "s/serial=\"sno\"/serial=\"$SNO\"/g" 91yunserverspeeder/apxfiles/etc/config
sed -i "s/apx-20341231/apx/g" 91yunserverspeeder/apxfiles/etc/config
rv=$release"_"$kernel_result
sed -i "s/acce-3.10.61.0-\[Debian_7_3.2.0-4-amd64\]/acce-$serverspeederver-[$rv]/g" 91yunserverspeeder/apxfiles/etc/config
#bin
wget -N --no-check-certificate -O "acce-"$serverspeederver"-["$release"_"$kernel_result"]" $BIN > /dev/null 2>&1
mv "acce-"$serverspeederver"-["$release"_"$kernel_result"]" 91yunserverspeeder/apxfiles/bin/
#
cd 91yunserverspeeder
bash install.sh > /dev/null 2>&1
#
#chattr +i /serverspeeder/etc/apx*
bash /serverspeeder/bin/serverSpeeder.sh status
``` | /content/code_sandbox/serverspeeder-v.sh | shell | 2016-03-11T18:31:52 | 2024-08-15T10:09:17 | serverspeeder | 91yun/serverspeeder | 2,919 | 972 |
```shell
#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin
export PATH
#
#url
APX=path_to_url
#
INSTALLPACK=path_to_url
#
CHECKSYSTEM=path_to_url
#bin
BIN=downloadurl
#
Get_Dist_Name()
{
if grep -Eqi "CentOS" /etc/issue || grep -Eq "CentOS" /etc/*-release; then
DISTRO='CentOS'
PM='yum'
elif grep -Eqi "Debian" /etc/issue || grep -Eq "Debian" /etc/*-release; then
DISTRO='Debian'
PM='apt'
elif grep -Eqi "Ubuntu" /etc/issue || grep -Eq "Ubuntu" /etc/*-release; then
DISTRO='Ubuntu'
PM='apt'
elif grep -Eqi "Raspbian" /etc/issue || grep -Eq "Raspbian" /etc/*-release; then
DISTRO='Raspbian'
PM='apt'
else
DISTRO='unknow'
fi
Get_OS_Bit
}
Get_OS_Bit()
{
if [[ `getconf WORD_BIT` = '32' && `getconf LONG_BIT` = '64' ]] ; then
ver3='x64'
else
ver3='x32'
fi
}
Get_Dist_Name
#
if [ "$DISTRO" == "CentOS" ];then
yum install -y redhat-lsb curl net-tools
elif [ "$DISTRO" == "Debian" ];then
apt-get update
apt-get install -y lsb-release curl
elif [ "$DISTRO" == "Raspbian" ];then
apt-get update
apt-get install -y lsb-release curl
elif [ "$DISTRO" == "Ubuntu" ];then
apt-get update
apt-get install -y lsb-release curl
else
echo "centosubuntudebianpath_to_url"
exit 1
fi
release=$DISTRO
#
if [ "$release" == "Debian" ]; then
ver1str="lsb_release -rs | awk -F '.' '{ print \$1 }'"
else
ver1str="lsb_release -rs | awk -F '.' '{ print \$1\".\"\$2 }'"
fi
ver1=$(eval $ver1str)
#ver11=`echo $ver1 | awk -F '.' '{ print $1 }'`
#
ver2=`uname -r`
#
ver4=3.10.61.0
echo "================================================="
echo "$release "
echo "$ver1 "
echo "$ver2 "
echo "$ver3 "
echo "$ver4 "
echo "================================================="
#bin
curl "path_to_url" -o serverspeederbin.txt || { echo "path_to_url";exit 1; }
#
grep -q "$release/$ver11[^/]*/$ver2/$ver3" serverspeederbin.txt
if [ $? == 1 ]; then
#echo ""
if [ "$release" == "CentOS" ]; then
ver21=`echo $ver2 | awk -F '-' '{ print $1 }'`
ver22=`echo $ver2 | awk -F '-' '{ print $2 }' | awk -F '.' '{ print $1 }'`
#cat serverspeederbin.txt | grep -q "$release/$ver1/$ver21-$ver22[^/]*/$ver3/"
cat serverspeederbin.txt | grep -q "$release/$ver11[^/]*/$ver21-$ver22[^/]*/$ver3/"
if [ $? == 1 ]; then
echo -e "\r\n"
echo ".path_to_url"
exit 1
fi
echo ",()"
echo -e " \033[41;37m $ver2 \033[0m"
cat serverspeederbin.txt | grep "$release/$ver11[^/]*/$ver21-$ver22[^/]*/$ver3/" | awk -F '/' '{ print NR""$3 }'
fi
if [[ "$release" == "Ubuntu" ]] || [[ "$release" == "Debian" ]]; then
ver21=`echo $ver2 | awk -F '-' '{ print $1 }'`
ver22=`echo $ver2 | awk -F '-' '{ print $2 }'`
cat serverspeederbin.txt | grep -q "$release/$ver11[^/]*/$ver21(-)?$ver22[^/]*/$ver3/"
if [ $? == 1 ]; then
echo -e "\r\n"
echo ".path_to_url"
exit 1
fi
echo ",()"
echo -e " \033[41;37m $ver2 \033[0m"
cat serverspeederbin.txt | grep "$release/$ver11[^/]*/$ver21(-)?$ver22[^/]*/$ver3/" | awk -F '/' '{ print NR""$3 }'
fi
echo ""
read cver2
if [ "$cver2" == "" ]; then
echo ""
exit 1
fi
if [ "$release" == "CentOS" ]; then
cver2str="cat serverspeederbin.txt | grep \"$release/$ver11[^/]*/$ver21-$ver22[^/]*/$ver3/\" | awk -F '/' '{ print NR\"\"\$3 }' | awk -F '' '/"$cver2"/{ print \$2 }' | awk 'NR==1{print \$1}'"
fi
if [[ "$release" == "Ubuntu" ]] || [[ "$release" == "Debian" ]]; then
cver2str="cat serverspeederbin.txt | grep \"$release/$ver11[^/]*/$ver21-[^/]*/$ver3/\" | awk -F '/' '{ print NR\"\"\$3 }' | awk -F '' '/"$cver2"/{ print \$2 }' awk 'NR==1{print \$1}'"
fi
ver2=$(eval $cver2str)
if [ "$ver2" == "" ]; then
echo ""
exit 1
fi
#
fi
#
grep -q "$release/$ver1/$ver2/$ver3/$ver4" serverspeederbin.txt
if [ $? == 1 ]; then
grep -q "$release/$ver11[^/]*/$ver2/$ver3/$ver4" serverspeederbin.txt
if [ $? == 1 ]; then
echo -e "\r\n"
echo -e "\033[41;37m 3.10.60.0 \033[0m,()"
cat serverspeederbin.txt | grep "$release/$ver11[^/]*/$ver2/$ver3/" | awk -F '/' '{ print NR""$5 }'
echo ""
read cver4
if [ "$cver4" == "" ]; then
echo ""
exit 1
fi
cver4str="cat serverspeederbin.txt | grep \"$release/$ver11[^/]*/$ver2/$ver3/\" | awk -F '/' '{ print NR\"\"\$5 }' | awk -F '' '/"$cver4"/{ print \$2 }' | awk 'NR==1{print \$1}'"
ver4=$(eval $cver4str)
if [ "$ver4" == "" ]; then
echo ""
exit 1
fi
fi
#
cver1str="cat serverspeederbin.txt | grep '$release/$ver11[^/]*/$ver2/$ver3/$ver4' | awk -F '/' 'NR==1{ print \$2 }'"
ver1=$(eval $cver1str)
fi
BINFILESTR="cat serverspeederbin.txt | grep '$release/$ver1/$ver2/$ver3/$ver4/0' | awk -F '/' '{ print \$7 }'"
BINFILE=$(eval $BINFILESTR)
BIN="path_to_url"
echo $BIN
rm -rf serverspeederbin.txt
#ipipmac
# if [ "$1" == "" ]; then
# IP=$(curl ipip.net | awk -F ' ' '{print $2}' | awk -F '' '{print $2}')
# NC="ifconfig | awk -F ' |:' '/$IP/{print a}{a=\$1}'"
# NETCARD=$(eval $NC)
# else
# NETCARD=eth0
# fi
# MACSTR="LANG=C ifconfig $NETCARD | awk '/HWaddr/{ print \$5 }' "
# MAC=$(eval $MACSTR)
# if [ "$MAC" = "" ]; then
# MACSTR="LANG=C ifconfig $NETCARD | awk '/ether/{ print \$2 }' "
# MAC=$(eval $MACSTR)
# fi
# echo IP=$IP
# echo NETCARD=$NETCARD
if [ "$1" == "" ]; then
MACSTR="LANG=C ifconfig eth0 | awk '/HWaddr/{ print \$5 }' "
MAC=$(eval $MACSTR)
if [ "$MAC" == "" ]; then
MACSTR="LANG=C ifconfig eth0 | awk '/ether/{ print \$2 }' "
MAC=$(eval $MACSTR)
fi
if [ "$MAC" == "" ]; then
#MAC=$(ip link | awk -F ether '{print $2}' | awk NF | awk 'NR==1{print $1}')
echo "eth0eth0,"
exit 1
fi
else
MAC=$1
fi
echo MAC=$MAC
#
if [ "$MAC" = "" ]; then
echo "mac"
read MAC
echo "mac$MAC"
fi
#
echo "======================================"
echo ""
echo "======================================"
wget -N --no-check-certificate -O 91yunserverspeeder.tar.gz $INSTALLPACK
tar xfvz 91yunserverspeeder.tar.gz || { echo "";exit 1; }
#
echo "======================================"
echo ""
echo "======================================"
curl "$APX?mac=$MAC" -o 91yunserverspeeder/apxfiles/etc/apx-20341231.lic || { echo "$APX?mac=$MAC";exit 1;}
#
echo "======================================"
echo ""
echo "======================================"
SNO=$(curl "$APX?mac=$MAC&sno") || { echo "";exit 1; }
echo "$SNO"
sed -i "s/serial=\"sno\"/serial=\"$SNO\"/g" 91yunserverspeeder/apxfiles/etc/config
rv=$release"_"$ver1"_"$ver2
sed -i "s/Debian_7_3.2.0-4-amd64/$rv/g" 91yunserverspeeder/apxfiles/etc/config
# sed -i "s/accppp=\"1\"/accppp=\"0\"/g" 91yunserverspeeder/apxfiles/etc/config
#bin
echo "======================================"
echo "bin"
echo "======================================"
curl $BIN -o "91yunserverspeeder/apxfiles/bin/acce-3.10.61.0-["$release"_"$ver1"_"$ver2"]" || { echo "bin";exit 1; }
#
cd 91yunserverspeeder
# Restore license permission to read and write if it exist for re-install.
if [ -f /serverspeeder/etc/apx-20341231.lic ]; then
chattr -i /serverspeeder/etc/apx-20341231.lic
fi
bash install.sh
#
chattr +i /serverspeeder/etc/apx*
#CentOS7
# if [ "$release" == "CentOS" ] && [ "$ver11" == "7" ]; then
# chmod +x /etc/rc.d/rc.local
# echo "/serverspeeder/bin/serverSpeeder.sh start" >> /etc/rc.local
# fi
#
bash /serverspeeder/bin/serverSpeeder.sh status
``` | /content/code_sandbox/serverspeeder-all.sh | shell | 2016-03-11T18:31:52 | 2024-08-15T10:09:17 | serverspeeder | 91yun/serverspeeder | 2,919 | 2,668 |
```python
# -*- coding: utf-8 -*-
import logging
import lxml
import os
import os.path
import re
import requests
from AdvancedHTMLParser import AdvancedHTMLParser
from glob import iglob
from urllib.parse import urlparse
from cmsis.PackLint import PackLinter, VersionParser
from cmsis.Pack import Pack, Api, SemanticVersion
def create():
return CmsisPackLinter()
class CmsisPackVersionParser(VersionParser):
def __init__(self, logger = None):
super().__init__(logger)
self._packs = {}
def _file_version_(self, file):
v = self._regex_(file, ".*@version\s+([vV])?([0-9]+[.][0-9]+([.][0-9]+)?).*", 2)
if not v:
v = self._regex_(file, ".*\$Revision:\s+([vV])?([0-9]+[.][0-9]+([.][0-9]+)?).*", 2)
return v
def _cmtable_(self, file, skip = 0):
table = ""
dump = False
with open(file, 'r') as f:
for l in f:
if not dump and l.strip() == "<table class=\"cmtable\" summary=\"Revision History\">":
if skip > 0:
skip -= 1
else:
dump = True
if dump:
table += l.replace("<br>", "\\n").replace("\\<", "<").replace("\\>", ">")
if l.strip() == "</table>":
break
if table:
table = lxml.etree.fromstring(table)
return table
return None
def _revhistory_(self, file, skip = 0):
table = self._cmtable_(file, skip)
if table is not None:
m = re.match("[Vv]?(\d+.\d+(.\d+)?)", table[1][0].text)
if m:
return SemanticVersion(m.group(1))
else:
self._logger.info("Revision History table not found in "+file)
return None
def readme_md(self, file):
"""Get the latest release version from README.md"""
return self._regex_(file, ".*repository contains the CMSIS Version ([0-9]+[.][0-9]+([.][0-9]+)?).*")
def _dxy(self, file):
"""Get the PROJECT_NUMBER from a Doxygen configuration file."""
return self._regex_(file, "PROJECT_NUMBER\s*=\s*\"(Version\s+)?(\d+.\d+(.\d+)?)\"", 2)
def _pdsc(self, file, component = None):
pack = None
if not file in self._packs:
pack = Pack(file, None)
self._packs[file] = pack
else:
pack = self._packs[file]
if component:
history = pack.history()
for r in sorted(history.keys(), reverse=True):
m = re.search(re.escape(component)+"(:)?\s+[Vv]?(\d+.\d+(.\d+)?)", history[r], re.MULTILINE)
if m:
return SemanticVersion(m.group(2))
else:
return pack.version()
def _h(self, file):
return self._file_version_(file)
def _c(self, file):
return self._file_version_(file)
def _s(self, file):
return self._file_version_(file)
def _xsd(self, file, rev=False, history=False):
if rev:
return self._all_(file)
elif history:
return self._regex_(file, ".*[0-9]+\. [A-Z][a-z]+ [12][0-9]+: (v)?(\d+.\d+(.\d+)?).*", 2)
else:
xsd = lxml.etree.parse(str(file)).getroot()
return SemanticVersion(xsd.get("version", None))
def overview_txt(self, file, skip = 0):
return self._revhistory_(file, skip)
def introduction_txt(self, file, component = None):
table = self._cmtable_(file)
if table is None:
return None
if component:
m = re.search(re.escape(component)+"\s+[Vv]?(\d+.\d+(.\d+)?)", table[1][1].text, re.MULTILINE)
if m:
return SemanticVersion(m.group(1))
else:
return SemanticVersion(table[1][0].text)
def dap_txt(self, file, skip = 0):
return self._revhistory_(file, skip)
def general_txt(self, file, skip = 0):
return self._revhistory_(file, skip)
def history_txt(self, file, skip = 0):
return self._revhistory_(file, skip)
def _all_(self, file):
"""Get the version or revision tag from an arbitrary file."""
version = self._regex_(file, ".*@version\s+([vV])?([0-9]+[.][0-9]+([.][0-9]+)?).*", 2)
if not version:
version = self._regex_(file, ".*\$Revision:\s+([vV])?([0-9]+[.][0-9]+([.][0-9]+)?).*", 2)
return version
class CmsisPackLinter(PackLinter):
def __init__(self, pdsc = "ARM.CMSIS.pdsc"):
super().__init__(pdsc)
self._versionParser = CmsisPackVersionParser(self._logger)
def pack_version(self):
return self._pack.version()
def cmsis_corem_component(self):
rte = { 'components' : set(), 'Dcore' : "Cortex-M3", 'Dvendor' : "*", 'Dname' : "*", 'Dtz' : "*", 'Dsecure' : "*", 'Tcompiler' : "*", 'Toptions' : "*" }
cs = self._pack.component_by_name(rte, "CMSIS.CORE")
cvs = { SemanticVersion(c.version()) for c in cs }
if len(cvs) > 1:
self.warning("Not all CMSIS-Core(M) components have same version information: %s", str([ (c.name(), c.version()) for c in cs ]))
return cvs.pop()
def cmsis_corea_component(self):
rte = { 'components' : set(), 'Dcore' : "Cortex-A9", 'Dvendor' : "*", 'Dname' : "*", 'Dtz' : "*", 'Dsecure' : "*", 'Tcompiler' : "*", 'Toptions' : "*" }
cs = self._pack.component_by_name(rte, "CMSIS.CORE")
cvs = { SemanticVersion(c.version()) for c in cs }
if len(cvs) > 1:
self.warning("Not all CMSIS-Core(A) components have same version information: %s", str([ (c.name(), c.version()) for c in cs ]))
return cvs.pop()
def cmsis_rtos2_api(self):
cs = self._pack.components_by_name("CMSIS.RTOS2")
cvs = { SemanticVersion(c.version()) for c in cs }
if len(cvs) > 1:
self.warning("Not all CMSIS-RTOS2 APIs have same version information: %s", str([ (c.name(), c.version()) for c in cs ]))
return cvs.pop()
def cmsis_rtx5_component(self):
cs = self._pack.components_by_name("CMSIS.RTOS2.Keil RTX5*")
cvs = { (SemanticVersion(c.version()), SemanticVersion(c.apiversion())) for c in cs }
if len(cvs) == 1:
return cvs.pop()
elif len(cvs) > 1:
self.warning("Not all RTX5 components have same version information: %s", str([ (c.name(), c.version(), c.apiversion()) for c in cs ]))
return None, None
def check_general(self):
"""CMSIS version"""
v = self.pack_version()
self.verify_version("README.md", v)
self.verify_version("CMSIS/DoxyGen/General/general.dxy", v)
self.verify_version("CMSIS/DoxyGen/General/src/introduction.txt", v)
def check_build(self):
"""CMSIS-Build version"""
v = self._versionParser.get_version("CMSIS/DoxyGen/Build/Build.dxy")
self.verify_version("CMSIS/DoxyGen/Build/src/General.txt", v)
self.verify_version("CMSIS/DoxyGen/General/src/introduction.txt", v, component="CMSIS-Build")
self.verify_version(self._pack.location(), v, component="CMSIS-Build")
def check_corem(self):
"""CMSIS-Core(M) version"""
v = self.cmsis_corem_component()
self.verify_version("CMSIS/DoxyGen/Core/core.dxy", v)
self.verify_version("CMSIS/DoxyGen/Core/src/Overview.txt", v)
self.verify_version("CMSIS/DoxyGen/General/src/introduction.txt", v, component="CMSIS-Core (Cortex-M)")
self.verify_version(self._pack.location(), v, component="CMSIS-Core(M)")
def check_corea(self):
"""CMSIS-Core(A) version"""
v = self.cmsis_corea_component()
self.verify_version("CMSIS/DoxyGen/Core_A/core_A.dxy", v)
self.verify_version("CMSIS/DoxyGen/Core_A/src/Overview.txt", v)
self.verify_version("CMSIS/DoxyGen/General/src/introduction.txt", v, component="CMSIS-Core (Cortex-A)")
self.verify_version(self._pack.location(), v, component="CMSIS-Core(A)")
def check_dap(self):
"""CMSIS-DAP version"""
v = self._versionParser.get_version("CMSIS/DoxyGen/DAP/dap.dxy")
self.verify_version("CMSIS/DoxyGen/DAP/src/dap.txt", v)
self.verify_version("CMSIS/DoxyGen/General/src/introduction.txt", v, component="CMSIS-DAP")
self.verify_version(self._pack.location(), v, component="CMSIS-DAP")
def check_driver(self):
"""CMSIS-Driver version"""
v = self._versionParser.get_version("CMSIS/DoxyGen/Driver/Driver.dxy")
self.verify_version("CMSIS/DoxyGen/Driver/src/General.txt", v)
self.verify_version("CMSIS/DoxyGen/General/src/introduction.txt", v, component="CMSIS-Driver")
self.verify_version(self._pack.location(), v, component="CMSIS-Driver")
def check_dsp(self):
"""CMSIS-DSP version"""
v = self._versionParser.get_version("CMSIS/DoxyGen/DSP/dsp.dxy")
self.verify_version("CMSIS/DoxyGen/DSP/src/history.txt", v)
self.verify_version("CMSIS/DoxyGen/General/src/introduction.txt", v, component="CMSIS-DSP")
self.verify_version(self._pack.location(), v, component="CMSIS-DSP")
def check_nn(self):
"""CMSIS-NN version"""
v = self._versionParser.get_version("CMSIS/DoxyGen/NN/nn.dxy")
self.verify_version("CMSIS/DoxyGen/NN/src/history.txt", v)
self.verify_version("CMSIS/DoxyGen/General/src/introduction.txt", v, component="CMSIS-NN")
self.verify_version(self._pack.location(), v, component="CMSIS-NN")
def check_pack(self):
"""CMSIS-Pack version"""
v = self._versionParser.get_version("CMSIS/Utilities/PACK.xsd")
self.verify_version("CMSIS/Utilities/PACK.xsd:Revision", v, rev=True)
self.verify_version("CMSIS/Utilities/PACK.xsd:History", v, history=True)
self.verify_version("CMSIS/DoxyGen/Pack/Pack.dxy", v)
self.verify_version("CMSIS/DoxyGen/Pack/src/General.txt", v)
self.verify_version("CMSIS/DoxyGen/General/src/introduction.txt", v, component="CMSIS-Pack")
self.verify_version(self._pack.location(), v, component="CMSIS-Pack")
def check_rtos2(self):
"""CMSIS-RTOS2 version"""
api = self.cmsis_rtos2_api()
v, a = self.cmsis_rtx5_component()
self.verify_version("CMSIS/DoxyGen/RTOS2/rtos.dxy", api)
self.verify_version("CMSIS/DoxyGen/RTOS2/src/history.txt", api, skip=0)
self.verify_version("CMSIS/DoxyGen/General/src/introduction.txt", api, component="CMSIS-RTOS")
# self.verify_version(self._pack.location(), v, component="CMSIS-RTOS2")
if a and not api.match(a):
self.warning("RTX5 API version (%s) does not match RTOS2 API version (%s)!", a, api)
self.verify_version("CMSIS/DoxyGen/RTOS2/src/history.txt", v, skip=1)
def check_files(self):
"""Files referenced by pack description"""
# Check schema of pack description
self.verify_schema(self._pack.location(), "CMSIS/Utilities/PACK.xsd")
# Check schema of SVD files
svdfiles = { d.svdfile() for d in self._pack.devices() if d.svdfile() }
for svd in svdfiles:
if os.path.exists(svd):
self.verify_schema(svd, "CMSIS/Utilities/CMSIS-SVD.xsd")
else:
self.warning("SVD File does not exist: %s!", svd)
# Check component file version
for c in self._pack.components():
cv = c.version()
for f in c.files():
hv = f.version()
if c is Api:
if f.isHeader():
if not hv:
self.verify_version(f.location(), cv)
if hv:
self.verify_version(f.location(), SemanticVersion(hv))
def check_doc(self, pattern="./CMSIS/Documentation/**/*.html"):
"""Documentation"""
self.debug("Using pattern '%s'", pattern)
for html in iglob(pattern, recursive=True):
parser = AdvancedHTMLParser()
parser.parseFile(html)
links = parser.getElementsByTagName("a")
if links:
self.info("%s: Checking links ...", html)
else:
self.debug("%s: No links found...", html)
for l in links:
href = l.getAttribute("href")
if href:
href = urlparse(href)
if href.scheme in ["http", "https", "ftp", "ftps" ]:
try:
self.info("%s: Checking link to %s...", html, href.geturl())
r = requests.head(href.geturl(), headers={'user-agent' : "packlint/1.0"}, timeout=10)
if r.status_code >= 400:
self.debug(f'HEAD method failed with HTTP-{r.status_code}, falling back to GET method.')
r = requests.get(href.geturl(), headers={'user-agent': "packlint/1.0"}, timeout=10)
r.raise_for_status()
except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError) as e:
exc_info = None
if self.loglevel() == logging.DEBUG:
exc_info = e
self.warning("%s: Broken web-link to %s!", html, href.geturl(), exc_info=exc_info)
except requests.exceptions.Timeout as e:
exc_info = None
if self.loglevel() == logging.DEBUG:
exc_info = e
self.warning("%s: Timeout following web-link to %s.", html, href.geturl(), exc_info=exc_info)
elif href.scheme == "javascript":
pass
elif not os.path.isabs(href.path):
target = os.path.normpath(os.path.join(os.path.dirname(html), href.path))
if not os.path.exists(target):
self.warning("%s: Broken relative-link to %s!", html, href.path)
else:
self.warning("%s: Broken relative-link to %s!", html, href.path)
``` | /content/code_sandbox/linter.py | python | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 3,617 |
```c
/* your_sha256_hash------
*
* $Date: 30. November 2011
* $Revision: V0.02
*
* Project: CMSIS-RTOS API
* Title: os_sample.c
*
* Description: This file shows the usage of the CMSIS-RTOS API.
*
*
* Version 0.02
* Initial Proposal Phase
* your_sha256_hash---- */
#include "my_objects.h" // Define CMSIS OS Objects
// dummy functions since there is no OS today
/// Add a thread to ActiveThreads and set it to state READY
osThreadId osThreadCreate (const osThreadDef_t *thread_def, void *argument) { return osOK; }
/// Terminate execution of a thread and remove it from ActiveThreads
osStatus osThreadTerminate (osThreadId thread_id) { return osOK; }
/// Change prority of an existing thread
osStatus osThreadSetPriority (osThreadId thread_id, osPriority priority) { return osOK; }
/// Get current prority of an existing thread
osPriority osThreadGetPriority (osThreadId thread_id) { return osPriorityNormal; }
osMessageQId osMessageCreate (const osMessageQDef_t *queue_def, osThreadId thread_id) { return NULL; }
osThreadId osThreadGetId (void) { return 0; }
osStatus status;
osThreadId thread_sample1;
osThreadId thread_sample2;
osMessageQDef(TcpMessageQ0, 10, a_element *);
osMessageQDef(TcpMessageQ1, 10, a_element *);
osMessageQDef(TcpMessageQ2, 10, a_element *);
osMessageQDef(TcpMessageQ3, 10, a_element *);
const osMessageQDef_t *TcpMessageQDef[4]
#if 1
= {
osMessageQ(TcpMessageQ0),
osMessageQ(TcpMessageQ1),
osMessageQ(TcpMessageQ2),
osMessageQ(TcpMessageQ3),
}
#endif
;
osMessageQId TcpMessageQ[4];
void CreateMessageQueues (void) {
uint32_t i;
for (i = 0; i < 4; i++) {
TcpMessageQ[i] = osMessageCreate (TcpMessageQDef[i], NULL);
}
}
int main (void) {
thread_sample1 = osThreadCreate (osThread (thread_sample), NULL);
thread_sample2 = osThreadCreate (osThread (thread_sample), NULL);
}
``` | /content/code_sandbox/CMSIS/RTOS/Template/os_sample.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 557 |
```objective-c
/* your_sha256_hash------
* $Date: 5. February 2013
* $Revision: V1.02
*
* Project: CMSIS-RTOS API
* Title: cmsis_os.h template header file
*
* Version 0.02
* Initial Proposal Phase
* Version 0.03
* osKernelStart added, optional feature: main started as thread
* osSemaphores have standard behavior
* osTimerCreate does not start the timer, added osTimerStart
* osThreadPass is renamed to osThreadYield
* Version 1.01
* Support for C++ interface
* - const attribute removed from the osXxxxDef_t typedef's
* - const attribute added to the osXxxxDef macros
* Added: osTimerDelete, osMutexDelete, osSemaphoreDelete
* Added: osKernelInitialize
* Version 1.02
* Control functions for short timeouts in microsecond resolution:
* Added: osKernelSysTick, osKernelSysTickFrequency, osKernelSysTickMicroSec
* Removed: osSignalGet
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#ifndef _CMSIS_OS_H
#define _CMSIS_OS_H
/// \note MUST REMAIN UNCHANGED: \b osCMSIS identifies the CMSIS-RTOS API version.
#define osCMSIS 0x10002 ///< API version (main [31:16] .sub [15:0])
/// \note CAN BE CHANGED: \b osCMSIS_KERNEL identifies the underlying RTOS kernel and version number.
#define osCMSIS_KERNEL 0x10000 ///< RTOS identification and version (main [31:16] .sub [15:0])
/// \note MUST REMAIN UNCHANGED: \b osKernelSystemId shall be consistent in every CMSIS-RTOS.
#define osKernelSystemId "KERNEL V1.00" ///< RTOS identification string
/// \note MUST REMAIN UNCHANGED: \b osFeature_xxx shall be consistent in every CMSIS-RTOS.
#define osFeature_MainThread 1 ///< main thread 1=main can be thread, 0=not available
#define osFeature_Pool 1 ///< Memory Pools: 1=available, 0=not available
#define osFeature_MailQ 1 ///< Mail Queues: 1=available, 0=not available
#define osFeature_MessageQ 1 ///< Message Queues: 1=available, 0=not available
#define osFeature_Signals 8 ///< maximum number of Signal Flags available per thread
#define osFeature_Semaphore 30 ///< maximum count for \ref osSemaphoreCreate function
#define osFeature_Wait 1 ///< osWait function: 1=available, 0=not available
#define osFeature_SysTick 1 ///< osKernelSysTick functions: 1=available, 0=not available
#include <stdint.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C"
{
#endif
// ==== Enumeration, structures, defines ====
/// Priority used for thread control.
/// \note MUST REMAIN UNCHANGED: \b osPriority shall be consistent in every CMSIS-RTOS.
typedef enum {
osPriorityIdle = -3, ///< priority: idle (lowest)
osPriorityLow = -2, ///< priority: low
osPriorityBelowNormal = -1, ///< priority: below normal
osPriorityNormal = 0, ///< priority: normal (default)
osPriorityAboveNormal = +1, ///< priority: above normal
osPriorityHigh = +2, ///< priority: high
osPriorityRealtime = +3, ///< priority: realtime (highest)
osPriorityError = 0x84 ///< system cannot determine priority or thread has illegal priority
} osPriority;
/// Timeout value.
/// \note MUST REMAIN UNCHANGED: \b osWaitForever shall be consistent in every CMSIS-RTOS.
#define osWaitForever 0xFFFFFFFF ///< wait forever timeout value
/// Status code values returned by CMSIS-RTOS functions.
/// \note MUST REMAIN UNCHANGED: \b osStatus shall be consistent in every CMSIS-RTOS.
typedef enum {
osOK = 0, ///< function completed; no error or event occurred.
osEventSignal = 0x08, ///< function completed; signal event occurred.
osEventMessage = 0x10, ///< function completed; message event occurred.
osEventMail = 0x20, ///< function completed; mail event occurred.
osEventTimeout = 0x40, ///< function completed; timeout occurred.
osErrorParameter = 0x80, ///< parameter error: a mandatory parameter was missing or specified an incorrect object.
osErrorResource = 0x81, ///< resource not available: a specified resource was not available.
osErrorTimeoutResource = 0xC1, ///< resource not available within given time: a specified resource was not available within the timeout period.
osErrorISR = 0x82, ///< not allowed in ISR context: the function cannot be called from interrupt service routines.
osErrorISRRecursive = 0x83, ///< function called multiple times from ISR with same object.
osErrorPriority = 0x84, ///< system cannot determine priority or thread has illegal priority.
osErrorNoMemory = 0x85, ///< system is out of memory: it was impossible to allocate or reserve memory for the operation.
osErrorValue = 0x86, ///< value of a parameter is out of range.
osErrorOS = 0xFF, ///< unspecified RTOS error: run-time error but no other error message fits.
os_status_reserved = 0x7FFFFFFF ///< prevent from enum down-size compiler optimization.
} osStatus;
/// Timer type value for the timer definition.
/// \note MUST REMAIN UNCHANGED: \b os_timer_type shall be consistent in every CMSIS-RTOS.
typedef enum {
osTimerOnce = 0, ///< one-shot timer
osTimerPeriodic = 1 ///< repeating timer
} os_timer_type;
/// Entry point of a thread.
/// \note MUST REMAIN UNCHANGED: \b os_pthread shall be consistent in every CMSIS-RTOS.
typedef void (*os_pthread) (void const *argument);
/// Entry point of a timer call back function.
/// \note MUST REMAIN UNCHANGED: \b os_ptimer shall be consistent in every CMSIS-RTOS.
typedef void (*os_ptimer) (void const *argument);
// >>> the following data type definitions may shall adapted towards a specific RTOS
/// Thread ID identifies the thread (pointer to a thread control block).
/// \note CAN BE CHANGED: \b os_thread_cb is implementation specific in every CMSIS-RTOS.
typedef struct os_thread_cb *osThreadId;
/// Timer ID identifies the timer (pointer to a timer control block).
/// \note CAN BE CHANGED: \b os_timer_cb is implementation specific in every CMSIS-RTOS.
typedef struct os_timer_cb *osTimerId;
/// Mutex ID identifies the mutex (pointer to a mutex control block).
/// \note CAN BE CHANGED: \b os_mutex_cb is implementation specific in every CMSIS-RTOS.
typedef struct os_mutex_cb *osMutexId;
/// Semaphore ID identifies the semaphore (pointer to a semaphore control block).
/// \note CAN BE CHANGED: \b os_semaphore_cb is implementation specific in every CMSIS-RTOS.
typedef struct os_semaphore_cb *osSemaphoreId;
/// Pool ID identifies the memory pool (pointer to a memory pool control block).
/// \note CAN BE CHANGED: \b os_pool_cb is implementation specific in every CMSIS-RTOS.
typedef struct os_pool_cb *osPoolId;
/// Message ID identifies the message queue (pointer to a message queue control block).
/// \note CAN BE CHANGED: \b os_messageQ_cb is implementation specific in every CMSIS-RTOS.
typedef struct os_messageQ_cb *osMessageQId;
/// Mail ID identifies the mail queue (pointer to a mail queue control block).
/// \note CAN BE CHANGED: \b os_mailQ_cb is implementation specific in every CMSIS-RTOS.
typedef struct os_mailQ_cb *osMailQId;
/// Thread Definition structure contains startup information of a thread.
/// \note CAN BE CHANGED: \b os_thread_def is implementation specific in every CMSIS-RTOS.
typedef struct os_thread_def {
os_pthread pthread; ///< start address of thread function
osPriority tpriority; ///< initial thread priority
uint32_t instances; ///< maximum number of instances of that thread function
uint32_t stacksize; ///< stack size requirements in bytes; 0 is default stack size
} osThreadDef_t;
/// Timer Definition structure contains timer parameters.
/// \note CAN BE CHANGED: \b os_timer_def is implementation specific in every CMSIS-RTOS.
typedef struct os_timer_def {
os_ptimer ptimer; ///< start address of a timer function
} osTimerDef_t;
/// Mutex Definition structure contains setup information for a mutex.
/// \note CAN BE CHANGED: \b os_mutex_def is implementation specific in every CMSIS-RTOS.
typedef struct os_mutex_def {
uint32_t dummy; ///< dummy value.
} osMutexDef_t;
/// Semaphore Definition structure contains setup information for a semaphore.
/// \note CAN BE CHANGED: \b os_semaphore_def is implementation specific in every CMSIS-RTOS.
typedef struct os_semaphore_def {
uint32_t dummy; ///< dummy value.
} osSemaphoreDef_t;
/// Definition structure for memory block allocation.
/// \note CAN BE CHANGED: \b os_pool_def is implementation specific in every CMSIS-RTOS.
typedef struct os_pool_def {
uint32_t pool_sz; ///< number of items (elements) in the pool
uint32_t item_sz; ///< size of an item
void *pool; ///< pointer to memory for pool
} osPoolDef_t;
/// Definition structure for message queue.
/// \note CAN BE CHANGED: \b os_messageQ_def is implementation specific in every CMSIS-RTOS.
typedef struct os_messageQ_def {
uint32_t queue_sz; ///< number of elements in the queue
uint32_t item_sz; ///< size of an item
void *pool; ///< memory array for messages
} osMessageQDef_t;
/// Definition structure for mail queue.
/// \note CAN BE CHANGED: \b os_mailQ_def is implementation specific in every CMSIS-RTOS.
typedef struct os_mailQ_def {
uint32_t queue_sz; ///< number of elements in the queue
uint32_t item_sz; ///< size of an item
void *pool; ///< memory array for mail
} osMailQDef_t;
/// Event structure contains detailed information about an event.
/// \note MUST REMAIN UNCHANGED: \b os_event shall be consistent in every CMSIS-RTOS.
/// However the struct may be extended at the end.
typedef struct {
osStatus status; ///< status code: event or error information
union {
uint32_t v; ///< message as 32-bit value
void *p; ///< message or mail as void pointer
int32_t signals; ///< signal flags
} value; ///< event value
union {
osMailQId mail_id; ///< mail id obtained by \ref osMailCreate
osMessageQId message_id; ///< message id obtained by \ref osMessageCreate
} def; ///< event definition
} osEvent;
// ==== Kernel Control Functions ====
/// Initialize the RTOS Kernel for creating objects.
/// \return status code that indicates the execution status of the function.
/// \note MUST REMAIN UNCHANGED: \b osKernelInitialize shall be consistent in every CMSIS-RTOS.
osStatus osKernelInitialize (void);
/// Start the RTOS Kernel.
/// \return status code that indicates the execution status of the function.
/// \note MUST REMAIN UNCHANGED: \b osKernelStart shall be consistent in every CMSIS-RTOS.
osStatus osKernelStart (void);
/// Check if the RTOS kernel is already started.
/// \note MUST REMAIN UNCHANGED: \b osKernelRunning shall be consistent in every CMSIS-RTOS.
/// \return 0 RTOS is not started, 1 RTOS is started.
int32_t osKernelRunning(void);
#if (defined (osFeature_SysTick) && (osFeature_SysTick != 0)) // System Timer available
/// Get the RTOS kernel system timer counter
/// \note MUST REMAIN UNCHANGED: \b osKernelSysTick shall be consistent in every CMSIS-RTOS.
/// \return RTOS kernel system timer as 32-bit value
uint32_t osKernelSysTick (void);
/// The RTOS kernel system timer frequency in Hz
/// \note Reflects the system timer setting and is typically defined in a configuration file.
#define osKernelSysTickFrequency 100000000
/// Convert a microseconds value to a RTOS kernel system timer value.
/// \param microsec time value in microseconds.
/// \return time value normalized to the \ref osKernelSysTickFrequency
#define osKernelSysTickMicroSec(microsec) (((uint64_t)microsec * (osKernelSysTickFrequency)) / 1000000)
#endif // System Timer available
// ==== Thread Management ====
/// Create a Thread Definition with function, priority, and stack requirements.
/// \param name name of the thread function.
/// \param priority initial priority of the thread function.
/// \param instances number of possible thread instances.
/// \param stacksz stack size (in bytes) requirements for the thread function.
/// \note CAN BE CHANGED: The parameters to \b osThreadDef shall be consistent but the
/// macro body is implementation specific in every CMSIS-RTOS.
#if defined (osObjectsExternal) // object is external
#define osThreadDef(name, priority, instances, stacksz) \
extern const osThreadDef_t os_thread_def_##name
#else // define the object
#define osThreadDef(name, priority, instances, stacksz) \
const osThreadDef_t os_thread_def_##name = \
{ (name), (priority), (instances), (stacksz) }
#endif
/// Access a Thread definition.
/// \param name name of the thread definition object.
/// \note CAN BE CHANGED: The parameter to \b osThread shall be consistent but the
/// macro body is implementation specific in every CMSIS-RTOS.
#define osThread(name) \
&os_thread_def_##name
/// Create a thread and add it to Active Threads and set it to state READY.
/// \param[in] thread_def thread definition referenced with \ref osThread.
/// \param[in] argument pointer that is passed to the thread function as start argument.
/// \return thread ID for reference by other functions or NULL in case of error.
/// \note MUST REMAIN UNCHANGED: \b osThreadCreate shall be consistent in every CMSIS-RTOS.
osThreadId osThreadCreate (const osThreadDef_t *thread_def, void *argument);
/// Return the thread ID of the current running thread.
/// \return thread ID for reference by other functions or NULL in case of error.
/// \note MUST REMAIN UNCHANGED: \b osThreadGetId shall be consistent in every CMSIS-RTOS.
osThreadId osThreadGetId (void);
/// Terminate execution of a thread and remove it from Active Threads.
/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
/// \return status code that indicates the execution status of the function.
/// \note MUST REMAIN UNCHANGED: \b osThreadTerminate shall be consistent in every CMSIS-RTOS.
osStatus osThreadTerminate (osThreadId thread_id);
/// Pass control to next thread that is in state \b READY.
/// \return status code that indicates the execution status of the function.
/// \note MUST REMAIN UNCHANGED: \b osThreadYield shall be consistent in every CMSIS-RTOS.
osStatus osThreadYield (void);
/// Change priority of an active thread.
/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
/// \param[in] priority new priority value for the thread function.
/// \return status code that indicates the execution status of the function.
/// \note MUST REMAIN UNCHANGED: \b osThreadSetPriority shall be consistent in every CMSIS-RTOS.
osStatus osThreadSetPriority (osThreadId thread_id, osPriority priority);
/// Get current priority of an active thread.
/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
/// \return current priority value of the thread function.
/// \note MUST REMAIN UNCHANGED: \b osThreadGetPriority shall be consistent in every CMSIS-RTOS.
osPriority osThreadGetPriority (osThreadId thread_id);
// ==== Generic Wait Functions ====
/// Wait for Timeout (Time Delay).
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue "time delay" value
/// \return status code that indicates the execution status of the function.
osStatus osDelay (uint32_t millisec);
#if (defined (osFeature_Wait) && (osFeature_Wait != 0)) // Generic Wait available
/// Wait for Signal, Message, Mail, or Timeout.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out
/// \return event that contains signal, message, or mail information or error code.
/// \note MUST REMAIN UNCHANGED: \b osWait shall be consistent in every CMSIS-RTOS.
osEvent osWait (uint32_t millisec);
#endif // Generic Wait available
// ==== Timer Management Functions ====
/// Define a Timer object.
/// \param name name of the timer object.
/// \param function name of the timer call back function.
/// \note CAN BE CHANGED: The parameter to \b osTimerDef shall be consistent but the
/// macro body is implementation specific in every CMSIS-RTOS.
#if defined (osObjectsExternal) // object is external
#define osTimerDef(name, function) \
extern const osTimerDef_t os_timer_def_##name
#else // define the object
#define osTimerDef(name, function) \
const osTimerDef_t os_timer_def_##name = \
{ (function) }
#endif
/// Access a Timer definition.
/// \param name name of the timer object.
/// \note CAN BE CHANGED: The parameter to \b osTimer shall be consistent but the
/// macro body is implementation specific in every CMSIS-RTOS.
#define osTimer(name) \
&os_timer_def_##name
/// Create a timer.
/// \param[in] timer_def timer object referenced with \ref osTimer.
/// \param[in] type osTimerOnce for one-shot or osTimerPeriodic for periodic behavior.
/// \param[in] argument argument to the timer call back function.
/// \return timer ID for reference by other functions or NULL in case of error.
/// \note MUST REMAIN UNCHANGED: \b osTimerCreate shall be consistent in every CMSIS-RTOS.
osTimerId osTimerCreate (const osTimerDef_t *timer_def, os_timer_type type, void *argument);
/// Start or restart a timer.
/// \param[in] timer_id timer ID obtained by \ref osTimerCreate.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue "time delay" value of the timer.
/// \return status code that indicates the execution status of the function.
/// \note MUST REMAIN UNCHANGED: \b osTimerStart shall be consistent in every CMSIS-RTOS.
osStatus osTimerStart (osTimerId timer_id, uint32_t millisec);
/// Stop the timer.
/// \param[in] timer_id timer ID obtained by \ref osTimerCreate.
/// \return status code that indicates the execution status of the function.
/// \note MUST REMAIN UNCHANGED: \b osTimerStop shall be consistent in every CMSIS-RTOS.
osStatus osTimerStop (osTimerId timer_id);
/// Delete a timer that was created by \ref osTimerCreate.
/// \param[in] timer_id timer ID obtained by \ref osTimerCreate.
/// \return status code that indicates the execution status of the function.
/// \note MUST REMAIN UNCHANGED: \b osTimerDelete shall be consistent in every CMSIS-RTOS.
osStatus osTimerDelete (osTimerId timer_id);
// ==== Signal Management ====
/// Set the specified Signal Flags of an active thread.
/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
/// \param[in] signals specifies the signal flags of the thread that should be set.
/// \return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters.
/// \note MUST REMAIN UNCHANGED: \b osSignalSet shall be consistent in every CMSIS-RTOS.
int32_t osSignalSet (osThreadId thread_id, int32_t signals);
/// Clear the specified Signal Flags of an active thread.
/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
/// \param[in] signals specifies the signal flags of the thread that shall be cleared.
/// \return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters or call from ISR.
/// \note MUST REMAIN UNCHANGED: \b osSignalClear shall be consistent in every CMSIS-RTOS.
int32_t osSignalClear (osThreadId thread_id, int32_t signals);
/// Wait for one or more Signal Flags to become signaled for the current \b RUNNING thread.
/// \param[in] signals wait until all specified signal flags set or 0 for any single signal flag.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out.
/// \return event flag information or error code.
/// \note MUST REMAIN UNCHANGED: \b osSignalWait shall be consistent in every CMSIS-RTOS.
osEvent osSignalWait (int32_t signals, uint32_t millisec);
// ==== Mutex Management ====
/// Define a Mutex.
/// \param name name of the mutex object.
/// \note CAN BE CHANGED: The parameter to \b osMutexDef shall be consistent but the
/// macro body is implementation specific in every CMSIS-RTOS.
#if defined (osObjectsExternal) // object is external
#define osMutexDef(name) \
extern const osMutexDef_t os_mutex_def_##name
#else // define the object
#define osMutexDef(name) \
const osMutexDef_t os_mutex_def_##name = { 0 }
#endif
/// Access a Mutex definition.
/// \param name name of the mutex object.
/// \note CAN BE CHANGED: The parameter to \b osMutex shall be consistent but the
/// macro body is implementation specific in every CMSIS-RTOS.
#define osMutex(name) \
&os_mutex_def_##name
/// Create and Initialize a Mutex object.
/// \param[in] mutex_def mutex definition referenced with \ref osMutex.
/// \return mutex ID for reference by other functions or NULL in case of error.
/// \note MUST REMAIN UNCHANGED: \b osMutexCreate shall be consistent in every CMSIS-RTOS.
osMutexId osMutexCreate (const osMutexDef_t *mutex_def);
/// Wait until a Mutex becomes available.
/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out.
/// \return status code that indicates the execution status of the function.
/// \note MUST REMAIN UNCHANGED: \b osMutexWait shall be consistent in every CMSIS-RTOS.
osStatus osMutexWait (osMutexId mutex_id, uint32_t millisec);
/// Release a Mutex that was obtained by \ref osMutexWait.
/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate.
/// \return status code that indicates the execution status of the function.
/// \note MUST REMAIN UNCHANGED: \b osMutexRelease shall be consistent in every CMSIS-RTOS.
osStatus osMutexRelease (osMutexId mutex_id);
/// Delete a Mutex that was created by \ref osMutexCreate.
/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate.
/// \return status code that indicates the execution status of the function.
/// \note MUST REMAIN UNCHANGED: \b osMutexDelete shall be consistent in every CMSIS-RTOS.
osStatus osMutexDelete (osMutexId mutex_id);
// ==== Semaphore Management Functions ====
#if (defined (osFeature_Semaphore) && (osFeature_Semaphore != 0)) // Semaphore available
/// Define a Semaphore object.
/// \param name name of the semaphore object.
/// \note CAN BE CHANGED: The parameter to \b osSemaphoreDef shall be consistent but the
/// macro body is implementation specific in every CMSIS-RTOS.
#if defined (osObjectsExternal) // object is external
#define osSemaphoreDef(name) \
extern const osSemaphoreDef_t os_semaphore_def_##name
#else // define the object
#define osSemaphoreDef(name) \
const osSemaphoreDef_t os_semaphore_def_##name = { 0 }
#endif
/// Access a Semaphore definition.
/// \param name name of the semaphore object.
/// \note CAN BE CHANGED: The parameter to \b osSemaphore shall be consistent but the
/// macro body is implementation specific in every CMSIS-RTOS.
#define osSemaphore(name) \
&os_semaphore_def_##name
/// Create and Initialize a Semaphore object used for managing resources.
/// \param[in] semaphore_def semaphore definition referenced with \ref osSemaphore.
/// \param[in] count number of available resources.
/// \return semaphore ID for reference by other functions or NULL in case of error.
/// \note MUST REMAIN UNCHANGED: \b osSemaphoreCreate shall be consistent in every CMSIS-RTOS.
osSemaphoreId osSemaphoreCreate (const osSemaphoreDef_t *semaphore_def, int32_t count);
/// Wait until a Semaphore token becomes available.
/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out.
/// \return number of available tokens, or -1 in case of incorrect parameters.
/// \note MUST REMAIN UNCHANGED: \b osSemaphoreWait shall be consistent in every CMSIS-RTOS.
int32_t osSemaphoreWait (osSemaphoreId semaphore_id, uint32_t millisec);
/// Release a Semaphore token.
/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate.
/// \return status code that indicates the execution status of the function.
/// \note MUST REMAIN UNCHANGED: \b osSemaphoreRelease shall be consistent in every CMSIS-RTOS.
osStatus osSemaphoreRelease (osSemaphoreId semaphore_id);
/// Delete a Semaphore that was created by \ref osSemaphoreCreate.
/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate.
/// \return status code that indicates the execution status of the function.
/// \note MUST REMAIN UNCHANGED: \b osSemaphoreDelete shall be consistent in every CMSIS-RTOS.
osStatus osSemaphoreDelete (osSemaphoreId semaphore_id);
#endif // Semaphore available
// ==== Memory Pool Management Functions ====
#if (defined (osFeature_Pool) && (osFeature_Pool != 0)) // Memory Pool Management available
/// \brief Define a Memory Pool.
/// \param name name of the memory pool.
/// \param no maximum number of blocks (objects) in the memory pool.
/// \param type data type of a single block (object).
/// \note CAN BE CHANGED: The parameter to \b osPoolDef shall be consistent but the
/// macro body is implementation specific in every CMSIS-RTOS.
#if defined (osObjectsExternal) // object is external
#define osPoolDef(name, no, type) \
extern const osPoolDef_t os_pool_def_##name
#else // define the object
#define osPoolDef(name, no, type) \
const osPoolDef_t os_pool_def_##name = \
{ (no), sizeof(type), NULL }
#endif
/// \brief Access a Memory Pool definition.
/// \param name name of the memory pool
/// \note CAN BE CHANGED: The parameter to \b osPool shall be consistent but the
/// macro body is implementation specific in every CMSIS-RTOS.
#define osPool(name) \
&os_pool_def_##name
/// Create and Initialize a memory pool.
/// \param[in] pool_def memory pool definition referenced with \ref osPool.
/// \return memory pool ID for reference by other functions or NULL in case of error.
/// \note MUST REMAIN UNCHANGED: \b osPoolCreate shall be consistent in every CMSIS-RTOS.
osPoolId osPoolCreate (const osPoolDef_t *pool_def);
/// Allocate a memory block from a memory pool.
/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate.
/// \return address of the allocated memory block or NULL in case of no memory available.
/// \note MUST REMAIN UNCHANGED: \b osPoolAlloc shall be consistent in every CMSIS-RTOS.
void *osPoolAlloc (osPoolId pool_id);
/// Allocate a memory block from a memory pool and set memory block to zero.
/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate.
/// \return address of the allocated memory block or NULL in case of no memory available.
/// \note MUST REMAIN UNCHANGED: \b osPoolCAlloc shall be consistent in every CMSIS-RTOS.
void *osPoolCAlloc (osPoolId pool_id);
/// Return an allocated memory block back to a specific memory pool.
/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate.
/// \param[in] block address of the allocated memory block that is returned to the memory pool.
/// \return status code that indicates the execution status of the function.
/// \note MUST REMAIN UNCHANGED: \b osPoolFree shall be consistent in every CMSIS-RTOS.
osStatus osPoolFree (osPoolId pool_id, void *block);
#endif // Memory Pool Management available
// ==== Message Queue Management Functions ====
#if (defined (osFeature_MessageQ) && (osFeature_MessageQ != 0)) // Message Queues available
/// \brief Create a Message Queue Definition.
/// \param name name of the queue.
/// \param queue_sz maximum number of messages in the queue.
/// \param type data type of a single message element (for debugger).
/// \note CAN BE CHANGED: The parameter to \b osMessageQDef shall be consistent but the
/// macro body is implementation specific in every CMSIS-RTOS.
#if defined (osObjectsExternal) // object is external
#define osMessageQDef(name, queue_sz, type) \
extern const osMessageQDef_t os_messageQ_def_##name
#else // define the object
#define osMessageQDef(name, queue_sz, type) \
const osMessageQDef_t os_messageQ_def_##name = \
{ (queue_sz), sizeof (type) }
#endif
/// \brief Access a Message Queue Definition.
/// \param name name of the queue
/// \note CAN BE CHANGED: The parameter to \b osMessageQ shall be consistent but the
/// macro body is implementation specific in every CMSIS-RTOS.
#define osMessageQ(name) \
&os_messageQ_def_##name
/// Create and Initialize a Message Queue.
/// \param[in] queue_def queue definition referenced with \ref osMessageQ.
/// \param[in] thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL.
/// \return message queue ID for reference by other functions or NULL in case of error.
/// \note MUST REMAIN UNCHANGED: \b osMessageCreate shall be consistent in every CMSIS-RTOS.
osMessageQId osMessageCreate (const osMessageQDef_t *queue_def, osThreadId thread_id);
/// Put a Message to a Queue.
/// \param[in] queue_id message queue ID obtained with \ref osMessageCreate.
/// \param[in] info message information.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out.
/// \return status code that indicates the execution status of the function.
/// \note MUST REMAIN UNCHANGED: \b osMessagePut shall be consistent in every CMSIS-RTOS.
osStatus osMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec);
/// Get a Message or Wait for a Message from a Queue.
/// \param[in] queue_id message queue ID obtained with \ref osMessageCreate.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out.
/// \return event information that includes status code.
/// \note MUST REMAIN UNCHANGED: \b osMessageGet shall be consistent in every CMSIS-RTOS.
osEvent osMessageGet (osMessageQId queue_id, uint32_t millisec);
#endif // Message Queues available
// ==== Mail Queue Management Functions ====
#if (defined (osFeature_MailQ) && (osFeature_MailQ != 0)) // Mail Queues available
/// \brief Create a Mail Queue Definition.
/// \param name name of the queue
/// \param queue_sz maximum number of messages in queue
/// \param type data type of a single message element
/// \note CAN BE CHANGED: The parameter to \b osMailQDef shall be consistent but the
/// macro body is implementation specific in every CMSIS-RTOS.
#if defined (osObjectsExternal) // object is external
#define osMailQDef(name, queue_sz, type) \
extern const osMailQDef_t os_mailQ_def_##name
#else // define the object
#define osMailQDef(name, queue_sz, type) \
const osMailQDef_t os_mailQ_def_##name = \
{ (queue_sz), sizeof (type) }
#endif
/// \brief Access a Mail Queue Definition.
/// \param name name of the queue
/// \note CAN BE CHANGED: The parameter to \b osMailQ shall be consistent but the
/// macro body is implementation specific in every CMSIS-RTOS.
#define osMailQ(name) \
&os_mailQ_def_##name
/// Create and Initialize mail queue.
/// \param[in] queue_def reference to the mail queue definition obtain with \ref osMailQ
/// \param[in] thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL.
/// \return mail queue ID for reference by other functions or NULL in case of error.
/// \note MUST REMAIN UNCHANGED: \b osMailCreate shall be consistent in every CMSIS-RTOS.
osMailQId osMailCreate (const osMailQDef_t *queue_def, osThreadId thread_id);
/// Allocate a memory block from a mail.
/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out
/// \return pointer to memory block that can be filled with mail or NULL in case of error.
/// \note MUST REMAIN UNCHANGED: \b osMailAlloc shall be consistent in every CMSIS-RTOS.
void *osMailAlloc (osMailQId queue_id, uint32_t millisec);
/// Allocate a memory block from a mail and set memory block to zero.
/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out
/// \return pointer to memory block that can be filled with mail or NULL in case of error.
/// \note MUST REMAIN UNCHANGED: \b osMailCAlloc shall be consistent in every CMSIS-RTOS.
void *osMailCAlloc (osMailQId queue_id, uint32_t millisec);
/// Put a mail to a queue.
/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate.
/// \param[in] mail memory block previously allocated with \ref osMailAlloc or \ref osMailCAlloc.
/// \return status code that indicates the execution status of the function.
/// \note MUST REMAIN UNCHANGED: \b osMailPut shall be consistent in every CMSIS-RTOS.
osStatus osMailPut (osMailQId queue_id, void *mail);
/// Get a mail from a queue.
/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out
/// \return event that contains mail information or error code.
/// \note MUST REMAIN UNCHANGED: \b osMailGet shall be consistent in every CMSIS-RTOS.
osEvent osMailGet (osMailQId queue_id, uint32_t millisec);
/// Free a memory block from a mail.
/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate.
/// \param[in] mail pointer to the memory block that was obtained with \ref osMailGet.
/// \return status code that indicates the execution status of the function.
/// \note MUST REMAIN UNCHANGED: \b osMailFree shall be consistent in every CMSIS-RTOS.
osStatus osMailFree (osMailQId queue_id, void *mail);
#endif // Mail Queues available
#ifdef __cplusplus
}
#endif
#endif // _CMSIS_OS_H
``` | /content/code_sandbox/CMSIS/RTOS/Template/cmsis_os.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 8,593 |
```c
/* your_sha256_hash------
*
* $Date: 30. November 2011
* $Revision: V0.02
*
* Project: CMSIS-RTOS API
* Title: os_sample1.c
*
* Description: This file shows the usage of the CMSIS-RTOS API.
*
* Version 0.02
* Initial Proposal Phase
* your_sha256_hash---- */
#define osObjectsExternal
#include "my_objects.h" // Reference CMSIS OS Objects
void thread_sample (void const *argument) {
osThreadId my_thread;
osPriority my_priority;
int i = 1000;
my_thread = osThreadGetId();
my_priority = osThreadGetPriority (my_thread); // Get priority of own thread
while (i > 0) {
osThreadSetPriority (my_thread, osPriorityAboveNormal);
i--;
}
osThreadSetPriority (my_thread, my_priority);
osThreadTerminate (my_thread); // terminate own thread
}
``` | /content/code_sandbox/CMSIS/RTOS/Template/os_sample1.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 230 |
```objective-c
#include "cmsis_os.h" // CMSIS RTOS header file
extern void thread_sample (void const *argument); // prototype
typedef struct a {
char y[100];
} a_element;
osThreadDef (thread_sample, osPriorityBelowNormal, 2, 100);
osPoolDef(MyPool, 10, struct a);
osMessageQDef(MyMessage, 10, a_element *);
osMailQDef(MyMail, 10, a_element);
``` | /content/code_sandbox/CMSIS/RTOS/Template/my_objects.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 103 |
```gas
;/*****************************************************************************
; * @file: startup_LPC177x_8x.s
; * @purpose: CMSIS Cortex-M3 Core Device Startup File
; * for the NXP LPC177x_8x Device Series
; * @version: V1.20
; * @date: 07. October 2010
; *------- <<< Use Configuration Wizard in Context Menu >>> ------------------
; *
; * ARM Limited (ARM) is supplying this software for use with Cortex-M3
; * processor based microcontrollers. This file can be freely distributed
; * within development tools that are supporting such ARM based processors.
; *
; * THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED
; * OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
; * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.
; * ARM SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR
; * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
; *
; *****************************************************************************/
; <h> Stack Configuration
; <o> Stack Size (in Bytes) <0x0-0xFFFFFFFF:8>
; </h>
Stack_Size EQU 0x00000200
AREA STACK, NOINIT, READWRITE, ALIGN=3
Stack_Mem SPACE Stack_Size
__initial_sp
; <h> Heap Configuration
; <o> Heap Size (in Bytes) <0x0-0xFFFFFFFF:8>
; </h>
Heap_Size EQU 0x00000000
AREA HEAP, NOINIT, READWRITE, ALIGN=3
__heap_base
Heap_Mem SPACE Heap_Size
__heap_limit
PRESERVE8
THUMB
; Vector Table Mapped to Address 0 at Reset
AREA RESET, DATA, READONLY
EXPORT __Vectors
__Vectors DCD __initial_sp ; Top of Stack
DCD Reset_Handler ; Reset Handler
DCD NMI_Handler ; NMI Handler
DCD HardFault_Handler ; Hard Fault Handler
DCD MemManage_Handler ; MPU Fault Handler
DCD BusFault_Handler ; Bus Fault Handler
DCD UsageFault_Handler ; Usage Fault Handler
DCD 0 ; Reserved
DCD 0 ; Reserved
DCD 0 ; Reserved
DCD 0 ; Reserved
DCD SVC_Handler ; SVCall Handler
DCD DebugMon_Handler ; Debug Monitor Handler
DCD 0 ; Reserved
DCD PendSV_Handler ; PendSV Handler
DCD SysTick_Handler ; SysTick Handler
; External Interrupts
DCD WDT_IRQHandler ; 16: Watchdog Timer
DCD TIMER0_IRQHandler ; 17: Timer0
DCD TIMER1_IRQHandler ; 18: Timer1
DCD TIMER2_IRQHandler ; 19: Timer2
DCD TIMER3_IRQHandler ; 20: Timer3
DCD UART0_IRQHandler ; 21: UART0
DCD UART1_IRQHandler ; 22: UART1
DCD UART2_IRQHandler ; 23: UART2
DCD UART3_IRQHandler ; 24: UART3
DCD PWM1_IRQHandler ; 25: PWM1
DCD I2C0_IRQHandler ; 26: I2C0
DCD I2C1_IRQHandler ; 27: I2C1
DCD I2C2_IRQHandler ; 28: I2C2
DCD SPIFI_IRQHandler ; 29: SPIFI
DCD SSP0_IRQHandler ; 30: SSP0
DCD SSP1_IRQHandler ; 31: SSP1
DCD PLL0_IRQHandler ; 32: PLL0 Lock (Main PLL)
DCD RTC_IRQHandler ; 33: Real Time Clock
DCD EINT0_IRQHandler ; 34: External Interrupt 0
DCD EINT1_IRQHandler ; 35: External Interrupt 1
DCD EINT2_IRQHandler ; 36: External Interrupt 2
DCD EINT3_IRQHandler ; 37: External Interrupt 3
DCD ADC_IRQHandler ; 38: A/D Converter
DCD BOD_IRQHandler ; 39: Brown-Out Detect
DCD USB_IRQHandler ; 40: USB
DCD CAN_IRQHandler ; 41: CAN
DCD DMA_IRQHandler ; 42: General Purpose DMA
DCD I2S_IRQHandler ; 43: I2S
DCD ENET_IRQHandler ; 44: Ethernet
DCD MCI_IRQHandler ; 45: SD/MMC card I/F
DCD MCPWM_IRQHandler ; 46: Motor Control PWM
DCD QEI_IRQHandler ; 47: Quadrature Encoder Interface
DCD PLL1_IRQHandler ; 48: PLL1 Lock (USB PLL)
DCD USBActivity_IRQHandler ; 49: USB Activity interrupt to wakeup
DCD CANActivity_IRQHandler ; 50: CAN Activity interrupt to wakeup
DCD UART4_IRQHandler ; 51: UART4
DCD SSP2_IRQHandler ; 52: SSP2
DCD LCD_IRQHandler ; 53: LCD
DCD GPIO_IRQHandler ; 54: GPIO
DCD PWM0_IRQHandler ; 55: PWM0
DCD EEPROM_IRQHandler ; 56: EEPROM
IF :LNOT::DEF:NO_CRP
AREA |.ARM.__at_0x02FC|, CODE, READONLY
CRP_Key DCD 0xFFFFFFFF
ENDIF
AREA |.text|, CODE, READONLY
; Reset Handler
Reset_Handler PROC
EXPORT Reset_Handler [WEAK]
IMPORT SystemInit
IMPORT __main
LDR R0, =SystemInit
BLX R0
LDR R0, =__main
BX R0
ENDP
; Dummy Exception Handlers (infinite loops which can be modified)
NMI_Handler PROC
EXPORT NMI_Handler [WEAK]
B .
ENDP
HardFault_Handler\
PROC
EXPORT HardFault_Handler [WEAK]
B .
ENDP
MemManage_Handler\
PROC
EXPORT MemManage_Handler [WEAK]
B .
ENDP
BusFault_Handler\
PROC
EXPORT BusFault_Handler [WEAK]
B .
ENDP
UsageFault_Handler\
PROC
EXPORT UsageFault_Handler [WEAK]
B .
ENDP
SVC_Handler PROC
EXPORT SVC_Handler [WEAK]
B .
ENDP
DebugMon_Handler\
PROC
EXPORT DebugMon_Handler [WEAK]
B .
ENDP
PendSV_Handler PROC
EXPORT PendSV_Handler [WEAK]
B .
ENDP
SysTick_Handler PROC
EXPORT SysTick_Handler [WEAK]
B .
ENDP
Default_Handler PROC
EXPORT WDT_IRQHandler [WEAK]
EXPORT TIMER0_IRQHandler [WEAK]
EXPORT TIMER1_IRQHandler [WEAK]
EXPORT TIMER2_IRQHandler [WEAK]
EXPORT TIMER3_IRQHandler [WEAK]
EXPORT UART0_IRQHandler [WEAK]
EXPORT UART1_IRQHandler [WEAK]
EXPORT UART2_IRQHandler [WEAK]
EXPORT UART3_IRQHandler [WEAK]
EXPORT PWM1_IRQHandler [WEAK]
EXPORT I2C0_IRQHandler [WEAK]
EXPORT I2C1_IRQHandler [WEAK]
EXPORT I2C2_IRQHandler [WEAK]
EXPORT SPIFI_IRQHandler [WEAK]
EXPORT SSP0_IRQHandler [WEAK]
EXPORT SSP1_IRQHandler [WEAK]
EXPORT PLL0_IRQHandler [WEAK]
EXPORT RTC_IRQHandler [WEAK]
EXPORT EINT0_IRQHandler [WEAK]
EXPORT EINT1_IRQHandler [WEAK]
EXPORT EINT2_IRQHandler [WEAK]
EXPORT EINT3_IRQHandler [WEAK]
EXPORT ADC_IRQHandler [WEAK]
EXPORT BOD_IRQHandler [WEAK]
EXPORT USB_IRQHandler [WEAK]
EXPORT CAN_IRQHandler [WEAK]
EXPORT DMA_IRQHandler [WEAK]
EXPORT I2S_IRQHandler [WEAK]
EXPORT ENET_IRQHandler [WEAK]
EXPORT MCI_IRQHandler [WEAK]
EXPORT MCPWM_IRQHandler [WEAK]
EXPORT QEI_IRQHandler [WEAK]
EXPORT PLL1_IRQHandler [WEAK]
EXPORT USBActivity_IRQHandler [WEAK]
EXPORT CANActivity_IRQHandler [WEAK]
EXPORT UART4_IRQHandler [WEAK]
EXPORT SSP2_IRQHandler [WEAK]
EXPORT LCD_IRQHandler [WEAK]
EXPORT GPIO_IRQHandler [WEAK]
EXPORT PWM0_IRQHandler [WEAK]
EXPORT EEPROM_IRQHandler [WEAK]
WDT_IRQHandler
TIMER0_IRQHandler
TIMER1_IRQHandler
TIMER2_IRQHandler
TIMER3_IRQHandler
UART0_IRQHandler
UART1_IRQHandler
UART2_IRQHandler
UART3_IRQHandler
PWM1_IRQHandler
I2C0_IRQHandler
I2C1_IRQHandler
I2C2_IRQHandler
SPIFI_IRQHandler
SSP0_IRQHandler
SSP1_IRQHandler
PLL0_IRQHandler
RTC_IRQHandler
EINT0_IRQHandler
EINT1_IRQHandler
EINT2_IRQHandler
EINT3_IRQHandler
ADC_IRQHandler
BOD_IRQHandler
USB_IRQHandler
CAN_IRQHandler
DMA_IRQHandler
I2S_IRQHandler
ENET_IRQHandler
MCI_IRQHandler
MCPWM_IRQHandler
QEI_IRQHandler
PLL1_IRQHandler
USBActivity_IRQHandler
CANActivity_IRQHandler
UART4_IRQHandler
SSP2_IRQHandler
LCD_IRQHandler
GPIO_IRQHandler
PWM0_IRQHandler
EEPROM_IRQHandler
B .
ENDP
ALIGN
; User Initial Stack & Heap
IF :DEF:__MICROLIB
EXPORT __initial_sp
EXPORT __heap_base
EXPORT __heap_limit
ELSE
IMPORT __use_two_region_memory
EXPORT __user_initial_stackheap
__user_initial_stackheap
LDR R0, = Heap_Mem
LDR R1, =(Stack_Mem + Stack_Size)
LDR R2, = (Heap_Mem + Heap_Size)
LDR R3, = Stack_Mem
BX LR
ALIGN
ENDIF
END
``` | /content/code_sandbox/CMSIS/RTOS/Template/startup_LPC177x_8x.s | gas | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 2,442 |
```objective-c
#ifndef MEMORYPOOL_H
#define MEMORYPOOL_H
#include <stdint.h>
#include <string.h>
#include "cmsis_os.h"
namespace rtos {
/*! Define and manage fixed-size memory pools of objects of a given type.
\tparam T data type of a single object (element).
\tparam queue_sz maximum number of objects (elements) in the memory pool.
*/
template<typename T, uint32_t pool_sz>
class MemoryPool {
public:
/*! Create and Initialize a memory pool. */
MemoryPool() {
#ifdef CMSIS_OS_RTX
memset(_pool_m, 0, sizeof(_pool_m));
_pool_def.pool = _pool_m;
_pool_def.pool_sz = pool_sz;
_pool_def.item_sz = sizeof(T);
#endif
_pool_id = osPoolCreate(&_pool_def);
}
/*! Allocate a memory block of type T from a memory pool.
\return address of the allocated memory block or NULL in case of no memory available.
*/
T* alloc(void) {
return (T*)osPoolAlloc(_pool_id);
}
/*! Allocate a memory block of type T from a memory pool and set memory block to zero.
\return address of the allocated memory block or NULL in case of no memory available.
*/
T* calloc(void) {
return (T*)osPoolCAlloc(_pool_id);
}
/*! Return an allocated memory block back to a specific memory pool.
\param address of the allocated memory block that is returned to the memory pool.
\return status code that indicates the execution status of the function.
*/
osStatus free(T *block) {
return osPoolFree(_pool_id, (void*)block);
}
private:
osPoolId _pool_id;
osPoolDef_t _pool_def;
#ifdef CMSIS_OS_RTX
uint32_t _pool_m[3+((sizeof(T)+3)/4)*(pool_sz)];
#endif
};
}
#endif
``` | /content/code_sandbox/CMSIS/RTOS/Template/CPP/MemoryPool.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 439 |
```c++
#include "RtosTimer.h"
#include <string.h>
#include "cmsis_os.h"
//#include "error.h"
namespace rtos {
RtosTimer::RtosTimer(void (*periodic_task)(void const *argument), os_timer_type type, void *argument) {
#ifdef CMSIS_OS_RTX
_timer.ptimer = periodic_task;
memset(_timer_data, 0, sizeof(_timer_data));
_timer.timer = _timer_data;
#endif
_timer_id = osTimerCreate(&_timer, type, argument);
}
osStatus RtosTimer::start(uint32_t millisec) {
return osTimerStart(_timer_id, millisec);
}
osStatus RtosTimer::stop(void) {
return osTimerStop(_timer_id);
}
}
``` | /content/code_sandbox/CMSIS/RTOS/Template/CPP/RtosTimer.cpp | c++ | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 164 |
```objective-c
#ifndef MAIL_H
#define MAIL_H
#include <stdint.h>
#include <string.h>
#include "cmsis_os.h"
namespace rtos {
/*! The Mail class allow to control, send, receive, or wait for mail.
A mail is a memory block that is send to a thread or interrupt service routine.
\tparam T data type of a single message element.
\tparam queue_sz maximum number of messages in queue.
*/
template<typename T, uint32_t queue_sz>
class Mail {
public:
/*! Create and Initialise Mail queue. */
Mail() {
#ifdef CMSIS_OS_RTX
memset(_mail_q, 0, sizeof(_mail_q));
_mail_p[0] = _mail_q;
memset(_mail_m, 0, sizeof(_mail_m));
_mail_p[1] = _mail_m;
_mail_def.pool = _mail_p;
_mail_def.queue_sz = queue_sz;
_mail_def.item_sz = sizeof(T);
#endif
_mail_id = osMailCreate(&_mail_def, NULL);
}
/*! Allocate a memory block of type T
\param millisec timeout value or 0 in case of no time-out. (default: 0).
\return pointer to memory block that can be filled with mail or NULL in case error.
*/
T* alloc(uint32_t millisec=0) {
return (T*)osMailAlloc(_mail_id, millisec);
}
/*! Allocate a memory block of type T and set memory block to zero.
\param millisec timeout value or 0 in case of no time-out. (default: 0).
\return pointer to memory block that can be filled with mail or NULL in case error.
*/
T* calloc(uint32_t millisec=0) {
return (T*)osMailCAlloc(_mail_id, millisec);
}
/*! Put a mail in the queue.
\param mptr memory block previously allocated with Mail::alloc or Mail::calloc.
\return status code that indicates the execution status of the function.
*/
osStatus put(T *mptr) {
return osMailPut(_mail_id, (void*)mptr);
}
/*! Get a mail from a queue.
\param millisec timeout value or 0 in case of no time-out. (default: osWaitForever).
\return event that contains mail information or error code.
*/
osEvent get(uint32_t millisec=osWaitForever) {
return osMailGet(_mail_id, millisec);
}
/*! Free a memory block from a mail.
\param mptr pointer to the memory block that was obtained with Mail::get.
\return status code that indicates the execution status of the function.
*/
osStatus free(T *mptr) {
return osMailFree(_mail_id, (void*)mptr);
}
private:
osMailQId _mail_id;
osMailQDef_t _mail_def;
#ifdef CMSIS_OS_RTX
uint32_t _mail_q[4+(queue_sz)];
uint32_t _mail_m[3+((sizeof(T)+3)/4)*(queue_sz)];
void *_mail_p[2];
#endif
};
}
#endif
``` | /content/code_sandbox/CMSIS/RTOS/Template/CPP/Mail.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 729 |
```objective-c
#ifndef THREAD_H
#define THREAD_H
#include <stdint.h>
#include "cmsis_os.h"
#define DEFAULT_STACK_SIZE 0x1000
namespace rtos {
/*! The Thread class allow defining, creating, and controlling thread functions in the system. */
class Thread {
public:
/*! Create a new thread, and start it executing the specified function.
\param task function to be executed by this thread.
\param argument pointer that is passed to the thread function as start argument. (default: NULL).
\param priority initial priority of the thread function. (default: osPriorityNormal).
\param stacksz stack size (in bytes) requirements for the thread function. (default: DEFAULT_STACK_SIZE).
*/
Thread(void (*task)(void const *argument),
void *argument=NULL,
osPriority priority=osPriorityNormal,
uint32_t stacksize=DEFAULT_STACK_SIZE);
/*! Terminate execution of a thread and remove it from Active Threads
\return status code that indicates the execution status of the function.
*/
osStatus terminate();
/*! Set priority of an active thread
\param priority new priority value for the thread function.
\return status code that indicates the execution status of the function.
*/
osStatus set_priority(osPriority priority);
/*! Get priority of an active thread
\ return current priority value of the thread function.
*/
osPriority get_priority();
/*! Set the specified Signal Flags of an active thread.
\param signals specifies the signal flags of the thread that should be set.
\return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters.
*/
int32_t signal_set(int32_t signals);
/*! Wait for one or more Signal Flags to become signaled for the current RUNNING thread.
\param signals wait until all specified signal flags set or 0 for any single signal flag.
\param millisec timeout value or 0 in case of no time-out. (default: osWaitForever).
\return event flag information or error code.
*/
static osEvent signal_wait(int32_t signals, uint32_t millisec=osWaitForever);
/*! Wait for a specified time period in millisec:
\param millisec time delay value
\return status code that indicates the execution status of the function.
*/
static osStatus wait(uint32_t millisec);
/*! Pass control to next thread that is in state READY.
\return status code that indicates the execution status of the function.
*/
static osStatus yield();
/*! Get the thread id of the current running thread.
\return thread ID for reference by other functions or NULL in case of error.
*/
static osThreadId gettid();
private:
osThreadId _tid;
osThreadDef_t _thread_def;
};
}
#endif
``` | /content/code_sandbox/CMSIS/RTOS/Template/CPP/Thread.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 632 |
```objective-c
/* mbed Microcontroller Library
*/
#ifndef RTOS_H
#define RTOS_H
#include "Thread.h"
#include "Mutex.h"
#include "RtosTimer.h"
#include "Semaphore.h"
#include "Mail.h"
#include "MemoryPool.h"
#include "Queue.h"
using namespace rtos;
#endif
``` | /content/code_sandbox/CMSIS/RTOS/Template/CPP/rtos.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 64 |
```objective-c
#ifndef QUEUE_H
#define QUEUE_H
#include <stdint.h>
#include <string.h>
#include "cmsis_os.h"
#include "error.h"
namespace rtos {
/*! The Queue class allow to control, send, receive, or wait for messages.
A message can be a integer or pointer value to a certain type T that is send
to a thread or interrupt service routine.
\tparam T data type of a single message element.
\tparam queue_sz maximum number of messages in queue.
*/
template<typename T, uint32_t queue_sz>
class Queue {
public:
/*! Create and initialise a message Queue. */
Queue() {
#ifdef CMSIS_OS_RTX
memset(_queue_q, 0, sizeof(_queue_q));
_queue_def.pool = _queue_q;
_queue_def.queue_sz = queue_sz;
#endif
_queue_id = osMessageCreate(&_queue_def, NULL);
if (_queue_id == NULL) {
error("Error initialising the queue object\n");
}
}
/*! Put a message in a Queue.
\param data message pointer.
\param millisec timeout value or 0 in case of no time-out. (default: 0)
\return status code that indicates the execution status of the function.
*/
osStatus put(T* data, uint32_t millisec=0) {
return osMessagePut(_queue_id, (uint32_t)data, millisec);
}
/*! Get a message or Wait for a message from a Queue.
\param millisec timeout value or 0 in case of no time-out. (default: osWaitForever).
\return event information that includes the message and the status code.
*/
osEvent get(uint32_t millisec=osWaitForever) {
return osMessageGet(_queue_id, millisec);
}
private:
osMessageQId _queue_id;
osMessageQDef_t _queue_def;
#ifdef CMSIS_OS_RTX
uint32_t _queue_q[4+(queue_sz)];
#endif
};
}
#endif
``` | /content/code_sandbox/CMSIS/RTOS/Template/CPP/Queue.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 456 |
```objective-c
#ifndef TIMER_H
#define TIMER_H
#include <stdint.h>
#include "cmsis_os.h"
namespace rtos {
/*! The RtosTimer class allow creating and and controlling of timer functions in the system.
A timer function is called when a time period expires whereby both on-shot and
periodic timers are possible. A timer can be started, restarted, or stopped.
Timers are handled in the thread osTimerThread.
Callback functions run under control of this thread and may use CMSIS-RTOS API calls.
*/
class RtosTimer {
public:
/*! Create and Start timer.
\param task name of the timer call back function.
\param type osTimerOnce for one-shot or osTimerPeriodic for periodic behaviour. (default: osTimerPeriodic)
\param argument argument to the timer call back function. (default: NULL)
*/
RtosTimer(void (*task)(void const *argument),
os_timer_type type=osTimerPeriodic,
void *argument=NULL);
/*! Stop the timer.
\return status code that indicates the execution status of the function.
*/
osStatus stop(void);
/*! start a timer.
\param millisec time delay value of the timer.
\return status code that indicates the execution status of the function.
*/
osStatus start(uint32_t millisec);
private:
osTimerId _timer_id;
osTimerDef_t _timer;
#ifdef CMSIS_OS_RTX
uint32_t _timer_data[5];
#endif
};
}
#endif
``` | /content/code_sandbox/CMSIS/RTOS/Template/CPP/RtosTimer.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 334 |
```objective-c
#ifndef SEMAPHORE_H
#define SEMAPHORE_H
#include <stdint.h>
#include "cmsis_os.h"
namespace rtos {
/*! The Semaphore class is used to manage and protect access to a set of shared resources. */
class Semaphore {
public:
/*! Create and Initialize a Semaphore object used for managing resources.
\param number of available resources; maximum index value is (count-1).
*/
Semaphore(int32_t count);
/*! Wait until a Semaphore resource becomes available.
\param millisec timeout value or 0 in case of no time-out. (default: osWaitForever).
\return number of available tokens, or -1 in case of incorrect parameters
*/
int32_t wait(uint32_t millisec=osWaitForever);
/*! Release a Semaphore resource that was obtain with Semaphore::wait.
\return status code that indicates the execution status of the function.
*/
osStatus release(void);
private:
osSemaphoreId _osSemaphoreId;
osSemaphoreDef_t _osSemaphoreDef;
#ifdef CMSIS_OS_RTX
uint32_t _semaphore_data[2];
#endif
};
}
#endif
``` | /content/code_sandbox/CMSIS/RTOS/Template/CPP/Semaphore.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 249 |
```c++
#include "Thread.h"
namespace rtos {
Thread::Thread(void (*task)(void const *argument),
void *argument,
osPriority priority,
uint32_t stacksize) {
// The actual fields of os_thread_def are implementation specific in every CMSIS-RTOS
#ifdef CMSIS_OS_RTX
_thread_def.pthread = task;
_thread_def.tpriority = priority;
_thread_def.instances = 1;
_thread_def.stacksize = stacksize;
#endif
_tid = osThreadCreate(&_thread_def, argument);
}
osStatus Thread::terminate() {
return osThreadTerminate(_tid);
}
osStatus Thread::set_priority(osPriority priority) {
return osThreadSetPriority(_tid, priority);
}
osPriority Thread::get_priority() {
return osThreadGetPriority(_tid);
}
int32_t Thread::signal_set(int32_t signals) {
return osSignalSet(_tid, signals);
}
osEvent Thread::signal_wait(int32_t signals, uint32_t millisec) {
return osSignalWait(signals, millisec);
}
osStatus Thread::wait(uint32_t millisec) {
return osDelay(millisec);
}
osStatus Thread::yield() {
return osThreadYield();
}
osThreadId Thread::gettid() {
return osThreadGetId();
}
}
``` | /content/code_sandbox/CMSIS/RTOS/Template/CPP/Thread.cpp | c++ | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 283 |
```c++
#include "Mutex.h"
#include <string.h>
//#include "error.h"
namespace rtos {
Mutex::Mutex() {
#ifdef CMSIS_OS_RTX
memset(_mutex_data, 0, sizeof(_mutex_data));
_osMutexDef.mutex = _mutex_data;
#endif
_osMutexId = osMutexCreate(&_osMutexDef);
if (_osMutexId == NULL) {
// error("Error initializing the mutex object\n");
}
}
osStatus Mutex::lock(uint32_t millisec) {
return osMutexWait(_osMutexId, millisec);
}
bool Mutex::trylock() {
return (osMutexWait(_osMutexId, 0) == osOK);
}
osStatus Mutex::unlock() {
return osMutexRelease(_osMutexId);
}
}
``` | /content/code_sandbox/CMSIS/RTOS/Template/CPP/Mutex.cpp | c++ | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 169 |
```objective-c
#ifndef MUTEX_H
#define MUTEX_H
#include <stdint.h>
#include "cmsis_os.h"
namespace rtos {
/*! The Mutex class is used to synchronise the execution of threads.
This is for example used to protect access to a shared resource.
*/
class Mutex {
public:
/*! Create and Initialize a Mutex object */
Mutex();
/*! Wait until a Mutex becomes available.
\param millisec timeout value or 0 in case of no time-out. (default: osWaitForever)
\return status code that indicates the execution status of the function.
*/
osStatus lock(uint32_t millisec=osWaitForever);
/*! Try to lock the mutex, and return immediately
\return true if the mutex was acquired, false otherwise.
*/
bool trylock();
/*! Unlock the mutex that has previously been locked by the same thread
\return status code that indicates the execution status of the function.
*/
osStatus unlock();
private:
osMutexId _osMutexId;
osMutexDef_t _osMutexDef;
#ifdef CMSIS_OS_RTX
int32_t _mutex_data[3];
#endif
};
}
#endif
``` | /content/code_sandbox/CMSIS/RTOS/Template/CPP/Mutex.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 256 |
```c++
#include "Semaphore.h"
#include <string.h>
//#include "error.h"
namespace rtos {
Semaphore::Semaphore(int32_t count) {
#ifdef CMSIS_OS_RTX
memset(_semaphore_data, 0, sizeof(_semaphore_data));
_osSemaphoreDef.semaphore = _semaphore_data;
#endif
_osSemaphoreId = osSemaphoreCreate(&_osSemaphoreDef, count);
}
int32_t Semaphore::wait(uint32_t millisec) {
return osSemaphoreWait(_osSemaphoreId, millisec);
}
osStatus Semaphore::release(void) {
return osSemaphoreRelease(_osSemaphoreId);
}
}
``` | /content/code_sandbox/CMSIS/RTOS/Template/CPP/Semaphore.cpp | c++ | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 132 |
```c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_TIMER.C
* Purpose: User timer functions
* Rev.: V4.70
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#include "rt_TypeDef.h"
#include "RTX_Config.h"
#include "rt_Timer.h"
#include "rt_MemBox.h"
#ifndef __CMSIS_RTOS
/*your_sha256_hash------------
* Global Variables
*your_sha256_hash-----------*/
/* User Timer list pointer */
struct OS_XTMR os_tmr;
/*your_sha256_hash------------
* Functions
*your_sha256_hash-----------*/
/*--------------------------- rt_tmr_tick -----------------------------------*/
void rt_tmr_tick (void) {
/* Decrement delta count of timer list head. Timers having the value of */
/* zero are removed from the list and the callback function is called. */
P_TMR p;
if (os_tmr.next == NULL) {
return;
}
os_tmr.tcnt--;
while ((os_tmr.tcnt == 0U) && ((p = os_tmr.next) != NULL)) {
/* Call a user provided function to handle an elapsed timer */
os_tmr_call (p->info);
os_tmr.tcnt = p->tcnt;
os_tmr.next = p->next;
rt_free_box ((U32 *)m_tmr, p);
}
}
/*--------------------------- rt_tmr_create ---------------------------------*/
OS_ID rt_tmr_create (U16 tcnt, U16 info) {
/* Create an user timer and put it into the chained timer list using */
/* a timeout count value of "tcnt". User parameter "info" is used as a */
/* parameter for the user provided callback function "os_tmr_call ()". */
P_TMR p_tmr, p;
U32 delta,itcnt = tcnt;
if ((tcnt == 0U) || (m_tmr == NULL)) {
return (NULL);
}
p_tmr = rt_alloc_box ((U32 *)m_tmr);
if (!p_tmr) {
return (NULL);
}
p_tmr->info = info;
p = (P_TMR)&os_tmr;
delta = p->tcnt;
while ((delta < itcnt) && (p->next != NULL)) {
p = p->next;
delta += p->tcnt;
}
/* Right place found, insert timer into the list */
p_tmr->next = p->next;
p_tmr->tcnt = (U16)(delta - itcnt);
p->next = p_tmr;
p->tcnt -= p_tmr->tcnt;
return (p_tmr);
}
/*--------------------------- rt_tmr_kill -----------------------------------*/
OS_ID rt_tmr_kill (OS_ID timer) {
/* Remove user timer from the chained timer list. */
P_TMR p, p_tmr;
p_tmr = (P_TMR)timer;
p = (P_TMR)&os_tmr;
/* Search timer list for requested timer */
while (p->next != p_tmr) {
if (p->next == NULL) {
/* Failed, "timer" is not in the timer list */
return (p_tmr);
}
p = p->next;
}
/* Timer was found, remove it from the list */
p->next = p_tmr->next;
p->tcnt += p_tmr->tcnt;
rt_free_box ((U32 *)m_tmr, p_tmr);
/* Timer killed */
return (NULL);
}
#endif
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_Timer.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 875 |
```c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_SEMAPHORE.C
* Purpose: Implements binary and counting semaphores
* Rev.: V4.79
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#include "rt_TypeDef.h"
#include "RTX_Config.h"
#include "rt_System.h"
#include "rt_List.h"
#include "rt_Task.h"
#include "rt_Semaphore.h"
#include "rt_HAL_CM.h"
/*your_sha256_hash------------
* Functions
*your_sha256_hash-----------*/
/*--------------------------- rt_sem_init -----------------------------------*/
void rt_sem_init (OS_ID semaphore, U16 token_count) {
/* Initialize a semaphore */
P_SCB p_SCB = semaphore;
p_SCB->cb_type = SCB;
p_SCB->p_lnk = NULL;
p_SCB->tokens = token_count;
}
/*--------------------------- rt_sem_delete ---------------------------------*/
#ifdef __CMSIS_RTOS
OS_RESULT rt_sem_delete (OS_ID semaphore) {
/* Delete semaphore */
P_SCB p_SCB = semaphore;
P_TCB p_TCB;
while (p_SCB->p_lnk != NULL) {
/* A task is waiting for token */
p_TCB = rt_get_first ((P_XCB)p_SCB);
rt_ret_val(p_TCB, 0U);
rt_rmv_dly(p_TCB);
p_TCB->state = READY;
rt_put_prio (&os_rdy, p_TCB);
}
if ((os_rdy.p_lnk != NULL) && (os_rdy.p_lnk->prio > os_tsk.run->prio)) {
/* preempt running task */
rt_put_prio (&os_rdy, os_tsk.run);
os_tsk.run->state = READY;
rt_dispatch (NULL);
}
p_SCB->cb_type = 0U;
return (OS_R_OK);
}
#endif
/*--------------------------- rt_sem_send -----------------------------------*/
OS_RESULT rt_sem_send (OS_ID semaphore) {
/* Return a token to semaphore */
P_SCB p_SCB = semaphore;
P_TCB p_TCB;
if (p_SCB->p_lnk != NULL) {
/* A task is waiting for token */
p_TCB = rt_get_first ((P_XCB)p_SCB);
#ifdef __CMSIS_RTOS
rt_ret_val(p_TCB, 1U);
#else
rt_ret_val(p_TCB, OS_R_SEM);
#endif
rt_rmv_dly (p_TCB);
rt_dispatch (p_TCB);
}
else {
/* Store token. */
p_SCB->tokens++;
}
return (OS_R_OK);
}
/*--------------------------- rt_sem_wait -----------------------------------*/
OS_RESULT rt_sem_wait (OS_ID semaphore, U16 timeout) {
/* Obtain a token; possibly wait for it */
P_SCB p_SCB = semaphore;
if (p_SCB->tokens) {
p_SCB->tokens--;
return (OS_R_OK);
}
/* No token available: wait for one */
if (timeout == 0U) {
return (OS_R_TMO);
}
if (p_SCB->p_lnk != NULL) {
rt_put_prio ((P_XCB)p_SCB, os_tsk.run);
}
else {
p_SCB->p_lnk = os_tsk.run;
os_tsk.run->p_lnk = NULL;
os_tsk.run->p_rlnk = (P_TCB)p_SCB;
}
rt_block(timeout, WAIT_SEM);
return (OS_R_TMO);
}
/*--------------------------- isr_sem_send ----------------------------------*/
void isr_sem_send (OS_ID semaphore) {
/* Same function as "os_sem_send", but to be called by ISRs */
P_SCB p_SCB = semaphore;
rt_psq_enq (p_SCB, 0U);
rt_psh_req ();
}
/*--------------------------- rt_sem_psh ------------------------------------*/
void rt_sem_psh (P_SCB p_CB) {
/* Check if task has to be waken up */
P_TCB p_TCB;
if (p_CB->p_lnk != NULL) {
/* A task is waiting for token */
p_TCB = rt_get_first ((P_XCB)p_CB);
rt_rmv_dly (p_TCB);
p_TCB->state = READY;
#ifdef __CMSIS_RTOS
rt_ret_val(p_TCB, 1U);
#else
rt_ret_val(p_TCB, OS_R_SEM);
#endif
rt_put_prio (&os_rdy, p_TCB);
}
else {
/* Store token */
p_CB->tokens++;
}
}
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_Semaphore.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 1,109 |
```objective-c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_HAL_CM.H
* Purpose: Hardware Abstraction Layer for Cortex-M definitions
* Rev.: V4.79
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
/* Definitions */
#define INITIAL_xPSR 0x01000000U
#define DEMCR_TRCENA 0x01000000U
#define ITM_ITMENA 0x00000001U
#define MAGIC_WORD 0xE25A2EA5U
#define MAGIC_PATTERN 0xCCCCCCCCU
#if defined (__CC_ARM) /* ARM Compiler */
#if ((defined(__TARGET_ARCH_7_M) || defined(__TARGET_ARCH_7E_M)) && !defined(NO_EXCLUSIVE_ACCESS))
#define __USE_EXCLUSIVE_ACCESS
#else
#undef __USE_EXCLUSIVE_ACCESS
#endif
#ifndef __CMSIS_GENERIC
#define __DMB() do {\
__schedule_barrier();\
__dmb(0xF);\
__schedule_barrier();\
} while (0)
#endif
#elif defined (__GNUC__) /* GNU Compiler */
#undef __USE_EXCLUSIVE_ACCESS
#if defined (__CORTEX_M0)
#define __TARGET_ARCH_6S_M
#endif
#if defined (__VFP_FP__) && !defined(__SOFTFP__)
#define __TARGET_FPU_VFP
#endif
#define __inline inline
#define __weak __attribute__((weak))
#ifndef __CMSIS_GENERIC
__attribute__((always_inline)) static inline void __enable_irq(void)
{
__asm volatile ("cpsie i");
}
__attribute__((always_inline)) static inline U32 __disable_irq(void)
{
U32 result;
__asm volatile ("mrs %0, primask" : "=r" (result));
__asm volatile ("cpsid i");
return(result & 1);
}
__attribute__((always_inline)) static inline void __DMB(void)
{
__asm volatile ("dmb 0xF":::"memory");
}
#endif
__attribute__(( always_inline)) static inline U8 __clz(U32 value)
{
U8 result;
__asm volatile ("clz %0, %1" : "=r" (result) : "r" (value));
return(result);
}
#elif defined (__ICCARM__) /* IAR Compiler */
#undef __USE_EXCLUSIVE_ACCESS
#if (__CORE__ == __ARM6M__)
#define __TARGET_ARCH_6S_M 1
#endif
#if defined __ARMVFP__
#define __TARGET_FPU_VFP 1
#endif
#define __inline inline
#ifndef __CMSIS_GENERIC
static inline void __enable_irq(void)
{
__asm volatile ("cpsie i");
}
static inline U32 __disable_irq(void)
{
U32 result;
__asm volatile ("mrs %0, primask" : "=r" (result));
__asm volatile ("cpsid i");
return(result & 1);
}
#endif
static inline U8 __clz(U32 value)
{
U8 result;
__asm volatile ("clz %0, %1" : "=r" (result) : "r" (value));
return(result);
}
#endif
/* NVIC registers */
#define NVIC_ST_CTRL (*((volatile U32 *)0xE000E010U))
#define NVIC_ST_RELOAD (*((volatile U32 *)0xE000E014U))
#define NVIC_ST_CURRENT (*((volatile U32 *)0xE000E018U))
#define NVIC_ISER ((volatile U32 *)0xE000E100U)
#define NVIC_ICER ((volatile U32 *)0xE000E180U)
#if defined(__TARGET_ARCH_6S_M)
#define NVIC_IP ((volatile U32 *)0xE000E400U)
#else
#define NVIC_IP ((volatile U8 *)0xE000E400U)
#endif
#define NVIC_INT_CTRL (*((volatile U32 *)0xE000ED04U))
#define NVIC_AIR_CTRL (*((volatile U32 *)0xE000ED0CU))
#define NVIC_SYS_PRI2 (*((volatile U32 *)0xE000ED1CU))
#define NVIC_SYS_PRI3 (*((volatile U32 *)0xE000ED20U))
#define OS_PEND_IRQ() NVIC_INT_CTRL = (1UL<<28)
#define OS_PENDING ((NVIC_INT_CTRL >> 26) & 5U)
#define OS_UNPEND(fl) NVIC_INT_CTRL = (U32)(fl = (U8)OS_PENDING) << 25
#define OS_PEND(fl,p) NVIC_INT_CTRL = (U32)(fl | (U8)(p<<2)) << 26
#define OS_LOCK() NVIC_ST_CTRL = 0x0005U
#define OS_UNLOCK() NVIC_ST_CTRL = 0x0007U
#define OS_X_PENDING ((NVIC_INT_CTRL >> 28) & 1U)
#define OS_X_UNPEND(fl) NVIC_INT_CTRL = (U32)(fl = (U8)OS_X_PENDING) << 27
#define OS_X_PEND(fl,p) NVIC_INT_CTRL = (U32)(fl | p) << 28
#if defined(__TARGET_ARCH_6S_M)
#define OS_X_INIT(n) NVIC_IP[n>>2] |= (U32)0xFFU << ((n & 0x03U) << 3); \
NVIC_ISER[n>>5] = (U32)1U << (n & 0x1FU)
#else
#define OS_X_INIT(n) NVIC_IP[n] = 0xFFU; \
NVIC_ISER[n>>5] = (U32)1U << (n & 0x1FU)
#endif
#define OS_X_LOCK(n) NVIC_ICER[n>>5] = (U32)1U << (n & 0x1FU)
#define OS_X_UNLOCK(n) NVIC_ISER[n>>5] = (U32)1U << (n & 0x1FU)
/* Core Debug registers */
#define DEMCR (*((volatile U32 *)0xE000EDFCU))
/* ITM registers */
#define ITM_CONTROL (*((volatile U32 *)0xE0000E80U))
#define ITM_ENABLE (*((volatile U32 *)0xE0000E00U))
#define ITM_PORT30_U32 (*((volatile U32 *)0xE0000078U))
#define ITM_PORT31_U32 (*((volatile U32 *)0xE000007CU))
#define ITM_PORT31_U16 (*((volatile U16 *)0xE000007CU))
#define ITM_PORT31_U8 (*((volatile U8 *)0xE000007CU))
/* Variables */
extern BIT dbg_msg;
/* Functions */
#ifdef __USE_EXCLUSIVE_ACCESS
#define rt_inc(p) while(__strex((__ldrex(p)+1U),p))
#define rt_dec(p) while(__strex((__ldrex(p)-1U),p))
#else
#define rt_inc(p) __disable_irq();(*p)++;__enable_irq();
#define rt_dec(p) __disable_irq();(*p)--;__enable_irq();
#endif
__inline static U32 rt_inc_qi (U32 size, U8 *count, U8 *first) {
U32 cnt,c2;
#ifdef __USE_EXCLUSIVE_ACCESS
do {
if ((cnt = __ldrex(count)) == size) {
__clrex();
return (cnt); }
} while (__strex(cnt+1U, count));
do {
c2 = (cnt = __ldrex(first)) + 1U;
if (c2 == size) { c2 = 0U; }
} while (__strex(c2, first));
#else
__disable_irq();
if ((cnt = *count) < size) {
*count = (U8)(cnt+1U);
c2 = (cnt = *first) + 1U;
if (c2 == size) { c2 = 0U; }
*first = (U8)c2;
}
__enable_irq ();
#endif
return (cnt);
}
__inline static void rt_systick_init (void) {
NVIC_ST_RELOAD = os_trv;
NVIC_ST_CURRENT = 0U;
NVIC_ST_CTRL = 0x0007U;
NVIC_SYS_PRI3 |= 0xFF000000U;
}
__inline static U32 rt_systick_val (void) {
return (os_trv - NVIC_ST_CURRENT);
}
__inline static U32 rt_systick_ovf (void) {
return ((NVIC_INT_CTRL >> 26) & 1U);
}
__inline static void rt_svc_init (void) {
#if !defined(__TARGET_ARCH_6S_M)
U32 sh,prigroup;
#endif
NVIC_SYS_PRI3 |= 0x00FF0000U;
#if defined(__TARGET_ARCH_6S_M)
NVIC_SYS_PRI2 |= (NVIC_SYS_PRI3<<(8+1)) & 0xFC000000U;
#else
sh = 8U - __clz(~((NVIC_SYS_PRI3 << 8) & 0xFF000000U));
prigroup = ((NVIC_AIR_CTRL >> 8) & 0x07U);
if (prigroup >= sh) {
sh = prigroup + 1U;
}
NVIC_SYS_PRI2 = ((0xFEFFFFFFU << sh) & 0xFF000000U) | (NVIC_SYS_PRI2 & 0x00FFFFFFU);
#endif
}
extern void rt_set_PSP (U32 stack);
extern U32 rt_get_PSP (void);
extern void os_set_env (void);
extern void *_alloc_box (void *box_mem);
extern U32 _free_box (void *box_mem, void *box);
extern void rt_init_stack (P_TCB p_TCB, FUNCP task_body);
extern void rt_ret_val (P_TCB p_TCB, U32 v0);
extern void rt_ret_val2 (P_TCB p_TCB, U32 v0, U32 v1);
extern void dbg_init (void);
extern void dbg_task_notify (P_TCB p_tcb, BOOL create);
extern void dbg_task_switch (U32 task_id);
#ifdef DBG_MSG
#define DBG_INIT() dbg_init()
#define DBG_TASK_NOTIFY(p_tcb,create) if (dbg_msg) dbg_task_notify(p_tcb,create)
#define DBG_TASK_SWITCH(task_id) if (dbg_msg && (os_tsk.next!=os_tsk.run)) \
dbg_task_switch(task_id)
#else
#define DBG_INIT()
#define DBG_TASK_NOTIFY(p_tcb,create)
#define DBG_TASK_SWITCH(task_id)
#endif
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_HAL_CM.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 2,364 |
```c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_MEMBOX.C
* Purpose: Interface functions for fixed memory block management system
* Rev.: V4.79
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#include "rt_TypeDef.h"
#include "RTX_Config.h"
#include "rt_System.h"
#include "rt_MemBox.h"
#include "rt_HAL_CM.h"
/*your_sha256_hash------------
* Global Functions
*your_sha256_hash-----------*/
/*--------------------------- _init_box -------------------------------------*/
U32 _init_box (void *box_mem, U32 box_size, U32 blk_size) {
/* Initialize memory block system, returns 0 if OK, 1 if fails. */
void *end;
void *blk;
void *next;
U32 sizeof_bm;
/* Create memory structure. */
if (blk_size & BOX_ALIGN_8) {
/* Memory blocks 8-byte aligned. */
blk_size = ((blk_size & ~BOX_ALIGN_8) + 7U) & ~(U32)7U;
sizeof_bm = (sizeof (struct OS_BM) + 7U) & ~(U32)7U;
}
else {
/* Memory blocks 4-byte aligned. */
blk_size = (blk_size + 3U) & ~(U32)3U;
sizeof_bm = sizeof (struct OS_BM);
}
if (blk_size == 0U) {
return (1U);
}
if ((blk_size + sizeof_bm) > box_size) {
return (1U);
}
/* Create a Memory structure. */
blk = ((U8 *) box_mem) + sizeof_bm;
((P_BM) box_mem)->free = blk;
end = ((U8 *) box_mem) + box_size;
((P_BM) box_mem)->end = end;
((P_BM) box_mem)->blk_size = blk_size;
/* Link all free blocks using offsets. */
end = ((U8 *) end) - blk_size;
while (1) {
next = ((U8 *) blk) + blk_size;
if (next > end) { break; }
*((void **)blk) = next;
blk = next;
}
/* end marker */
*((void **)blk) = 0U;
return (0U);
}
/*--------------------------- rt_alloc_box ----------------------------------*/
void *rt_alloc_box (void *box_mem) {
/* Allocate a memory block and return start address. */
void **free;
#ifndef __USE_EXCLUSIVE_ACCESS
U32 irq_mask;
irq_mask = (U32)__disable_irq ();
free = ((P_BM) box_mem)->free;
if (free) {
((P_BM) box_mem)->free = *free;
}
if (irq_mask == 0U) { __enable_irq (); }
#else
do {
if ((free = (void **)__ldrex(&((P_BM) box_mem)->free)) == 0U) {
__clrex();
break;
}
} while (__strex((U32)*free, &((P_BM) box_mem)->free));
#endif
return (free);
}
/*--------------------------- _calloc_box -----------------------------------*/
void *_calloc_box (void *box_mem) {
/* Allocate a 0-initialized memory block and return start address. */
void *free;
U32 *p;
U32 i;
free = _alloc_box (box_mem);
if (free) {
p = free;
for (i = ((P_BM) box_mem)->blk_size; i; i -= 4U) {
*p = 0U;
p++;
}
}
return (free);
}
/*--------------------------- rt_free_box -----------------------------------*/
U32 rt_free_box (void *box_mem, void *box) {
/* Free a memory block, returns 0 if OK, 1 if box does not belong to box_mem */
#ifndef __USE_EXCLUSIVE_ACCESS
U32 irq_mask;
#endif
if ((box < box_mem) || (box >= ((P_BM) box_mem)->end)) {
return (1U);
}
#ifndef __USE_EXCLUSIVE_ACCESS
irq_mask = (U32)__disable_irq ();
*((void **)box) = ((P_BM) box_mem)->free;
((P_BM) box_mem)->free = box;
if (irq_mask == 0U) { __enable_irq (); }
#else
do {
do {
*((void **)box) = ((P_BM) box_mem)->free;
__DMB();
} while (*(void**)box != (void *)__ldrex(&((P_BM) box_mem)->free));
} while (__strex ((U32)box, &((P_BM) box_mem)->free));
#endif
return (0U);
}
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_MemBox.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 1,152 |
```c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_MUTEX.C
* Purpose: Implements mutex synchronization objects
* Rev.: V4.82
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#include "rt_TypeDef.h"
#include "RTX_Config.h"
#include "rt_List.h"
#include "rt_Task.h"
#include "rt_Mutex.h"
#include "rt_HAL_CM.h"
/*your_sha256_hash------------
* Functions
*your_sha256_hash-----------*/
/*--------------------------- rt_mut_init -----------------------------------*/
void rt_mut_init (OS_ID mutex) {
/* Initialize a mutex object */
P_MUCB p_MCB = mutex;
p_MCB->cb_type = MUCB;
p_MCB->level = 0U;
p_MCB->p_lnk = NULL;
p_MCB->owner = NULL;
p_MCB->p_mlnk = NULL;
}
/*--------------------------- rt_mut_delete ---------------------------------*/
#ifdef __CMSIS_RTOS
OS_RESULT rt_mut_delete (OS_ID mutex) {
/* Delete a mutex object */
P_MUCB p_MCB = mutex;
P_TCB p_TCB;
P_MUCB p_mlnk;
U8 prio;
if (p_MCB->level != 0U) {
p_TCB = p_MCB->owner;
/* Remove mutex from task mutex owner list. */
p_mlnk = p_TCB->p_mlnk;
if (p_mlnk == p_MCB) {
p_TCB->p_mlnk = p_MCB->p_mlnk;
}
else {
while (p_mlnk) {
if (p_mlnk->p_mlnk == p_MCB) {
p_mlnk->p_mlnk = p_MCB->p_mlnk;
break;
}
p_mlnk = p_mlnk->p_mlnk;
}
}
/* Restore owner task's priority. */
prio = p_TCB->prio_base;
p_mlnk = p_TCB->p_mlnk;
while (p_mlnk) {
if ((p_mlnk->p_lnk != NULL) && (p_mlnk->p_lnk->prio > prio)) {
/* A task with higher priority is waiting for mutex. */
prio = p_mlnk->p_lnk->prio;
}
p_mlnk = p_mlnk->p_mlnk;
}
if (p_TCB->prio != prio) {
p_TCB->prio = prio;
if (p_TCB != os_tsk.run) {
rt_resort_prio (p_TCB);
}
}
}
while (p_MCB->p_lnk != NULL) {
/* A task is waiting for mutex. */
p_TCB = rt_get_first ((P_XCB)p_MCB);
rt_ret_val(p_TCB, 0U/*osOK*/);
rt_rmv_dly(p_TCB);
p_TCB->state = READY;
rt_put_prio (&os_rdy, p_TCB);
}
if ((os_rdy.p_lnk != NULL) && (os_rdy.p_lnk->prio > os_tsk.run->prio)) {
/* preempt running task */
rt_put_prio (&os_rdy, os_tsk.run);
os_tsk.run->state = READY;
rt_dispatch (NULL);
}
p_MCB->cb_type = 0U;
return (OS_R_OK);
}
#endif
/*--------------------------- rt_mut_release --------------------------------*/
OS_RESULT rt_mut_release (OS_ID mutex) {
/* Release a mutex object */
P_MUCB p_MCB = mutex;
P_TCB p_TCB;
P_MUCB p_mlnk;
U8 prio;
if ((p_MCB->level == 0U) || (p_MCB->owner != os_tsk.run)) {
/* Unbalanced mutex release or task is not the owner */
return (OS_R_NOK);
}
if (--p_MCB->level != 0U) {
return (OS_R_OK);
}
/* Remove mutex from task mutex owner list. */
p_mlnk = os_tsk.run->p_mlnk;
if (p_mlnk == p_MCB) {
os_tsk.run->p_mlnk = p_MCB->p_mlnk;
}
else {
while (p_mlnk) {
if (p_mlnk->p_mlnk == p_MCB) {
p_mlnk->p_mlnk = p_MCB->p_mlnk;
break;
}
p_mlnk = p_mlnk->p_mlnk;
}
}
/* Restore owner task's priority. */
prio = os_tsk.run->prio_base;
p_mlnk = os_tsk.run->p_mlnk;
while (p_mlnk) {
if ((p_mlnk->p_lnk != NULL) && (p_mlnk->p_lnk->prio > prio)) {
/* A task with higher priority is waiting for mutex. */
prio = p_mlnk->p_lnk->prio;
}
p_mlnk = p_mlnk->p_mlnk;
}
os_tsk.run->prio = prio;
if (p_MCB->p_lnk != NULL) {
/* A task is waiting for mutex. */
p_TCB = rt_get_first ((P_XCB)p_MCB);
#ifdef __CMSIS_RTOS
rt_ret_val(p_TCB, 0U/*osOK*/);
#else
rt_ret_val(p_TCB, OS_R_MUT);
#endif
rt_rmv_dly (p_TCB);
/* A waiting task becomes the owner of this mutex. */
p_MCB->level = 1U;
p_MCB->owner = p_TCB;
p_MCB->p_mlnk = p_TCB->p_mlnk;
p_TCB->p_mlnk = p_MCB;
/* Priority inversion, check which task continues. */
if (os_tsk.run->prio >= rt_rdy_prio()) {
rt_dispatch (p_TCB);
}
else {
/* Ready task has higher priority than running task. */
rt_put_prio (&os_rdy, os_tsk.run);
rt_put_prio (&os_rdy, p_TCB);
os_tsk.run->state = READY;
p_TCB->state = READY;
rt_dispatch (NULL);
}
}
else {
/* Check if own priority lowered by priority inversion. */
if (rt_rdy_prio() > os_tsk.run->prio) {
rt_put_prio (&os_rdy, os_tsk.run);
os_tsk.run->state = READY;
rt_dispatch (NULL);
}
}
return (OS_R_OK);
}
/*--------------------------- rt_mut_wait -----------------------------------*/
OS_RESULT rt_mut_wait (OS_ID mutex, U16 timeout) {
/* Wait for a mutex, continue when mutex is free. */
P_MUCB p_MCB = mutex;
if (p_MCB->level == 0U) {
p_MCB->owner = os_tsk.run;
p_MCB->p_mlnk = os_tsk.run->p_mlnk;
os_tsk.run->p_mlnk = p_MCB;
p_MCB->level = 1U;
return (OS_R_OK);
}
if (p_MCB->owner == os_tsk.run) {
/* OK, running task is the owner of this mutex. */
if (p_MCB->level == 0xFFFFU) {
return (OS_R_NOK);
}
p_MCB->level++;
return (OS_R_OK);
}
/* Mutex owned by another task, wait until released. */
if (timeout == 0U) {
return (OS_R_TMO);
}
/* Raise the owner task priority if lower than current priority. */
/* This priority inversion is called priority inheritance. */
if (p_MCB->owner->prio < os_tsk.run->prio) {
p_MCB->owner->prio = os_tsk.run->prio;
rt_resort_prio (p_MCB->owner);
}
if (p_MCB->p_lnk != NULL) {
rt_put_prio ((P_XCB)p_MCB, os_tsk.run);
}
else {
p_MCB->p_lnk = os_tsk.run;
os_tsk.run->p_lnk = NULL;
os_tsk.run->p_rlnk = (P_TCB)p_MCB;
}
rt_block(timeout, WAIT_MUT);
return (OS_R_TMO);
}
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_Mutex.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 2,047 |
```c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_TASK.C
* Purpose: Task functions and system start up.
* Rev.: V4.80
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#include "rt_TypeDef.h"
#include "RTX_Config.h"
#include "rt_System.h"
#include "rt_Task.h"
#include "rt_List.h"
#include "rt_MemBox.h"
#include "rt_Robin.h"
#include "rt_HAL_CM.h"
/*your_sha256_hash------------
* Global Variables
*your_sha256_hash-----------*/
/* Running and next task info. */
struct OS_TSK os_tsk;
/* Task Control Blocks of idle demon */
struct OS_TCB os_idle_TCB;
/*your_sha256_hash------------
* Local Functions
*your_sha256_hash-----------*/
static OS_TID rt_get_TID (void) {
U32 tid;
for (tid = 1U; tid <= os_maxtaskrun; tid++) {
if (os_active_TCB[tid-1U] == NULL) {
return ((OS_TID)tid);
}
}
return (0U);
}
/*--------------------------- rt_init_context -------------------------------*/
static void rt_init_context (P_TCB p_TCB, U8 priority, FUNCP task_body) {
/* Initialize general part of the Task Control Block. */
p_TCB->cb_type = TCB;
p_TCB->state = READY;
p_TCB->prio = priority;
p_TCB->prio_base = priority;
p_TCB->p_lnk = NULL;
p_TCB->p_rlnk = NULL;
p_TCB->p_dlnk = NULL;
p_TCB->p_blnk = NULL;
p_TCB->p_mlnk = NULL;
p_TCB->delta_time = 0U;
p_TCB->interval_time = 0U;
p_TCB->events = 0U;
p_TCB->waits = 0U;
p_TCB->stack_frame = 0U;
if (p_TCB->priv_stack == 0U) {
/* Allocate the memory space for the stack. */
p_TCB->stack = rt_alloc_box (mp_stk);
}
rt_init_stack (p_TCB, task_body);
}
/*--------------------------- rt_switch_req ---------------------------------*/
void rt_switch_req (P_TCB p_next) {
/* Switch to next task (identified by "p_next"). */
os_tsk.next = p_next;
p_next->state = RUNNING;
DBG_TASK_SWITCH(p_next->task_id);
}
/*--------------------------- rt_dispatch -----------------------------------*/
void rt_dispatch (P_TCB next_TCB) {
/* Dispatch next task if any identified or dispatch highest ready task */
/* "next_TCB" identifies a task to run or has value NULL (=no next task) */
if (next_TCB == NULL) {
/* Running task was blocked: continue with highest ready task */
next_TCB = rt_get_first (&os_rdy);
rt_switch_req (next_TCB);
}
else {
/* Check which task continues */
if (next_TCB->prio > os_tsk.run->prio) {
/* preempt running task */
rt_put_rdy_first (os_tsk.run);
os_tsk.run->state = READY;
rt_switch_req (next_TCB);
}
else {
/* put next task into ready list, no task switch takes place */
next_TCB->state = READY;
rt_put_prio (&os_rdy, next_TCB);
}
}
}
/*--------------------------- rt_block --------------------------------------*/
void rt_block (U16 timeout, U8 block_state) {
/* Block running task and choose next ready task. */
/* "timeout" sets a time-out value or is 0xffff (=no time-out). */
/* "block_state" defines the appropriate task state */
P_TCB next_TCB;
if (timeout) {
if (timeout < 0xFFFFU) {
rt_put_dly (os_tsk.run, timeout);
}
os_tsk.run->state = block_state;
next_TCB = rt_get_first (&os_rdy);
rt_switch_req (next_TCB);
}
}
/*--------------------------- rt_tsk_pass -----------------------------------*/
void rt_tsk_pass (void) {
/* Allow tasks of same priority level to run cooperatively.*/
P_TCB p_new;
p_new = rt_get_same_rdy_prio();
if (p_new != NULL) {
rt_put_prio ((P_XCB)&os_rdy, os_tsk.run);
os_tsk.run->state = READY;
rt_switch_req (p_new);
}
}
/*--------------------------- rt_tsk_self -----------------------------------*/
OS_TID rt_tsk_self (void) {
/* Return own task identifier value. */
if (os_tsk.run == NULL) {
return (0U);
}
return ((OS_TID)os_tsk.run->task_id);
}
/*--------------------------- rt_tsk_prio -----------------------------------*/
OS_RESULT rt_tsk_prio (OS_TID task_id, U8 new_prio) {
/* Change execution priority of a task to "new_prio". */
P_TCB p_task;
if (task_id == 0U) {
/* Change execution priority of calling task. */
os_tsk.run->prio = new_prio;
os_tsk.run->prio_base = new_prio;
run:if (rt_rdy_prio() > new_prio) {
rt_put_prio (&os_rdy, os_tsk.run);
os_tsk.run->state = READY;
rt_dispatch (NULL);
}
return (OS_R_OK);
}
/* Find the task in the "os_active_TCB" array. */
if ((task_id > os_maxtaskrun) || (os_active_TCB[task_id-1U] == NULL)) {
/* Task with "task_id" not found or not started. */
return (OS_R_NOK);
}
p_task = os_active_TCB[task_id-1U];
p_task->prio = new_prio;
p_task->prio_base = new_prio;
if (p_task == os_tsk.run) {
goto run;
}
rt_resort_prio (p_task);
if (p_task->state == READY) {
/* Task enqueued in a ready list. */
p_task = rt_get_first (&os_rdy);
rt_dispatch (p_task);
}
return (OS_R_OK);
}
/*--------------------------- rt_tsk_create ---------------------------------*/
OS_TID rt_tsk_create (FUNCP task, U32 prio_stksz, void *stk, void *argv) {
/* Start a new task declared with "task". */
P_TCB task_context;
U32 i;
/* Priority 0 is reserved for idle task! */
if ((prio_stksz & 0xFFU) == 0U) {
prio_stksz += 1U;
}
task_context = rt_alloc_box (mp_tcb);
if (task_context == NULL) {
return (0U);
}
/* If "size != 0" use a private user provided stack. */
task_context->stack = stk;
task_context->priv_stack = (U16)(prio_stksz >> 8);
/* Pass parameter 'argv' to 'rt_init_context' */
task_context->msg = argv;
/* For 'size == 0' system allocates the user stack from the memory pool. */
rt_init_context (task_context, (U8)(prio_stksz & 0xFFU), task);
/* Find a free entry in 'os_active_TCB' table. */
i = rt_get_TID ();
if (i == 0U) {
return (0U);
}
os_active_TCB[i-1U] = task_context;
task_context->task_id = (U8)i;
DBG_TASK_NOTIFY(task_context, __TRUE);
rt_dispatch (task_context);
return ((OS_TID)i);
}
/*--------------------------- rt_tsk_delete ---------------------------------*/
OS_RESULT rt_tsk_delete (OS_TID task_id) {
/* Terminate the task identified with "task_id". */
P_TCB task_context;
P_TCB p_TCB;
P_MUCB p_MCB, p_MCB0;
if ((task_id == 0U) || (task_id == os_tsk.run->task_id)) {
/* Terminate itself. */
os_tsk.run->state = INACTIVE;
os_tsk.run->tsk_stack = rt_get_PSP ();
rt_stk_check ();
p_MCB = os_tsk.run->p_mlnk;
while (p_MCB) {
/* Release mutexes owned by this task */
if (p_MCB->p_lnk) {
/* A task is waiting for mutex. */
p_TCB = rt_get_first ((P_XCB)p_MCB);
#ifdef __CMSIS_RTOS
rt_ret_val (p_TCB, 0U/*osOK*/);
#else
rt_ret_val (p_TCB, OS_R_MUT);
#endif
rt_rmv_dly (p_TCB);
p_TCB->state = READY;
rt_put_prio (&os_rdy, p_TCB);
/* A waiting task becomes the owner of this mutex. */
p_MCB0 = p_MCB->p_mlnk;
p_MCB->level = 1U;
p_MCB->owner = p_TCB;
p_MCB->p_mlnk = p_TCB->p_mlnk;
p_TCB->p_mlnk = p_MCB;
p_MCB = p_MCB0;
}
else {
p_MCB0 = p_MCB->p_mlnk;
p_MCB->level = 0U;
p_MCB->owner = NULL;
p_MCB->p_mlnk = NULL;
p_MCB = p_MCB0;
}
}
os_active_TCB[os_tsk.run->task_id-1U] = NULL;
rt_free_box (mp_stk, os_tsk.run->stack);
os_tsk.run->stack = NULL;
DBG_TASK_NOTIFY(os_tsk.run, __FALSE);
rt_free_box (mp_tcb, os_tsk.run);
os_tsk.run = NULL;
rt_dispatch (NULL);
/* The program should never come to this point. */
}
else {
/* Find the task in the "os_active_TCB" array. */
if ((task_id > os_maxtaskrun) || (os_active_TCB[task_id-1U] == NULL)) {
/* Task with "task_id" not found or not started. */
return (OS_R_NOK);
}
task_context = os_active_TCB[task_id-1U];
rt_rmv_list (task_context);
rt_rmv_dly (task_context);
p_MCB = task_context->p_mlnk;
while (p_MCB) {
/* Release mutexes owned by this task */
if (p_MCB->p_lnk) {
/* A task is waiting for mutex. */
p_TCB = rt_get_first ((P_XCB)p_MCB);
#ifdef __CMSIS_RTOS
rt_ret_val (p_TCB, 0U/*osOK*/);
#else
rt_ret_val (p_TCB, OS_R_MUT);
#endif
rt_rmv_dly (p_TCB);
p_TCB->state = READY;
rt_put_prio (&os_rdy, p_TCB);
/* A waiting task becomes the owner of this mutex. */
p_MCB0 = p_MCB->p_mlnk;
p_MCB->level = 1U;
p_MCB->owner = p_TCB;
p_MCB->p_mlnk = p_TCB->p_mlnk;
p_TCB->p_mlnk = p_MCB;
p_MCB = p_MCB0;
}
else {
p_MCB0 = p_MCB->p_mlnk;
p_MCB->level = 0U;
p_MCB->owner = NULL;
p_MCB->p_mlnk = NULL;
p_MCB = p_MCB0;
}
}
os_active_TCB[task_id-1U] = NULL;
rt_free_box (mp_stk, task_context->stack);
task_context->stack = NULL;
DBG_TASK_NOTIFY(task_context, __FALSE);
rt_free_box (mp_tcb, task_context);
if (rt_rdy_prio() > os_tsk.run->prio) {
/* Ready task has higher priority than running task. */
os_tsk.run->state = READY;
rt_put_prio (&os_rdy, os_tsk.run);
rt_dispatch (NULL);
}
}
return (OS_R_OK);
}
/*--------------------------- rt_sys_init -----------------------------------*/
#ifdef __CMSIS_RTOS
void rt_sys_init (void) {
#else
void rt_sys_init (FUNCP first_task, U32 prio_stksz, void *stk) {
#endif
/* Initialize system and start up task declared with "first_task". */
U32 i;
DBG_INIT();
/* Initialize dynamic memory and task TCB pointers to NULL. */
for (i = 0U; i < os_maxtaskrun; i++) {
os_active_TCB[i] = NULL;
}
rt_init_box (mp_tcb, (U32)mp_tcb_size, sizeof(struct OS_TCB));
rt_init_box (mp_stk, mp_stk_size, BOX_ALIGN_8 | (U16)(os_stackinfo));
rt_init_box ((U32 *)m_tmr, (U32)mp_tmr_size, sizeof(struct OS_TMR));
/* Set up TCB of idle demon */
os_idle_TCB.task_id = 255U;
os_idle_TCB.priv_stack = 0U;
rt_init_context (&os_idle_TCB, 0U, os_idle_demon);
/* Set up ready list: initially empty */
os_rdy.cb_type = HCB;
os_rdy.p_lnk = NULL;
/* Set up delay list: initially empty */
os_dly.cb_type = HCB;
os_dly.p_dlnk = NULL;
os_dly.p_blnk = NULL;
os_dly.delta_time = 0U;
/* Fix SP and system variables to assume idle task is running */
/* Transform main program into idle task by assuming idle TCB */
#ifndef __CMSIS_RTOS
rt_set_PSP (os_idle_TCB.tsk_stack+32U);
#endif
os_tsk.run = &os_idle_TCB;
os_tsk.run->state = RUNNING;
/* Initialize ps queue */
os_psq->first = 0U;
os_psq->last = 0U;
os_psq->size = os_fifo_size;
rt_init_robin ();
#ifndef __CMSIS_RTOS
/* Initialize SVC and PendSV */
rt_svc_init ();
/* Initialize and start system clock timer */
os_tick_irqn = os_tick_init ();
if (os_tick_irqn >= 0) {
OS_X_INIT((U32)os_tick_irqn);
}
/* Start up first user task before entering the endless loop */
rt_tsk_create (first_task, prio_stksz, stk, NULL);
#endif
}
/*--------------------------- rt_sys_start ----------------------------------*/
#ifdef __CMSIS_RTOS
void rt_sys_start (void) {
/* Start system */
/* Initialize SVC and PendSV */
rt_svc_init ();
/* Initialize and start system clock timer */
os_tick_irqn = os_tick_init ();
if (os_tick_irqn >= 0) {
OS_X_INIT((U32)os_tick_irqn);
}
}
#endif
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_Task.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 3,614 |
```objective-c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_EVENT.H
* Purpose: Implements waits and wake-ups for event flags
* Rev.: V4.70
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
/* Functions */
extern OS_RESULT rt_evt_wait (U16 wait_flags, U16 timeout, BOOL and_wait);
extern void rt_evt_set (U16 event_flags, OS_TID task_id);
extern void rt_evt_clr (U16 clear_flags, OS_TID task_id);
extern void isr_evt_set (U16 event_flags, OS_TID task_id);
extern U16 rt_evt_get (void);
extern void rt_evt_psh (P_TCB p_CB, U16 set_flags);
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_Event.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 241 |
```objective-c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_TIMER.H
* Purpose: User timer functions
* Rev.: V4.70
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
/* Variables */
extern struct OS_XTMR os_tmr;
/* Functions */
extern void rt_tmr_tick (void);
extern OS_ID rt_tmr_create (U16 tcnt, U16 info);
extern OS_ID rt_tmr_kill (OS_ID timer);
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_Timer.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 182 |
```objective-c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_ROBIN.H
* Purpose: Round Robin Task switching definitions
* Rev.: V4.70
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
/* Variables */
extern struct OS_ROBIN os_robin;
/* Functions */
extern void rt_init_robin (void);
extern void rt_chk_robin (void);
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_Robin.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 162 |
```c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_SYSTEM.C
* Purpose: System Task Manager
* Rev.: V4.82
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#include "rt_TypeDef.h"
#include "RTX_Config.h"
#include "rt_Task.h"
#include "rt_System.h"
#include "rt_Event.h"
#include "rt_List.h"
#include "rt_Mailbox.h"
#include "rt_Semaphore.h"
#include "rt_Time.h"
#include "rt_Timer.h"
#include "rt_Robin.h"
#include "rt_HAL_CM.h"
/*your_sha256_hash------------
* Global Variables
*your_sha256_hash-----------*/
S32 os_tick_irqn;
/*your_sha256_hash------------
* Local Variables
*your_sha256_hash-----------*/
static volatile BIT os_lock;
static volatile BIT os_psh_flag;
static U8 pend_flags;
/*your_sha256_hash------------
* Global Functions
*your_sha256_hash-----------*/
#define RL_RTX_VER 0x482
#if defined (__CC_ARM)
__asm void $$RTX$$version (void) {
/* Export a version number symbol for a version control. */
EXPORT __RL_RTX_VER
__RL_RTX_VER EQU RL_RTX_VER
}
#endif
/*--------------------------- rt_suspend ------------------------------------*/
extern U32 sysUserTimerWakeupTime(void);
U32 rt_suspend (void) {
/* Suspend OS scheduler */
U32 delta = 0xFFFFU;
#ifdef __CMSIS_RTOS
U32 sleep;
#endif
rt_tsk_lock();
if (os_dly.p_dlnk) {
delta = os_dly.delta_time;
}
#ifdef __CMSIS_RTOS
sleep = sysUserTimerWakeupTime();
if (sleep < delta) { delta = sleep; }
#else
if (os_tmr.next) {
if (os_tmr.tcnt < delta) delta = os_tmr.tcnt;
}
#endif
return (delta);
}
/*--------------------------- rt_resume -------------------------------------*/
extern void sysUserTimerUpdate (U32 sleep_time);
void rt_resume (U32 sleep_time) {
/* Resume OS scheduler after suspend */
P_TCB next;
U32 delta;
os_tsk.run->state = READY;
rt_put_rdy_first (os_tsk.run);
os_robin.task = NULL;
/* Update delays. */
if (os_dly.p_dlnk) {
delta = sleep_time;
if (delta >= os_dly.delta_time) {
delta -= os_dly.delta_time;
os_time += os_dly.delta_time;
os_dly.delta_time = 1U;
while (os_dly.p_dlnk) {
rt_dec_dly();
if (delta == 0U) { break; }
delta--;
os_time++;
}
} else {
os_time += delta;
os_dly.delta_time -= (U16)delta;
}
} else {
os_time += sleep_time;
}
/* Check the user timers. */
#ifdef __CMSIS_RTOS
sysUserTimerUpdate(sleep_time);
#else
if (os_tmr.next) {
delta = sleep_time;
if (delta >= os_tmr.tcnt) {
delta -= os_tmr.tcnt;
os_tmr.tcnt = 1U;
while (os_tmr.next) {
rt_tmr_tick();
if (delta == 0U) { break; }
delta--;
}
} else {
os_tmr.tcnt -= delta;
}
}
#endif
/* Switch back to highest ready task */
next = rt_get_first (&os_rdy);
rt_switch_req (next);
rt_tsk_unlock();
}
/*--------------------------- rt_tsk_lock -----------------------------------*/
void rt_tsk_lock (void) {
/* Prevent task switching by locking out scheduler */
if (os_tick_irqn < 0) {
OS_LOCK();
os_lock = __TRUE;
OS_UNPEND(pend_flags);
} else {
OS_X_LOCK((U32)os_tick_irqn);
os_lock = __TRUE;
OS_X_UNPEND(pend_flags);
}
}
/*--------------------------- rt_tsk_unlock ---------------------------------*/
void rt_tsk_unlock (void) {
/* Unlock scheduler and re-enable task switching */
if (os_tick_irqn < 0) {
OS_UNLOCK();
os_lock = __FALSE;
OS_PEND(pend_flags, os_psh_flag);
os_psh_flag = __FALSE;
} else {
OS_X_UNLOCK((U32)os_tick_irqn);
os_lock = __FALSE;
OS_X_PEND(pend_flags, os_psh_flag);
os_psh_flag = __FALSE;
}
}
/*--------------------------- rt_psh_req ------------------------------------*/
void rt_psh_req (void) {
/* Initiate a post service handling request if required. */
if (os_lock == __FALSE) {
OS_PEND_IRQ();
}
else {
os_psh_flag = __TRUE;
}
}
/*--------------------------- rt_pop_req ------------------------------------*/
void rt_pop_req (void) {
/* Process an ISR post service requests. */
struct OS_XCB *p_CB;
P_TCB next;
U32 idx;
os_tsk.run->state = READY;
rt_put_rdy_first (os_tsk.run);
idx = os_psq->last;
while (os_psq->count) {
p_CB = os_psq->q[idx].id;
if (p_CB->cb_type == TCB) {
/* Is of TCB type */
rt_evt_psh ((P_TCB)p_CB, (U16)os_psq->q[idx].arg);
}
else if (p_CB->cb_type == MCB) {
/* Is of MCB type */
rt_mbx_psh ((P_MCB)p_CB, (void *)os_psq->q[idx].arg);
}
else {
/* Must be of SCB type */
rt_sem_psh ((P_SCB)p_CB);
}
if (++idx == os_psq->size) { idx = 0U; }
rt_dec (&os_psq->count);
}
os_psq->last = (U8)idx;
next = rt_get_first (&os_rdy);
rt_switch_req (next);
}
/*--------------------------- os_tick_init ----------------------------------*/
__weak S32 os_tick_init (void) {
/* Initialize SysTick timer as system tick timer. */
rt_systick_init();
return (-1); /* Return IRQ number of SysTick timer */
}
/*--------------------------- os_tick_val -----------------------------------*/
__weak U32 os_tick_val (void) {
/* Get SysTick timer current value (0 .. OS_TRV). */
return rt_systick_val();
}
/*--------------------------- os_tick_ovf -----------------------------------*/
__weak U32 os_tick_ovf (void) {
/* Get SysTick timer overflow flag */
return rt_systick_ovf();
}
/*--------------------------- os_tick_irqack --------------------------------*/
__weak void os_tick_irqack (void) {
/* Acknowledge timer interrupt. */
}
/*--------------------------- rt_systick ------------------------------------*/
extern void sysTimerTick(void);
void rt_systick (void) {
/* Check for system clock update, suspend running task. */
P_TCB next;
os_tsk.run->state = READY;
rt_put_rdy_first (os_tsk.run);
/* Check Round Robin timeout. */
rt_chk_robin ();
/* Update delays. */
os_time++;
rt_dec_dly ();
/* Check the user timers. */
#ifdef __CMSIS_RTOS
sysTimerTick();
#else
rt_tmr_tick ();
#endif
/* Switch back to highest ready task */
next = rt_get_first (&os_rdy);
rt_switch_req (next);
}
/*--------------------------- rt_stk_check ----------------------------------*/
__weak void rt_stk_check (void) {
/* Check for stack overflow. */
if ((os_tsk.run->tsk_stack < (U32)os_tsk.run->stack) ||
(os_tsk.run->stack[0] != MAGIC_WORD)) {
os_error (OS_ERR_STK_OVF);
}
}
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_System.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 1,878 |
```objective-c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_MEMBOX.H
* Purpose: Interface functions for fixed memory block management system
* Rev.: V4.79
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
/* Functions */
#define rt_init_box _init_box
#define rt_calloc_box _calloc_box
extern U32 _init_box (void *box_mem, U32 box_size, U32 blk_size);
extern void *rt_alloc_box (void *box_mem);
extern void * _calloc_box (void *box_mem);
extern U32 rt_free_box (void *box_mem, void *box);
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_MemBox.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 221 |
```objective-c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_SEMAPHORE.H
* Purpose: Implements binary and counting semaphores
* Rev.: V4.70
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
/* Functions */
extern void rt_sem_init (OS_ID semaphore, U16 token_count);
extern OS_RESULT rt_sem_delete(OS_ID semaphore);
extern OS_RESULT rt_sem_send (OS_ID semaphore);
extern OS_RESULT rt_sem_wait (OS_ID semaphore, U16 timeout);
extern void isr_sem_send (OS_ID semaphore);
extern void rt_sem_psh (P_SCB p_CB);
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_Semaphore.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 215 |
```c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_ROBIN.C
* Purpose: Round Robin Task switching
* Rev.: V4.79
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#include "rt_TypeDef.h"
#include "RTX_Config.h"
#include "rt_List.h"
#include "rt_Task.h"
#include "rt_Time.h"
#include "rt_Robin.h"
#include "rt_HAL_CM.h"
/*your_sha256_hash------------
* Global Variables
*your_sha256_hash-----------*/
struct OS_ROBIN os_robin;
/*your_sha256_hash------------
* Global Functions
*your_sha256_hash-----------*/
/*--------------------------- rt_init_robin ---------------------------------*/
__weak void rt_init_robin (void) {
/* Initialize Round Robin variables. */
os_robin.task = NULL;
os_robin.tout = (U16)os_rrobin;
}
/*--------------------------- rt_chk_robin ----------------------------------*/
__weak void rt_chk_robin (void) {
/* Check if Round Robin timeout expired and switch to the next ready task.*/
P_TCB p_new;
if (os_robin.task != os_rdy.p_lnk) {
/* New task was suspended, reset Round Robin timeout. */
os_robin.task = os_rdy.p_lnk;
os_robin.time = (U16)os_time + os_robin.tout - 1U;
}
if (os_robin.time == (U16)os_time) {
/* Round Robin timeout has expired, swap Robin tasks. */
os_robin.task = NULL;
p_new = rt_get_first (&os_rdy);
rt_put_prio ((P_XCB)&os_rdy, p_new);
}
}
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_Robin.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 451 |
```objective-c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_TYPEDEF.H
* Purpose: Type Definitions
* Rev.: V4.79
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
/* Types */
typedef char S8;
typedef unsigned char U8;
typedef short S16;
typedef unsigned short U16;
typedef int S32;
typedef unsigned int U32;
typedef long long S64;
typedef unsigned long long U64;
typedef unsigned char BIT;
typedef unsigned int BOOL;
typedef void (*FUNCP)(void);
typedef U32 OS_TID;
typedef void *OS_ID;
typedef U32 OS_RESULT;
typedef struct OS_TCB {
/* General part: identical for all implementations. */
U8 cb_type; /* Control Block Type */
U8 state; /* Task state */
U8 prio; /* Execution priority */
U8 task_id; /* Task ID value for optimized TCB access */
struct OS_TCB *p_lnk; /* Link pointer for ready/sem. wait list */
struct OS_TCB *p_rlnk; /* Link pointer for sem./mbx lst backwards */
struct OS_TCB *p_dlnk; /* Link pointer for delay list */
struct OS_TCB *p_blnk; /* Link pointer for delay list backwards */
U16 delta_time; /* Time until time out */
U16 interval_time; /* Time interval for periodic waits */
U16 events; /* Event flags */
U16 waits; /* Wait flags */
void **msg; /* Direct message passing when task waits */
struct OS_MUCB *p_mlnk; /* Link pointer for mutex owner list */
U8 prio_base; /* Base priority */
/* Hardware dependant part: specific for CM processor */
U8 stack_frame; /* Stack frame: 0=Basic, 1=Extended, */
/* (2=VFP/D16 stacked, 4=NEON/D32 stacked) */
U16 priv_stack; /* Private stack size, 0= system assigned */
U32 tsk_stack; /* Current task Stack pointer (R13) */
U32 *stack; /* Pointer to Task Stack memory block */
/* Task entry point used for uVision debugger */
FUNCP ptask; /* Task entry address */
} *P_TCB;
#define TCB_STACKF 37 /* 'stack_frame' offset */
#define TCB_TSTACK 40 /* 'tsk_stack' offset */
typedef struct OS_PSFE { /* Post Service Fifo Entry */
void *id; /* Object Identification */
U32 arg; /* Object Argument */
} *P_PSFE;
typedef struct OS_PSQ { /* Post Service Queue */
U8 first; /* FIFO Head Index */
U8 last; /* FIFO Tail Index */
U8 count; /* Number of stored items in FIFO */
U8 size; /* FIFO Size */
struct OS_PSFE q[1]; /* FIFO Content */
} *P_PSQ;
typedef struct OS_TSK {
P_TCB run; /* Current running task */
P_TCB next; /* Scheduled task to run */
} *P_TSK;
typedef struct OS_ROBIN { /* Round Robin Control */
P_TCB task; /* Round Robin task */
U16 time; /* Round Robin switch time */
U16 tout; /* Round Robin timeout */
} *P_ROBIN;
typedef struct OS_XCB {
U8 cb_type; /* Control Block Type */
struct OS_TCB *p_lnk; /* Link pointer for ready/sem. wait list */
struct OS_TCB *p_rlnk; /* Link pointer for sem./mbx lst backwards */
struct OS_TCB *p_dlnk; /* Link pointer for delay list */
struct OS_TCB *p_blnk; /* Link pointer for delay list backwards */
U16 delta_time; /* Time until time out */
} *P_XCB;
typedef struct OS_MCB {
U8 cb_type; /* Control Block Type */
U8 state; /* State flag variable */
U8 isr_st; /* State flag variable for isr functions */
struct OS_TCB *p_lnk; /* Chain of tasks waiting for message */
U16 first; /* Index of the message list begin */
U16 last; /* Index of the message list end */
U16 count; /* Actual number of stored messages */
U16 size; /* Maximum number of stored messages */
void *msg[1]; /* FIFO for Message pointers 1st element */
} *P_MCB;
typedef struct OS_SCB {
U8 cb_type; /* Control Block Type */
U8 mask; /* Semaphore token mask */
U16 tokens; /* Semaphore tokens */
struct OS_TCB *p_lnk; /* Chain of tasks waiting for tokens */
} *P_SCB;
typedef struct OS_MUCB {
U8 cb_type; /* Control Block Type */
U16 level; /* Call nesting level */
struct OS_TCB *p_lnk; /* Chain of tasks waiting for mutex */
struct OS_TCB *owner; /* Mutex owner task */
struct OS_MUCB *p_mlnk; /* Chain of mutexes by owner task */
} *P_MUCB;
typedef struct OS_XTMR {
struct OS_TMR *next;
U16 tcnt;
} *P_XTMR;
typedef struct OS_TMR {
struct OS_TMR *next; /* Link pointer to Next timer */
U16 tcnt; /* Timer delay count */
U16 info; /* User defined call info */
} *P_TMR;
typedef struct OS_BM {
void *free; /* Pointer to first free memory block */
void *end; /* Pointer to memory block end */
U32 blk_size; /* Memory block size */
} *P_BM;
/* Definitions */
#define __TRUE 1U
#define __FALSE 0U
#define NULL ((void *) 0)
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_TypeDef.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 1,534 |
```objective-c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_MEMORY.H
* Purpose: Interface functions for Dynamic Memory Management System
* Rev.: V4.79
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
/* Types */
typedef struct mem { /* << Memory Pool management struct >> */
struct mem *next; /* Next Memory Block in the list */
U32 len; /* Length of data block */
} MEMP;
/* Functions */
extern U32 rt_init_mem (void *pool, U32 size);
extern void *rt_alloc_mem (void *pool, U32 size);
extern U32 rt_free_mem (void *pool, void *mem);
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_Memory.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 217 |
```objective-c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_MUTEX.H
* Purpose: Implements mutex synchronization objects
* Rev.: V4.70
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
/* Functions */
extern void rt_mut_init (OS_ID mutex);
extern OS_RESULT rt_mut_delete (OS_ID mutex);
extern OS_RESULT rt_mut_release (OS_ID mutex);
extern OS_RESULT rt_mut_wait (OS_ID mutex, U16 timeout);
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_Mutex.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 180 |
```c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_LIST.C
* Purpose: Functions for the management of different lists
* Rev.: V4.79
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#include "rt_TypeDef.h"
#include "RTX_Config.h"
#include "rt_System.h"
#include "rt_List.h"
#include "rt_Task.h"
#include "rt_Time.h"
#include "rt_HAL_CM.h"
/*your_sha256_hash------------
* Global Variables
*your_sha256_hash-----------*/
/* List head of chained ready tasks */
struct OS_XCB os_rdy;
/* List head of chained delay tasks */
struct OS_XCB os_dly;
/*your_sha256_hash------------
* Functions
*your_sha256_hash-----------*/
/*--------------------------- rt_put_prio -----------------------------------*/
void rt_put_prio (P_XCB p_CB, P_TCB p_task) {
/* Put task identified with "p_task" into list ordered by priority. */
/* "p_CB" points to head of list; list has always an element at end with */
/* a priority less than "p_task->prio". */
P_TCB p_CB2;
U32 prio;
BOOL sem_mbx = __FALSE;
if ((p_CB->cb_type == SCB) || (p_CB->cb_type == MCB) || (p_CB->cb_type == MUCB)) {
sem_mbx = __TRUE;
}
prio = p_task->prio;
p_CB2 = p_CB->p_lnk;
/* Search for an entry in the list */
while ((p_CB2 != NULL) && (prio <= p_CB2->prio)) {
p_CB = (P_XCB)p_CB2;
p_CB2 = p_CB2->p_lnk;
}
/* Entry found, insert the task into the list */
p_task->p_lnk = p_CB2;
p_CB->p_lnk = p_task;
if (sem_mbx) {
if (p_CB2 != NULL) {
p_CB2->p_rlnk = p_task;
}
p_task->p_rlnk = (P_TCB)p_CB;
}
else {
p_task->p_rlnk = NULL;
}
}
/*--------------------------- rt_get_first ----------------------------------*/
P_TCB rt_get_first (P_XCB p_CB) {
/* Get task at head of list: it is the task with highest priority. */
/* "p_CB" points to head of list. */
P_TCB p_first;
p_first = p_CB->p_lnk;
p_CB->p_lnk = p_first->p_lnk;
if ((p_CB->cb_type == SCB) || (p_CB->cb_type == MCB) || (p_CB->cb_type == MUCB)) {
if (p_first->p_lnk != NULL) {
p_first->p_lnk->p_rlnk = (P_TCB)p_CB;
p_first->p_lnk = NULL;
}
p_first->p_rlnk = NULL;
}
else {
p_first->p_lnk = NULL;
}
return (p_first);
}
/*--------------------------- rt_put_rdy_first ------------------------------*/
void rt_put_rdy_first (P_TCB p_task) {
/* Put task identified with "p_task" at the head of the ready list. The */
/* task must have at least a priority equal to highest priority in list. */
p_task->p_lnk = os_rdy.p_lnk;
p_task->p_rlnk = NULL;
os_rdy.p_lnk = p_task;
}
/*--------------------------- rt_get_same_rdy_prio --------------------------*/
P_TCB rt_get_same_rdy_prio (void) {
/* Remove a task of same priority from ready list if any exists. Other- */
/* wise return NULL. */
P_TCB p_first;
p_first = os_rdy.p_lnk;
if (p_first->prio == os_tsk.run->prio) {
os_rdy.p_lnk = os_rdy.p_lnk->p_lnk;
return (p_first);
}
return (NULL);
}
/*--------------------------- rt_resort_prio --------------------------------*/
void rt_resort_prio (P_TCB p_task) {
/* Re-sort ordered lists after the priority of 'p_task' has changed. */
P_TCB p_CB;
if (p_task->p_rlnk == NULL) {
if (p_task->state == READY) {
/* Task is chained into READY list. */
p_CB = (P_TCB)&os_rdy;
goto res;
}
}
else {
p_CB = p_task->p_rlnk;
while (p_CB->cb_type == TCB) {
/* Find a header of this task chain list. */
p_CB = p_CB->p_rlnk;
}
res:rt_rmv_list (p_task);
rt_put_prio ((P_XCB)p_CB, p_task);
}
}
/*--------------------------- rt_put_dly ------------------------------------*/
void rt_put_dly (P_TCB p_task, U16 delay) {
/* Put a task identified with "p_task" into chained delay wait list using */
/* a delay value of "delay". */
P_TCB p;
U32 delta,idelay = delay;
p = (P_TCB)&os_dly;
if (p->p_dlnk == NULL) {
/* Delay list empty */
delta = 0U;
goto last;
}
delta = os_dly.delta_time;
while (delta < idelay) {
if (p->p_dlnk == NULL) {
/* End of list found */
last: p_task->p_dlnk = NULL;
p->p_dlnk = p_task;
p_task->p_blnk = p;
p->delta_time = (U16)(idelay - delta);
p_task->delta_time = 0U;
return;
}
p = p->p_dlnk;
delta += p->delta_time;
}
/* Right place found */
p_task->p_dlnk = p->p_dlnk;
p->p_dlnk = p_task;
p_task->p_blnk = p;
if (p_task->p_dlnk != NULL) {
p_task->p_dlnk->p_blnk = p_task;
}
p_task->delta_time = (U16)(delta - idelay);
p->delta_time -= p_task->delta_time;
}
/*--------------------------- rt_dec_dly ------------------------------------*/
void rt_dec_dly (void) {
/* Decrement delta time of list head: remove tasks having a value of zero.*/
P_TCB p_rdy;
if (os_dly.p_dlnk == NULL) {
return;
}
os_dly.delta_time--;
while ((os_dly.delta_time == 0U) && (os_dly.p_dlnk != NULL)) {
p_rdy = os_dly.p_dlnk;
if (p_rdy->p_rlnk != NULL) {
/* Task is really enqueued, remove task from semaphore/mailbox */
/* timeout waiting list. */
p_rdy->p_rlnk->p_lnk = p_rdy->p_lnk;
if (p_rdy->p_lnk != NULL) {
p_rdy->p_lnk->p_rlnk = p_rdy->p_rlnk;
p_rdy->p_lnk = NULL;
}
p_rdy->p_rlnk = NULL;
}
rt_put_prio (&os_rdy, p_rdy);
os_dly.delta_time = p_rdy->delta_time;
if (p_rdy->state == WAIT_ITV) {
/* Calculate the next time for interval wait. */
p_rdy->delta_time = p_rdy->interval_time + (U16)os_time;
}
p_rdy->state = READY;
os_dly.p_dlnk = p_rdy->p_dlnk;
if (p_rdy->p_dlnk != NULL) {
p_rdy->p_dlnk->p_blnk = (P_TCB)&os_dly;
p_rdy->p_dlnk = NULL;
}
p_rdy->p_blnk = NULL;
}
}
/*--------------------------- rt_rmv_list -----------------------------------*/
void rt_rmv_list (P_TCB p_task) {
/* Remove task identified with "p_task" from ready, semaphore or mailbox */
/* waiting list if enqueued. */
P_TCB p_b;
if (p_task->p_rlnk != NULL) {
/* A task is enqueued in semaphore / mailbox waiting list. */
p_task->p_rlnk->p_lnk = p_task->p_lnk;
if (p_task->p_lnk != NULL) {
p_task->p_lnk->p_rlnk = p_task->p_rlnk;
}
return;
}
p_b = (P_TCB)&os_rdy;
while (p_b != NULL) {
/* Search the ready list for task "p_task" */
if (p_b->p_lnk == p_task) {
p_b->p_lnk = p_task->p_lnk;
return;
}
p_b = p_b->p_lnk;
}
}
/*--------------------------- rt_rmv_dly ------------------------------------*/
void rt_rmv_dly (P_TCB p_task) {
/* Remove task identified with "p_task" from delay list if enqueued. */
P_TCB p_b;
p_b = p_task->p_blnk;
if (p_b != NULL) {
/* Task is really enqueued */
p_b->p_dlnk = p_task->p_dlnk;
if (p_task->p_dlnk != NULL) {
/* 'p_task' is in the middle of list */
p_b->delta_time += p_task->delta_time;
p_task->p_dlnk->p_blnk = p_b;
p_task->p_dlnk = NULL;
}
else {
/* 'p_task' is at the end of list */
p_b->delta_time = 0U;
}
p_task->p_blnk = NULL;
}
}
/*--------------------------- rt_psq_enq ------------------------------------*/
void rt_psq_enq (OS_ID entry, U32 arg) {
/* Insert post service request "entry" into ps-queue. */
U32 idx;
idx = rt_inc_qi (os_psq->size, &os_psq->count, &os_psq->first);
if (idx < os_psq->size) {
os_psq->q[idx].id = entry;
os_psq->q[idx].arg = arg;
}
else {
os_error (OS_ERR_FIFO_OVF);
}
}
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_List.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 2,514 |
```c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: HAL_CM.C
* Purpose: Hardware Abstraction Layer for Cortex-M
* Rev.: V4.79
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#include "rt_TypeDef.h"
#include "RTX_Config.h"
#include "rt_HAL_CM.h"
/*your_sha256_hash------------
* Global Variables
*your_sha256_hash-----------*/
#ifdef DBG_MSG
BIT dbg_msg;
#endif
/*your_sha256_hash------------
* Functions
*your_sha256_hash-----------*/
/*--------------------------- rt_init_stack ---------------------------------*/
void rt_init_stack (P_TCB p_TCB, FUNCP task_body) {
/* Prepare TCB and saved context for a first time start of a task. */
U32 *stk,i,size;
/* Prepare a complete interrupt frame for first task start */
size = p_TCB->priv_stack >> 2;
if (size == 0U) {
size = (U16)os_stackinfo >> 2;
}
/* Write to the top of stack. */
stk = &p_TCB->stack[size];
/* Auto correct to 8-byte ARM stack alignment. */
if ((U32)stk & 0x04U) {
stk--;
}
stk -= 16;
/* Default xPSR and initial PC */
stk[15] = INITIAL_xPSR;
stk[14] = (U32)task_body;
/* Clear R4-R11,R0-R3,R12,LR registers. */
for (i = 0U; i < 14U; i++) {
stk[i] = 0U;
}
/* Assign a void pointer to R0. */
stk[8] = (U32)p_TCB->msg;
/* Initial Task stack pointer. */
p_TCB->tsk_stack = (U32)stk;
/* Task entry point. */
p_TCB->ptask = task_body;
/* Initialize stack with magic pattern. */
if (os_stackinfo & 0x10000000U) {
if (size > (16U+1U)) {
for (i = ((size - 16U)/2U) - 1U; i; i--) {
stk -= 2U;
stk[1] = MAGIC_PATTERN;
stk[0] = MAGIC_PATTERN;
}
if (--stk > p_TCB->stack) {
*stk = MAGIC_PATTERN;
}
}
}
/* Set a magic word for checking of stack overflow. */
p_TCB->stack[0] = MAGIC_WORD;
}
/*--------------------------- rt_ret_val ----------------------------------*/
static __inline U32 *rt_ret_regs (P_TCB p_TCB) {
/* Get pointer to task return value registers (R0..R3) in Stack */
#if defined(__TARGET_FPU_VFP)
if (p_TCB->stack_frame) {
/* Extended Stack Frame: R4-R11,S16-S31,R0-R3,R12,LR,PC,xPSR,S0-S15,FPSCR */
return (U32 *)(p_TCB->tsk_stack + (8U*4U) + (16U*4U));
} else {
/* Basic Stack Frame: R4-R11,R0-R3,R12,LR,PC,xPSR */
return (U32 *)(p_TCB->tsk_stack + (8U*4U));
}
#else
/* Stack Frame: R4-R11,R0-R3,R12,LR,PC,xPSR */
return (U32 *)(p_TCB->tsk_stack + (8U*4U));
#endif
}
void rt_ret_val (P_TCB p_TCB, U32 v0) {
U32 *ret;
ret = rt_ret_regs(p_TCB);
ret[0] = v0;
}
void rt_ret_val2(P_TCB p_TCB, U32 v0, U32 v1) {
U32 *ret;
ret = rt_ret_regs(p_TCB);
ret[0] = v0;
ret[1] = v1;
}
/*--------------------------- dbg_init --------------------------------------*/
#ifdef DBG_MSG
void dbg_init (void) {
if (((DEMCR & DEMCR_TRCENA) != 0U) &&
((ITM_CONTROL & ITM_ITMENA) != 0U) &&
((ITM_ENABLE & (1UL << 31)) != 0U)) {
dbg_msg = __TRUE;
}
}
#endif
/*--------------------------- dbg_task_notify -------------------------------*/
#ifdef DBG_MSG
void dbg_task_notify (P_TCB p_tcb, BOOL create) {
while (ITM_PORT31_U32 == 0U);
ITM_PORT31_U32 = (U32)p_tcb->ptask;
while (ITM_PORT31_U32 == 0U);
ITM_PORT31_U16 = (U16)((create << 8) | p_tcb->task_id);
}
#endif
/*--------------------------- dbg_task_switch -------------------------------*/
#ifdef DBG_MSG
void dbg_task_switch (U32 task_id) {
while (ITM_PORT31_U32 == 0U);
ITM_PORT31_U8 = (U8)task_id;
}
#endif
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/HAL_CM.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 1,224 |
```objective-c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_MAILBOX.H
* Purpose: Implements waits and wake-ups for mailbox messages
* Rev.: V4.70
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
/* Functions */
extern void rt_mbx_init (OS_ID mailbox, U16 mbx_size);
extern OS_RESULT rt_mbx_send (OS_ID mailbox, void *p_msg, U16 timeout);
extern OS_RESULT rt_mbx_wait (OS_ID mailbox, void **message, U16 timeout);
extern OS_RESULT rt_mbx_check (OS_ID mailbox);
extern void isr_mbx_send (OS_ID mailbox, void *p_msg);
extern OS_RESULT isr_mbx_receive (OS_ID mailbox, void **message);
extern void rt_mbx_psh (P_MCB p_CB, void *p_msg);
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_Mailbox.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 264 |
```c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_TIME.C
* Purpose: Delay and interval wait functions
* Rev.: V4.79
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#include "rt_TypeDef.h"
#include "RTX_Config.h"
#include "rt_Task.h"
#include "rt_Time.h"
/*your_sha256_hash------------
* Global Variables
*your_sha256_hash-----------*/
/* Free running system tick counter */
U32 os_time;
/*your_sha256_hash------------
* Functions
*your_sha256_hash-----------*/
/*--------------------------- rt_time_get -----------------------------------*/
U32 rt_time_get (void) {
/* Get system time tick */
return (os_time);
}
/*--------------------------- rt_dly_wait -----------------------------------*/
void rt_dly_wait (U16 delay_time) {
/* Delay task by "delay_time" */
rt_block (delay_time, WAIT_DLY);
}
/*--------------------------- rt_itv_set ------------------------------------*/
void rt_itv_set (U16 interval_time) {
/* Set interval length and define start of first interval */
os_tsk.run->interval_time = interval_time;
os_tsk.run->delta_time = interval_time + (U16)os_time;
}
/*--------------------------- rt_itv_wait -----------------------------------*/
void rt_itv_wait (void) {
/* Wait for interval end and define start of next one */
U16 delta;
delta = os_tsk.run->delta_time - (U16)os_time;
os_tsk.run->delta_time += os_tsk.run->interval_time;
if ((delta & 0x8000U) == 0U) {
rt_block (delta, WAIT_ITV);
}
}
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_Time.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 444 |
```objective-c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_LIST.H
* Purpose: Functions for the management of different lists
* Rev.: V4.79
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
/* Definitions */
/* Values for 'cb_type' */
#define TCB 0U
#define MCB 1U
#define SCB 2U
#define MUCB 3U
#define HCB 4U
/* Variables */
extern struct OS_XCB os_rdy;
extern struct OS_XCB os_dly;
/* Functions */
extern void rt_put_prio (P_XCB p_CB, P_TCB p_task);
extern P_TCB rt_get_first (P_XCB p_CB);
extern void rt_put_rdy_first (P_TCB p_task);
extern P_TCB rt_get_same_rdy_prio (void);
extern void rt_resort_prio (P_TCB p_task);
extern void rt_put_dly (P_TCB p_task, U16 delay);
extern void rt_dec_dly (void);
extern void rt_rmv_list (P_TCB p_task);
extern void rt_rmv_dly (P_TCB p_task);
extern void rt_psq_enq (OS_ID entry, U32 arg);
/* This is a fast macro generating in-line code */
#define rt_rdy_prio(void) (os_rdy.p_lnk->prio)
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_List.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 395 |
```c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_EVENT.C
* Purpose: Implements waits and wake-ups for event flags
* Rev.: V4.79
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#include "rt_TypeDef.h"
#include "RTX_Config.h"
#include "rt_System.h"
#include "rt_Event.h"
#include "rt_List.h"
#include "rt_Task.h"
#include "rt_HAL_CM.h"
/*your_sha256_hash------------
* Functions
*your_sha256_hash-----------*/
/*--------------------------- rt_evt_wait -----------------------------------*/
OS_RESULT rt_evt_wait (U16 wait_flags, U16 timeout, BOOL and_wait) {
/* Wait for one or more event flags with optional time-out. */
/* "wait_flags" identifies the flags to wait for. */
/* "timeout" is the time-out limit in system ticks (0xffff if no time-out) */
/* "and_wait" specifies the AND-ing of "wait_flags" as condition to be met */
/* to complete the wait. (OR-ing if set to 0). */
U32 block_state;
if (and_wait) {
/* Check for AND-connected events */
if ((os_tsk.run->events & wait_flags) == wait_flags) {
os_tsk.run->events &= ~wait_flags;
return (OS_R_EVT);
}
block_state = WAIT_AND;
}
else {
/* Check for OR-connected events */
if (os_tsk.run->events & wait_flags) {
os_tsk.run->waits = os_tsk.run->events & wait_flags;
os_tsk.run->events &= ~wait_flags;
return (OS_R_EVT);
}
block_state = WAIT_OR;
}
/* Task has to wait */
os_tsk.run->waits = wait_flags;
rt_block (timeout, (U8)block_state);
return (OS_R_TMO);
}
/*--------------------------- rt_evt_set ------------------------------------*/
void rt_evt_set (U16 event_flags, OS_TID task_id) {
/* Set one or more event flags of a selectable task. */
P_TCB p_tcb;
p_tcb = os_active_TCB[task_id-1U];
if (p_tcb == NULL) {
return;
}
p_tcb->events |= event_flags;
event_flags = p_tcb->waits;
/* If the task is not waiting for an event, it should not be put */
/* to ready state. */
if (p_tcb->state == WAIT_AND) {
/* Check for AND-connected events */
if ((p_tcb->events & event_flags) == event_flags) {
goto wkup;
}
}
if (p_tcb->state == WAIT_OR) {
/* Check for OR-connected events */
if (p_tcb->events & event_flags) {
p_tcb->waits &= p_tcb->events;
wkup: p_tcb->events &= ~event_flags;
rt_rmv_dly (p_tcb);
p_tcb->state = READY;
#ifdef __CMSIS_RTOS
rt_ret_val2(p_tcb, 0x08U/*osEventSignal*/, p_tcb->waits);
#else
rt_ret_val (p_tcb, OS_R_EVT);
#endif
rt_dispatch (p_tcb);
}
}
}
/*--------------------------- rt_evt_clr ------------------------------------*/
void rt_evt_clr (U16 clear_flags, OS_TID task_id) {
/* Clear one or more event flags (identified by "clear_flags") of a */
/* selectable task (identified by "task"). */
P_TCB task = os_active_TCB[task_id-1U];
if (task == NULL) {
return;
}
task->events &= ~clear_flags;
}
/*--------------------------- isr_evt_set -----------------------------------*/
void isr_evt_set (U16 event_flags, OS_TID task_id) {
/* Same function as "os_evt_set", but to be called by ISRs. */
P_TCB p_tcb = os_active_TCB[task_id-1U];
if (p_tcb == NULL) {
return;
}
rt_psq_enq (p_tcb, event_flags);
rt_psh_req ();
}
/*--------------------------- rt_evt_get ------------------------------------*/
U16 rt_evt_get (void) {
/* Get events of a running task after waiting for OR connected events. */
return (os_tsk.run->waits);
}
/*--------------------------- rt_evt_psh ------------------------------------*/
void rt_evt_psh (P_TCB p_CB, U16 set_flags) {
/* Check if task has to be waken up */
U16 event_flags;
p_CB->events |= set_flags;
event_flags = p_CB->waits;
if (p_CB->state == WAIT_AND) {
/* Check for AND-connected events */
if ((p_CB->events & event_flags) == event_flags) {
goto rdy;
}
}
if (p_CB->state == WAIT_OR) {
/* Check for OR-connected events */
if (p_CB->events & event_flags) {
p_CB->waits &= p_CB->events;
rdy: p_CB->events &= ~event_flags;
rt_rmv_dly (p_CB);
p_CB->state = READY;
#ifdef __CMSIS_RTOS
rt_ret_val2(p_CB, 0x08U/*osEventSignal*/, p_CB->waits);
#else
rt_ret_val (p_CB, OS_R_EVT);
#endif
rt_put_prio (&os_rdy, p_CB);
}
}
}
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_Event.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 1,288 |
```objective-c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_TASK.H
* Purpose: Task functions and system start up.
* Rev.: V4.79
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
/* Definitions */
/* Values for 'state' */
#define INACTIVE 0U
#define READY 1U
#define RUNNING 2U
#define WAIT_DLY 3U
#define WAIT_ITV 4U
#define WAIT_OR 5U
#define WAIT_AND 6U
#define WAIT_SEM 7U
#define WAIT_MBX 8U
#define WAIT_MUT 9U
/* Return codes */
#define OS_R_TMO 0x01U
#define OS_R_EVT 0x02U
#define OS_R_SEM 0x03U
#define OS_R_MBX 0x04U
#define OS_R_MUT 0x05U
#define OS_R_OK 0x00U
#define OS_R_NOK 0xFFU
/* Variables */
extern struct OS_TSK os_tsk;
extern struct OS_TCB os_idle_TCB;
/* Functions */
extern void rt_switch_req (P_TCB p_next);
extern void rt_dispatch (P_TCB next_TCB);
extern void rt_block (U16 timeout, U8 block_state);
extern void rt_tsk_pass (void);
extern OS_TID rt_tsk_self (void);
extern OS_RESULT rt_tsk_prio (OS_TID task_id, U8 new_prio);
extern OS_TID rt_tsk_create (FUNCP task, U32 prio_stksz, void *stk, void *argv);
extern OS_RESULT rt_tsk_delete (OS_TID task_id);
#ifdef __CMSIS_RTOS
extern void rt_sys_init (void);
extern void rt_sys_start (void);
#else
extern void rt_sys_init (FUNCP first_task, U32 prio_stksz, void *stk);
#endif
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_Task.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 517 |
```objective-c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RTX_CONFIG.H
* Purpose: Exported functions of RTX_Config.c
* Rev.: V4.81
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#include <stdint.h>
/* Error Codes */
#define OS_ERR_STK_OVF 1U
#define OS_ERR_FIFO_OVF 2U
#define OS_ERR_MBX_OVF 3U
#define OS_ERR_TIMER_OVF 4U
/* Definitions */
#define BOX_ALIGN_8 0x80000000U
#define _declare_box(pool,size,cnt) U32 pool[(((size)+3)/4)*(cnt) + 3]
#define _declare_box8(pool,size,cnt) U64 pool[(((size)+7)/8)*(cnt) + 2]
#define _init_box8(pool,size,bsize) _init_box (pool,size,(bsize) | BOX_ALIGN_8)
/* Variables */
extern U32 mp_tcb[];
extern U64 mp_stk[];
extern U32 os_fifo[];
extern void *os_active_TCB[];
/* Constants */
extern U16 const os_maxtaskrun;
extern U32 const os_trv;
extern U8 const os_flags;
extern U32 const os_stackinfo;
extern U32 const os_rrobin;
extern U32 const os_clockrate;
extern U32 const os_timernum;
extern U16 const mp_tcb_size;
extern U32 const mp_stk_size;
extern U32 const *m_tmr;
extern U16 const mp_tmr_size;
extern U8 const os_fifo_size;
/* Functions */
extern void os_idle_demon (void);
extern S32 os_tick_init (void);
extern U32 os_tick_val (void);
extern U32 os_tick_ovf (void);
extern void os_tick_irqack (void);
extern void os_tmr_call (U16 info);
extern void os_error (uint32_t err_code);
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/RTX_Config.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 503 |
```objective-c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_TIME.H
* Purpose: Delay and interval wait functions definitions
* Rev.: V4.70
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
/* Variables */
extern U32 os_time;
/* Functions */
extern U32 rt_time_get (void);
extern void rt_dly_wait (U16 delay_time);
extern void rt_itv_set (U16 interval_time);
extern void rt_itv_wait (void);
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_Time.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 184 |
```objective-c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_SYSTEM.H
* Purpose: System Task Manager definitions
* Rev.: V4.79
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
/* Variables */
#define os_psq ((P_PSQ)&os_fifo)
extern S32 os_tick_irqn;
/* Functions */
extern U32 rt_suspend (void);
extern void rt_resume (U32 sleep_time);
extern void rt_tsk_lock (void);
extern void rt_tsk_unlock (void);
extern void rt_psh_req (void);
extern void rt_pop_req (void);
extern void rt_systick (void);
extern void rt_stk_check (void);
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_System.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 231 |
```c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_MAILBOX.C
* Purpose: Implements waits and wake-ups for mailbox messages
* Rev.: V4.81
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#include "rt_TypeDef.h"
#include "RTX_Config.h"
#include "rt_System.h"
#include "rt_List.h"
#include "rt_Mailbox.h"
#include "rt_MemBox.h"
#include "rt_Task.h"
#include "rt_HAL_CM.h"
/*your_sha256_hash------------
* Functions
*your_sha256_hash-----------*/
/*--------------------------- rt_mbx_init -----------------------------------*/
void rt_mbx_init (OS_ID mailbox, U16 mbx_size) {
/* Initialize a mailbox */
P_MCB p_MCB = mailbox;
p_MCB->cb_type = MCB;
p_MCB->state = 0U;
p_MCB->isr_st = 0U;
p_MCB->p_lnk = NULL;
p_MCB->first = 0U;
p_MCB->last = 0U;
p_MCB->count = 0U;
p_MCB->size = (U16)((mbx_size - (sizeof(struct OS_MCB) - (sizeof(void *))))
/ sizeof(void *));
}
/*--------------------------- rt_mbx_send -----------------------------------*/
OS_RESULT rt_mbx_send (OS_ID mailbox, void *p_msg, U16 timeout) {
/* Send message to a mailbox */
P_MCB p_MCB = mailbox;
P_TCB p_TCB;
if ((p_MCB->p_lnk != NULL) && (p_MCB->state == 1U)) {
/* A task is waiting for message */
p_TCB = rt_get_first ((P_XCB)p_MCB);
#ifdef __CMSIS_RTOS
rt_ret_val2(p_TCB, 0x10U/*osEventMessage*/, (U32)p_msg);
#else
*p_TCB->msg = p_msg;
rt_ret_val (p_TCB, OS_R_MBX);
#endif
rt_rmv_dly (p_TCB);
rt_dispatch (p_TCB);
}
else {
/* Store message in mailbox queue */
if (p_MCB->count == p_MCB->size) {
/* No free message entry, wait for one. If message queue is full, */
/* then no task is waiting for message. The 'p_MCB->p_lnk' list */
/* pointer can now be reused for send message waits task list. */
if (timeout == 0U) {
return (OS_R_TMO);
}
if (p_MCB->p_lnk != NULL) {
rt_put_prio ((P_XCB)p_MCB, os_tsk.run);
}
else {
p_MCB->p_lnk = os_tsk.run;
os_tsk.run->p_lnk = NULL;
os_tsk.run->p_rlnk = (P_TCB)p_MCB;
/* Task is waiting to send a message */
p_MCB->state = 2U;
}
os_tsk.run->msg = p_msg;
rt_block (timeout, WAIT_MBX);
return (OS_R_TMO);
}
/* Yes, there is a free entry in a mailbox. */
p_MCB->msg[p_MCB->first] = p_msg;
rt_inc (&p_MCB->count);
if (++p_MCB->first == p_MCB->size) {
p_MCB->first = 0U;
}
}
return (OS_R_OK);
}
/*--------------------------- rt_mbx_wait -----------------------------------*/
OS_RESULT rt_mbx_wait (OS_ID mailbox, void **message, U16 timeout) {
/* Receive a message; possibly wait for it */
P_MCB p_MCB = mailbox;
P_TCB p_TCB;
/* If a message is available in the fifo buffer */
/* remove it from the fifo buffer and return. */
if (p_MCB->count) {
*message = p_MCB->msg[p_MCB->last];
if (++p_MCB->last == p_MCB->size) {
p_MCB->last = 0U;
}
if ((p_MCB->p_lnk != NULL) && (p_MCB->state == 2U)) {
/* A task is waiting to send message */
p_TCB = rt_get_first ((P_XCB)p_MCB);
#ifdef __CMSIS_RTOS
rt_ret_val(p_TCB, 0U/*osOK*/);
#else
rt_ret_val(p_TCB, OS_R_OK);
#endif
p_MCB->msg[p_MCB->first] = p_TCB->msg;
if (++p_MCB->first == p_MCB->size) {
p_MCB->first = 0U;
}
rt_rmv_dly (p_TCB);
rt_dispatch (p_TCB);
}
else {
rt_dec (&p_MCB->count);
}
return (OS_R_OK);
}
/* No message available: wait for one */
if (timeout == 0U) {
return (OS_R_TMO);
}
if (p_MCB->p_lnk != NULL) {
rt_put_prio ((P_XCB)p_MCB, os_tsk.run);
}
else {
p_MCB->p_lnk = os_tsk.run;
os_tsk.run->p_lnk = NULL;
os_tsk.run->p_rlnk = (P_TCB)p_MCB;
/* Task is waiting to receive a message */
p_MCB->state = 1U;
}
rt_block(timeout, WAIT_MBX);
#ifndef __CMSIS_RTOS
os_tsk.run->msg = message;
#endif
return (OS_R_TMO);
}
/*--------------------------- rt_mbx_check ----------------------------------*/
OS_RESULT rt_mbx_check (OS_ID mailbox) {
/* Check for free space in a mailbox. Returns the number of messages */
/* that can be stored to a mailbox. It returns 0 when mailbox is full. */
P_MCB p_MCB = mailbox;
return ((U32)(p_MCB->size - p_MCB->count));
}
/*--------------------------- isr_mbx_send ----------------------------------*/
void isr_mbx_send (OS_ID mailbox, void *p_msg) {
/* Same function as "os_mbx_send", but to be called by ISRs. */
P_MCB p_MCB = mailbox;
rt_psq_enq (p_MCB, (U32)p_msg);
rt_psh_req ();
}
/*--------------------------- isr_mbx_receive -------------------------------*/
OS_RESULT isr_mbx_receive (OS_ID mailbox, void **message) {
/* Receive a message in the interrupt function. The interrupt function */
/* should not wait for a message since this would block the rtx os. */
P_MCB p_MCB = mailbox;
if (p_MCB->count) {
/* A message is available in the fifo buffer. */
*message = p_MCB->msg[p_MCB->last];
if ((p_MCB->p_lnk != NULL) && (p_MCB->state == 2U)) {
/* A task is locked waiting to send message */
rt_psq_enq (p_MCB, 0U);
rt_psh_req ();
}
rt_dec (&p_MCB->count);
if (++p_MCB->last == p_MCB->size) {
p_MCB->last = 0U;
}
return (OS_R_MBX);
}
return (OS_R_OK);
}
/*--------------------------- rt_mbx_psh ------------------------------------*/
void rt_mbx_psh (P_MCB p_CB, void *p_msg) {
/* Store the message to the mailbox queue or pass it to task directly. */
P_TCB p_TCB;
void *mem;
if (p_CB->p_lnk != NULL) switch (p_CB->state) {
#ifdef __CMSIS_RTOS
case 3:
/* Task is waiting to allocate memory, remove it from the waiting list */
mem = rt_alloc_box(p_msg);
if (mem == NULL) { break; }
p_TCB = rt_get_first ((P_XCB)p_CB);
rt_ret_val(p_TCB, (U32)mem);
p_TCB->state = READY;
rt_rmv_dly (p_TCB);
rt_put_prio (&os_rdy, p_TCB);
break;
#endif
case 2:
/* Task is waiting to send a message, remove it from the waiting list */
p_TCB = rt_get_first ((P_XCB)p_CB);
#ifdef __CMSIS_RTOS
rt_ret_val(p_TCB, 0U/*osOK*/);
#else
rt_ret_val(p_TCB, OS_R_OK);
#endif
p_CB->msg[p_CB->first] = p_TCB->msg;
rt_inc (&p_CB->count);
if (++p_CB->first == p_CB->size) {
p_CB->first = 0U;
}
p_TCB->state = READY;
rt_rmv_dly (p_TCB);
rt_put_prio (&os_rdy, p_TCB);
break;
case 1:
/* Task is waiting for a message, pass the message to the task directly */
p_TCB = rt_get_first ((P_XCB)p_CB);
#ifdef __CMSIS_RTOS
rt_ret_val2(p_TCB, 0x10U/*osEventMessage*/, (U32)p_msg);
#else
*p_TCB->msg = p_msg;
rt_ret_val (p_TCB, OS_R_MBX);
#endif
p_TCB->state = READY;
rt_rmv_dly (p_TCB);
rt_put_prio (&os_rdy, p_TCB);
break;
default:
break;
} else {
/* No task is waiting for a message, store it to the mailbox queue */
if (p_CB->count < p_CB->size) {
p_CB->msg[p_CB->first] = p_msg;
rt_inc (&p_CB->count);
if (++p_CB->first == p_CB->size) {
p_CB->first = 0U;
}
}
else {
os_error (OS_ERR_MBX_OVF);
}
}
}
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_Mailbox.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 2,370 |
```c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RT_MEMORY.C
* Purpose: Interface functions for Dynamic Memory Management System
* Rev.: V4.79
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#include "rt_TypeDef.h"
#include "rt_Memory.h"
/* Functions */
// Initialize Dynamic Memory pool
// Parameters:
// pool: Pointer to memory pool
// size: Size of memory pool in bytes
// Return: 0 - OK, 1 - Error
U32 rt_init_mem (void *pool, U32 size) {
MEMP *ptr;
if ((pool == NULL) || (size < sizeof(MEMP))) { return (1U); }
ptr = (MEMP *)pool;
ptr->next = (MEMP *)((U32)pool + size - sizeof(MEMP *));
ptr->next->next = NULL;
ptr->len = 0U;
return (0U);
}
// Allocate Memory from Memory pool
// Parameters:
// pool: Pointer to memory pool
// size: Size of memory in bytes to allocate
// Return: Pointer to allocated memory
void *rt_alloc_mem (void *pool, U32 size) {
MEMP *p, *p_search, *p_new;
U32 hole_size;
if ((pool == NULL) || (size == 0U)) { return NULL; }
/* Add header offset to 'size' */
size += sizeof(MEMP);
/* Make sure that block is 4-byte aligned */
size = (size + 3U) & ~(U32)3U;
p_search = (MEMP *)pool;
while (1) {
hole_size = (U32)p_search->next - (U32)p_search;
hole_size -= p_search->len;
/* Check if hole size is big enough */
if (hole_size >= size) { break; }
p_search = p_search->next;
if (p_search->next == NULL) {
/* Failed, we are at the end of the list */
return NULL;
}
}
if (p_search->len == 0U) {
/* No block is allocated, set the Length of the first element */
p_search->len = size;
p = (MEMP *)(((U32)p_search) + sizeof(MEMP));
} else {
/* Insert new list element into the memory list */
p_new = (MEMP *)((U32)p_search + p_search->len);
p_new->next = p_search->next;
p_new->len = size;
p_search->next = p_new;
p = (MEMP *)(((U32)p_new) + sizeof(MEMP));
}
return (p);
}
// Free Memory and return it to Memory pool
// Parameters:
// pool: Pointer to memory pool
// mem: Pointer to memory to free
// Return: 0 - OK, 1 - Error
U32 rt_free_mem (void *pool, void *mem) {
MEMP *p_search, *p_prev, *p_return;
if ((pool == NULL) || (mem == NULL)) { return (1U); }
p_return = (MEMP *)((U32)mem - sizeof(MEMP));
/* Set list header */
p_prev = NULL;
p_search = (MEMP *)pool;
while (p_search != p_return) {
p_prev = p_search;
p_search = p_search->next;
if (p_search == NULL) {
/* Valid Memory block not found */
return (1U);
}
}
if (p_prev == NULL) {
/* First block to be released, only set length to 0 */
p_search->len = 0U;
} else {
/* Discard block from chain list */
p_prev->next = p_search->next;
}
return (0U);
}
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_Memory.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 932 |
```c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: rt_CMSIS.c
* Purpose: CMSIS RTOS API
* Rev.: V4.82
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#define __CMSIS_GENERIC
#if defined (__CORTEX_M4) || defined (__CORTEX_M4F)
#include "core_cm4.h"
#elif defined (__CORTEX_M3)
#include "core_cm3.h"
#elif defined (__CORTEX_M0)
#include "core_cm0.h"
#else
#error "Missing __CORTEX_Mx definition"
#endif
#include "rt_TypeDef.h"
#include "RTX_Config.h"
#include "rt_System.h"
#include "rt_Task.h"
#include "rt_Event.h"
#include "rt_List.h"
#include "rt_Time.h"
#include "rt_Mutex.h"
#include "rt_Semaphore.h"
#include "rt_Mailbox.h"
#include "rt_MemBox.h"
#include "rt_Memory.h"
#include "rt_HAL_CM.h"
#define os_thread_cb OS_TCB
#include "cmsis_os.h"
#if (osFeature_Signals != 16)
#error Invalid "osFeature_Signals" value!
#endif
#if (osFeature_Semaphore > 65535)
#error Invalid "osFeature_Semaphore" value!
#endif
#if (osFeature_Wait != 0)
#error osWait not supported!
#endif
// ==== Enumeration, structures, defines ====
// Service Calls defines
#if defined (__CC_ARM) /* ARM Compiler */
#define __NO_RETURN __declspec(noreturn)
#define osEvent_type osEvent
#define osEvent_ret_status ret
#define osEvent_ret_value ret
#define osEvent_ret_msg ret
#define osEvent_ret_mail ret
#define osCallback_type osCallback
#define osCallback_ret ret
#define SVC_0_1(f,t,...) \
__svc_indirect(0) t _##f (t(*)()); \
t f (void); \
__attribute__((always_inline)) \
static __inline t __##f (void) { \
return _##f(f); \
}
#define SVC_1_0(f,t,t1,...) \
__svc_indirect(0) t _##f (t(*)(t1),t1); \
t f (t1 a1); \
__attribute__((always_inline)) \
static __inline t __##f (t1 a1) { \
_##f(f,a1); \
}
#define SVC_1_1(f,t,t1,...) \
__svc_indirect(0) t _##f (t(*)(t1),t1); \
t f (t1 a1); \
__attribute__((always_inline)) \
static __inline t __##f (t1 a1) { \
return _##f(f,a1); \
}
#define SVC_2_1(f,t,t1,t2,...) \
__svc_indirect(0) t _##f (t(*)(t1,t2),t1,t2); \
t f (t1 a1, t2 a2); \
__attribute__((always_inline)) \
static __inline t __##f (t1 a1, t2 a2) { \
return _##f(f,a1,a2); \
}
#define SVC_3_1(f,t,t1,t2,t3,...) \
__svc_indirect(0) t _##f (t(*)(t1,t2,t3),t1,t2,t3); \
t f (t1 a1, t2 a2, t3 a3); \
__attribute__((always_inline)) \
static __inline t __##f (t1 a1, t2 a2, t3 a3) { \
return _##f(f,a1,a2,a3); \
}
#define SVC_4_1(f,t,t1,t2,t3,t4,...) \
__svc_indirect(0) t _##f (t(*)(t1,t2,t3,t4),t1,t2,t3,t4); \
t f (t1 a1, t2 a2, t3 a3, t4 a4); \
__attribute__((always_inline)) \
static __inline t __##f (t1 a1, t2 a2, t3 a3, t4 a4) { \
return _##f(f,a1,a2,a3,a4); \
}
#define SVC_1_2 SVC_1_1
#define SVC_1_3 SVC_1_1
#define SVC_2_3 SVC_2_1
#elif defined (__GNUC__) /* GNU Compiler */
#define __NO_RETURN __attribute__((noreturn))
typedef uint32_t __attribute__((vector_size(8))) ret64;
typedef uint32_t __attribute__((vector_size(16))) ret128;
#define RET_pointer __r0
#define RET_int32_t __r0
#define RET_uint32_t __r0
#define RET_osStatus __r0
#define RET_osPriority __r0
#define RET_osEvent {(osStatus)__r0, {(uint32_t)__r1}, {(void *)__r2}}
#define RET_osCallback {(void *)__r0, (void *)__r1}
#define osEvent_type __attribute__((pcs("aapcs"))) ret128
#define osEvent_ret_status (ret128){ret.status}
#define osEvent_ret_value (ret128){ret.status, ret.value.v}
#define osEvent_ret_msg (ret128){ret.status, ret.value.v, (uint32_t)ret.def.message_id}
#define osEvent_ret_mail (ret128){ret.status, ret.value.v, (uint32_t)ret.def.mail_id}
#define osCallback_type __attribute__((pcs("aapcs"))) ret64
#define osCallback_ret (ret64) {(uint32_t)ret.fp, (uint32_t)ret.arg}
#define SVC_ArgN(n) \
register int __r##n __asm("r"#n);
#define SVC_ArgR(n,t,a) \
register t __r##n __asm("r"#n) = a;
#define SVC_Arg0() \
SVC_ArgN(0) \
SVC_ArgN(1) \
SVC_ArgN(2) \
SVC_ArgN(3)
#define SVC_Arg1(t1) \
SVC_ArgR(0,t1,a1) \
SVC_ArgN(1) \
SVC_ArgN(2) \
SVC_ArgN(3)
#define SVC_Arg2(t1,t2) \
SVC_ArgR(0,t1,a1) \
SVC_ArgR(1,t2,a2) \
SVC_ArgN(2) \
SVC_ArgN(3)
#define SVC_Arg3(t1,t2,t3) \
SVC_ArgR(0,t1,a1) \
SVC_ArgR(1,t2,a2) \
SVC_ArgR(2,t3,a3) \
SVC_ArgN(3)
#define SVC_Arg4(t1,t2,t3,t4) \
SVC_ArgR(0,t1,a1) \
SVC_ArgR(1,t2,a2) \
SVC_ArgR(2,t3,a3) \
SVC_ArgR(3,t4,a4)
#if (defined (__CORTEX_M0))
#define SVC_Call(f) \
__asm volatile \
( \
"ldr r7,="#f"\n\t" \
"mov r12,r7\n\t" \
"svc 0" \
: "=r" (__r0), "=r" (__r1), "=r" (__r2), "=r" (__r3) \
: "r" (__r0), "r" (__r1), "r" (__r2), "r" (__r3) \
: "r7", "r12", "lr", "cc" \
);
#else
#define SVC_Call(f) \
__asm volatile \
( \
"ldr r12,="#f"\n\t" \
"svc 0" \
: "=r" (__r0), "=r" (__r1), "=r" (__r2), "=r" (__r3) \
: "r" (__r0), "r" (__r1), "r" (__r2), "r" (__r3) \
: "r12", "lr", "cc" \
);
#endif
#define SVC_0_1(f,t,rv) \
__attribute__((always_inline)) \
static inline t __##f (void) { \
SVC_Arg0(); \
SVC_Call(f); \
return (t) rv; \
}
#define SVC_1_0(f,t,t1) \
__attribute__((always_inline)) \
static inline t __##f (t1 a1) { \
SVC_Arg1(t1); \
SVC_Call(f); \
}
#define SVC_1_1(f,t,t1,rv) \
__attribute__((always_inline)) \
static inline t __##f (t1 a1) { \
SVC_Arg1(t1); \
SVC_Call(f); \
return (t) rv; \
}
#define SVC_2_1(f,t,t1,t2,rv) \
__attribute__((always_inline)) \
static inline t __##f (t1 a1, t2 a2) { \
SVC_Arg2(t1,t2); \
SVC_Call(f); \
return (t) rv; \
}
#define SVC_3_1(f,t,t1,t2,t3,rv) \
__attribute__((always_inline)) \
static inline t __##f (t1 a1, t2 a2, t3 a3) { \
SVC_Arg3(t1,t2,t3); \
SVC_Call(f); \
return (t) rv; \
}
#define SVC_4_1(f,t,t1,t2,t3,t4,rv) \
__attribute__((always_inline)) \
static inline t __##f (t1 a1, t2 a2, t3 a3, t4 a4) { \
SVC_Arg4(t1,t2,t3,t4); \
SVC_Call(f); \
return (t) rv; \
}
#define SVC_1_2 SVC_1_1
#define SVC_1_3 SVC_1_1
#define SVC_2_3 SVC_2_1
#elif defined (__ICCARM__) /* IAR Compiler */
#define __NO_RETURN __noreturn
#define RET_osEvent "=r"(ret.status), "=r"(ret.value), "=r"(ret.def)
#define RET_osCallback "=r"(ret.fp), "=r"(ret.arg)
#define osEvent_type osEvent
#define osEvent_ret_status ret
#define osEvent_ret_value ret
#define osEvent_ret_msg ret
#define osEvent_ret_mail ret
#define osCallback_type uint64_t
#define osCallback_ret ((uint64_t)ret.fp | ((uint64_t)ret.arg)<<32)
#define SVC_Setup(f) \
__asm( \
"mov r12,%0\n" \
:: "r"(&f): "r12" \
);
#define SVC_Ret3() \
__asm( \
"ldr r0,[sp,#0]\n" \
"ldr r1,[sp,#4]\n" \
"ldr r2,[sp,#8]\n" \
);
#define SVC_0_1(f,t,...) \
t f (void); \
_Pragma("swi_number=0") __swi t _##f (void); \
static inline t __##f (void) { \
SVC_Setup(f); \
return _##f(); \
}
#define SVC_1_0(f,t,t1,...) \
t f (t1 a1); \
_Pragma("swi_number=0") __swi t _##f (t1 a1); \
static inline t __##f (t1 a1) { \
SVC_Setup(f); \
_##f(a1); \
}
#define SVC_1_1(f,t,t1,...) \
t f (t1 a1); \
_Pragma("swi_number=0") __swi t _##f (t1 a1); \
static inline t __##f (t1 a1) { \
SVC_Setup(f); \
return _##f(a1); \
}
#define SVC_2_1(f,t,t1,t2,...) \
t f (t1 a1, t2 a2); \
_Pragma("swi_number=0") __swi t _##f (t1 a1, t2 a2); \
static inline t __##f (t1 a1, t2 a2) { \
SVC_Setup(f); \
return _##f(a1,a2); \
}
#define SVC_3_1(f,t,t1,t2,t3,...) \
t f (t1 a1, t2 a2, t3 a3); \
_Pragma("swi_number=0") __swi t _##f (t1 a1, t2 a2, t3 a3); \
static inline t __##f (t1 a1, t2 a2, t3 a3) { \
SVC_Setup(f); \
return _##f(a1,a2,a3); \
}
#define SVC_4_1(f,t,t1,t2,t3,t4,...) \
t f (t1 a1, t2 a2, t3 a3, t4 a4); \
_Pragma("swi_number=0") __swi t _##f (t1 a1, t2 a2, t3 a3, t4 a4); \
static inline t __##f (t1 a1, t2 a2, t3 a3, t4 a4) { \
SVC_Setup(f); \
return _##f(a1,a2,a3,a4); \
}
#define SVC_1_2(f,t,t1,rr) \
uint64_t f (t1 a1); \
_Pragma("swi_number=0") __swi uint64_t _##f (t1 a1); \
static inline t __##f (t1 a1) { \
t ret; \
SVC_Setup(f); \
_##f(a1); \
__asm("" : rr : :); \
return ret; \
}
#define SVC_1_3(f,t,t1,rr) \
t f (t1 a1); \
void f##_ (t1 a1) { \
f(a1); \
SVC_Ret3(); \
} \
_Pragma("swi_number=0") __swi void _##f (t1 a1); \
static inline t __##f (t1 a1) { \
t ret; \
SVC_Setup(f##_); \
_##f(a1); \
__asm("" : rr : :); \
return ret; \
}
#define SVC_2_3(f,t,t1,t2,rr) \
t f (t1 a1, t2 a2); \
void f##_ (t1 a1, t2 a2) { \
f(a1,a2); \
SVC_Ret3(); \
} \
_Pragma("swi_number=0") __swi void _##f (t1 a1, t2 a2); \
static inline t __##f (t1 a1, t2 a2) { \
t ret; \
SVC_Setup(f##_); \
_##f(a1,a2); \
__asm("" : rr : :); \
return ret; \
}
#endif
// Callback structure
typedef struct {
void *fp; // Function pointer
void *arg; // Function argument
} osCallback;
// OS Section definitions
#ifdef OS_SECTIONS_LINK_INFO
extern const uint32_t os_section_id$$Base;
extern const uint32_t os_section_id$$Limit;
#endif
// OS Stack Memory for Threads definitions
extern uint64_t os_stack_mem[];
extern const uint32_t os_stack_sz;
// OS Timers external resources
extern const osThreadDef_t os_thread_def_osTimerThread;
extern osThreadId osThreadId_osTimerThread;
extern const osMessageQDef_t os_messageQ_def_osTimerMessageQ;
extern osMessageQId osMessageQId_osTimerMessageQ;
// ==== Helper Functions ====
/// Convert timeout in millisec to system ticks
static uint16_t rt_ms2tick (uint32_t millisec) {
uint32_t tick;
if (millisec == 0U) { return 0x0U; } // No timeout
if (millisec == osWaitForever) { return 0xFFFFU; } // Indefinite timeout
if (millisec > 4000000U) { return 0xFFFEU; } // Max ticks supported
tick = ((1000U * millisec) + os_clockrate - 1U) / os_clockrate;
if (tick > 0xFFFEU) { return 0xFFFEU; }
return (uint16_t)tick;
}
/// Convert Thread ID to TCB pointer
static P_TCB rt_tid2ptcb (osThreadId thread_id) {
P_TCB ptcb;
if (thread_id == NULL) { return NULL; }
if ((uint32_t)thread_id & 3U) { return NULL; }
#ifdef OS_SECTIONS_LINK_INFO
if ((os_section_id$$Base != 0U) && (os_section_id$$Limit != 0U)) {
if (thread_id < (osThreadId)os_section_id$$Base) { return NULL; }
if (thread_id >= (osThreadId)os_section_id$$Limit) { return NULL; }
}
#endif
ptcb = thread_id;
if (ptcb->cb_type != TCB) { return NULL; }
return ptcb;
}
/// Convert ID pointer to Object pointer
static void *rt_id2obj (void *id) {
if ((uint32_t)id & 3U) { return NULL; }
#ifdef OS_SECTIONS_LINK_INFO
if ((os_section_id$$Base != 0U) && (os_section_id$$Limit != 0U)) {
if (id < (void *)os_section_id$$Base) { return NULL; }
if (id >= (void *)os_section_id$$Limit) { return NULL; }
}
#endif
return id;
}
// ==== Kernel Control ====
uint8_t os_initialized; // Kernel Initialized flag
uint8_t os_running; // Kernel Running flag
// Kernel Control Service Calls declarations
SVC_0_1(svcKernelInitialize, osStatus, RET_osStatus)
SVC_0_1(svcKernelStart, osStatus, RET_osStatus)
SVC_0_1(svcKernelRunning, int32_t, RET_int32_t)
SVC_0_1(svcKernelSysTick, uint32_t, RET_uint32_t)
static void sysThreadError (osStatus status);
osThreadId svcThreadCreate (const osThreadDef_t *thread_def, void *argument);
osMessageQId svcMessageCreate (const osMessageQDef_t *queue_def, osThreadId thread_id);
// Kernel Control Service Calls
/// Initialize the RTOS Kernel for creating objects
osStatus svcKernelInitialize (void) {
uint32_t ret;
if (os_initialized == 0U) {
// Init Thread Stack Memory (must be 8-byte aligned)
if (((uint32_t)os_stack_mem & 7U) != 0U) { return osErrorNoMemory; }
ret = rt_init_mem(os_stack_mem, os_stack_sz);
if (ret != 0U) { return osErrorNoMemory; }
rt_sys_init(); // RTX System Initialization
}
os_tsk.run->prio = 255U; // Highest priority
if (os_initialized == 0U) {
// Create OS Timers resources (Message Queue & Thread)
osMessageQId_osTimerMessageQ = svcMessageCreate (&os_messageQ_def_osTimerMessageQ, NULL);
osThreadId_osTimerThread = svcThreadCreate(&os_thread_def_osTimerThread, NULL);
}
sysThreadError(osOK);
os_initialized = 1U;
os_running = 0U;
return osOK;
}
/// Start the RTOS Kernel
osStatus svcKernelStart (void) {
if (os_running) { return osOK; }
rt_tsk_prio(0U, os_tsk.run->prio_base); // Restore priority
if (os_tsk.run->task_id == 0xFFU) { // Idle Thread
__set_PSP(os_tsk.run->tsk_stack + (8U*4U)); // Setup PSP
}
if (os_tsk.next == NULL) { // Force context switch
os_tsk.next = os_tsk.run;
os_tsk.run = NULL;
}
rt_sys_start();
os_running = 1U;
return osOK;
}
/// Check if the RTOS kernel is already started
int32_t svcKernelRunning (void) {
return (int32_t)os_running;
}
/// Get the RTOS kernel system timer counter
uint32_t svcKernelSysTick (void) {
uint32_t tick, tick0;
tick = os_tick_val();
if (os_tick_ovf()) {
tick0 = os_tick_val();
if (tick0 < tick) { tick = tick0; }
tick += (os_trv + 1U) * (os_time + 1U);
} else {
tick += (os_trv + 1U) * os_time;
}
return tick;
}
// Kernel Control Public API
/// Initialize the RTOS Kernel for creating objects
osStatus osKernelInitialize (void) {
if (__get_IPSR() != 0U) {
return osErrorISR; // Not allowed in ISR
}
if ((__get_CONTROL() & 1U) == 0U) { // Privileged mode
return svcKernelInitialize();
} else {
return __svcKernelInitialize();
}
}
/// Start the RTOS Kernel
osStatus osKernelStart (void) {
uint32_t stack[8];
if (__get_IPSR() != 0U) {
return osErrorISR; // Not allowed in ISR
}
switch (__get_CONTROL() & 0x03U) {
case 0x00U: // Privileged Thread mode & MSP
__set_PSP((uint32_t)(stack + 8)); // Initial PSP
if (os_flags & 1U) {
__set_CONTROL(0x02U); // Set Privileged Thread mode & PSP
} else {
__set_CONTROL(0x03U); // Set Unprivileged Thread mode & PSP
}
__DSB();
__ISB();
break;
case 0x01U: // Unprivileged Thread mode & MSP
return osErrorOS;
case 0x02U: // Privileged Thread mode & PSP
if ((os_flags & 1U) == 0U) { // Unprivileged Thread mode requested
__set_CONTROL(0x03U); // Set Unprivileged Thread mode & PSP
__DSB();
__ISB();
}
break;
case 0x03U: // Unprivileged Thread mode & PSP
if (os_flags & 1U) { return osErrorOS; } // Privileged Thread mode requested
break;
}
return __svcKernelStart();
}
/// Check if the RTOS kernel is already started
int32_t osKernelRunning (void) {
if ((__get_IPSR() != 0U) || ((__get_CONTROL() & 1U) == 0U)) {
// in ISR or Privileged
return (int32_t)os_running;
} else {
return __svcKernelRunning();
}
}
/// Get the RTOS kernel system timer counter
uint32_t osKernelSysTick (void) {
if (__get_IPSR() != 0U) { return 0U; } // Not allowed in ISR
return __svcKernelSysTick();
}
// ==== Thread Management ====
/// Set Thread Error (for Create functions which return IDs)
static void sysThreadError (osStatus status) {
// To Do
}
__NO_RETURN void osThreadExit (void);
// Thread Service Calls declarations
SVC_2_1(svcThreadCreate, osThreadId, const osThreadDef_t *, void *, RET_pointer)
SVC_0_1(svcThreadGetId, osThreadId, RET_pointer)
SVC_1_1(svcThreadTerminate, osStatus, osThreadId, RET_osStatus)
SVC_0_1(svcThreadYield, osStatus, RET_osStatus)
SVC_2_1(svcThreadSetPriority, osStatus, osThreadId, osPriority, RET_osStatus)
SVC_1_1(svcThreadGetPriority, osPriority, osThreadId, RET_osPriority)
// Thread Service Calls
/// Create a thread and add it to Active Threads and set it to state READY
osThreadId svcThreadCreate (const osThreadDef_t *thread_def, void *argument) {
P_TCB ptcb;
OS_TID tsk;
void *stk;
if ((thread_def == NULL) ||
(thread_def->pthread == NULL) ||
(thread_def->tpriority < osPriorityIdle) ||
(thread_def->tpriority > osPriorityRealtime)) {
sysThreadError(osErrorParameter);
return NULL;
}
if (thread_def->stacksize != 0U) { // Custom stack size
stk = rt_alloc_mem( // Allocate stack
os_stack_mem,
thread_def->stacksize
);
if (stk == NULL) {
sysThreadError(osErrorNoMemory); // Out of memory
return NULL;
}
} else { // Default stack size
stk = NULL;
}
tsk = rt_tsk_create( // Create task
(FUNCP)thread_def->pthread, // Task function pointer
(uint32_t)
(thread_def->tpriority-osPriorityIdle+1) | // Task priority
(thread_def->stacksize << 8), // Task stack size in bytes
stk, // Pointer to task's stack
argument // Argument to the task
);
if (tsk == 0U) { // Invalid task ID
if (stk != NULL) {
rt_free_mem(os_stack_mem, stk); // Free allocated stack
}
sysThreadError(osErrorNoMemory); // Create task failed (Out of memory)
return NULL;
}
ptcb = (P_TCB)os_active_TCB[tsk - 1U]; // TCB pointer
*((uint32_t *)ptcb->tsk_stack + 13) = (uint32_t)osThreadExit;
return ptcb;
}
/// Return the thread ID of the current running thread
osThreadId svcThreadGetId (void) {
OS_TID tsk;
tsk = rt_tsk_self();
if (tsk == 0U) { return NULL; }
return (P_TCB)os_active_TCB[tsk - 1U];
}
/// Terminate execution of a thread and remove it from ActiveThreads
osStatus svcThreadTerminate (osThreadId thread_id) {
OS_RESULT res;
P_TCB ptcb;
void *stk;
ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer
if (ptcb == NULL) {
return osErrorParameter;
}
stk = ptcb->priv_stack ? ptcb->stack : NULL; // Private stack
res = rt_tsk_delete(ptcb->task_id); // Delete task
if (res == OS_R_NOK) {
return osErrorResource; // Delete task failed
}
if (stk != NULL) {
rt_free_mem(os_stack_mem, stk); // Free private stack
}
return osOK;
}
/// Pass control to next thread that is in state READY
osStatus svcThreadYield (void) {
rt_tsk_pass(); // Pass control to next task
return osOK;
}
/// Change priority of an active thread
osStatus svcThreadSetPriority (osThreadId thread_id, osPriority priority) {
OS_RESULT res;
P_TCB ptcb;
ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer
if (ptcb == NULL) {
return osErrorParameter;
}
if ((priority < osPriorityIdle) || (priority > osPriorityRealtime)) {
return osErrorValue;
}
res = rt_tsk_prio( // Change task priority
ptcb->task_id, // Task ID
(uint8_t)(priority - osPriorityIdle + 1) // New task priority
);
if (res == OS_R_NOK) {
return osErrorResource; // Change task priority failed
}
return osOK;
}
/// Get current priority of an active thread
osPriority svcThreadGetPriority (osThreadId thread_id) {
P_TCB ptcb;
ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer
if (ptcb == NULL) {
return osPriorityError;
}
return (osPriority)(ptcb->prio - 1 + osPriorityIdle);
}
// Thread Public API
/// Create a thread and add it to Active Threads and set it to state READY
osThreadId osThreadCreate (const osThreadDef_t *thread_def, void *argument) {
if (__get_IPSR() != 0U) {
return NULL; // Not allowed in ISR
}
if (((__get_CONTROL() & 1U) == 0U) && (os_running == 0U)) {
// Privileged and not running
return svcThreadCreate(thread_def, argument);
} else {
return __svcThreadCreate(thread_def, argument);
}
}
/// Return the thread ID of the current running thread
osThreadId osThreadGetId (void) {
if (__get_IPSR() != 0U) {
return NULL; // Not allowed in ISR
}
return __svcThreadGetId();
}
/// Terminate execution of a thread and remove it from ActiveThreads
osStatus osThreadTerminate (osThreadId thread_id) {
if (__get_IPSR() != 0U) {
return osErrorISR; // Not allowed in ISR
}
return __svcThreadTerminate(thread_id);
}
/// Pass control to next thread that is in state READY
osStatus osThreadYield (void) {
if (__get_IPSR() != 0U) {
return osErrorISR; // Not allowed in ISR
}
return __svcThreadYield();
}
/// Change priority of an active thread
osStatus osThreadSetPriority (osThreadId thread_id, osPriority priority) {
if (__get_IPSR() != 0U) {
return osErrorISR; // Not allowed in ISR
}
return __svcThreadSetPriority(thread_id, priority);
}
/// Get current priority of an active thread
osPriority osThreadGetPriority (osThreadId thread_id) {
if (__get_IPSR() != 0U) {
return osPriorityError; // Not allowed in ISR
}
return __svcThreadGetPriority(thread_id);
}
/// INTERNAL - Not Public
/// Auto Terminate Thread on exit (used implicitly when thread exists)
__NO_RETURN void osThreadExit (void) {
__svcThreadTerminate(__svcThreadGetId());
for (;;); // Should never come here
}
// ==== Generic Wait Functions ====
// Generic Wait Service Calls declarations
SVC_1_1(svcDelay, osStatus, uint32_t, RET_osStatus)
#if osFeature_Wait != 0
SVC_1_3(svcWait, os_InRegs osEvent, uint32_t, RET_osEvent)
#endif
// Generic Wait Service Calls
/// Wait for Timeout (Time Delay)
osStatus svcDelay (uint32_t millisec) {
if (millisec == 0U) { return osOK; }
rt_dly_wait(rt_ms2tick(millisec));
return osEventTimeout;
}
/// Wait for Signal, Message, Mail, or Timeout
#if osFeature_Wait != 0
os_InRegs osEvent_type svcWait (uint32_t millisec) {
osEvent ret;
if (millisec == 0U) {
ret.status = osOK;
return osEvent_ret_status;
}
/* To Do: osEventSignal, osEventMessage, osEventMail */
rt_dly_wait(rt_ms2tick(millisec));
ret.status = osEventTimeout;
return osEvent_ret_status;
}
#endif
// Generic Wait API
/// Wait for Timeout (Time Delay)
osStatus osDelay (uint32_t millisec) {
if (__get_IPSR() != 0U) {
return osErrorISR; // Not allowed in ISR
}
return __svcDelay(millisec);
}
/// Wait for Signal, Message, Mail, or Timeout
os_InRegs osEvent osWait (uint32_t millisec) {
osEvent ret;
#if osFeature_Wait == 0
ret.status = osErrorOS;
return ret;
#else
if (__get_IPSR() != 0U) { // Not allowed in ISR
ret.status = osErrorISR;
return ret;
}
return __svcWait(millisec);
#endif
}
// ==== Timer Management ====
// Timer definitions
#define osTimerInvalid 0U
#define osTimerStopped 1U
#define osTimerRunning 2U
// Timer structures
typedef struct os_timer_cb_ { // Timer Control Block
struct os_timer_cb_ *next; // Pointer to next active Timer
uint8_t state; // Timer State
uint8_t type; // Timer Type (Periodic/One-shot)
uint16_t reserved; // Reserved
uint32_t tcnt; // Timer Delay Count
uint32_t icnt; // Timer Initial Count
void *arg; // Timer Function Argument
const osTimerDef_t *timer; // Pointer to Timer definition
} os_timer_cb;
// Timer variables
os_timer_cb *os_timer_head; // Pointer to first active Timer
// Timer Helper Functions
// Insert Timer into the list sorted by time
static void rt_timer_insert (os_timer_cb *pt, uint32_t tcnt) {
os_timer_cb *p, *prev;
prev = NULL;
p = os_timer_head;
while (p != NULL) {
if (tcnt < p->tcnt) { break; }
tcnt -= p->tcnt;
prev = p;
p = p->next;
}
pt->next = p;
pt->tcnt = tcnt;
if (p != NULL) {
p->tcnt -= pt->tcnt;
}
if (prev != NULL) {
prev->next = pt;
} else {
os_timer_head = pt;
}
}
// Remove Timer from the list
static int32_t rt_timer_remove (os_timer_cb *pt) {
os_timer_cb *p, *prev;
prev = NULL;
p = os_timer_head;
while (p != NULL) {
if (p == pt) { break; }
prev = p;
p = p->next;
}
if (p == NULL) { return -1; }
if (prev != NULL) {
prev->next = pt->next;
} else {
os_timer_head = pt->next;
}
if (pt->next != NULL) {
pt->next->tcnt += pt->tcnt;
}
return 0;
}
// Timer Service Calls declarations
SVC_3_1(svcTimerCreate, osTimerId, const osTimerDef_t *, os_timer_type, void *, RET_pointer)
SVC_2_1(svcTimerStart, osStatus, osTimerId, uint32_t, RET_osStatus)
SVC_1_1(svcTimerStop, osStatus, osTimerId, RET_osStatus)
SVC_1_1(svcTimerDelete, osStatus, osTimerId, RET_osStatus)
SVC_1_2(svcTimerCall, os_InRegs osCallback, osTimerId, RET_osCallback)
// Timer Management Service Calls
/// Create timer
osTimerId svcTimerCreate (const osTimerDef_t *timer_def, os_timer_type type, void *argument) {
os_timer_cb *pt;
if ((timer_def == NULL) || (timer_def->ptimer == NULL)) {
sysThreadError(osErrorParameter);
return NULL;
}
pt = timer_def->timer;
if (pt == NULL) {
sysThreadError(osErrorParameter);
return NULL;
}
if ((type != osTimerOnce) && (type != osTimerPeriodic)) {
sysThreadError(osErrorValue);
return NULL;
}
if (osThreadId_osTimerThread == NULL) {
sysThreadError(osErrorResource);
return NULL;
}
if (pt->state != osTimerInvalid){
sysThreadError(osErrorResource);
return NULL;
}
pt->next = NULL;
pt->state = osTimerStopped;
pt->type = (uint8_t)type;
pt->arg = argument;
pt->timer = timer_def;
return (osTimerId)pt;
}
/// Start or restart timer
osStatus svcTimerStart (osTimerId timer_id, uint32_t millisec) {
os_timer_cb *pt;
uint32_t tcnt;
pt = rt_id2obj(timer_id);
if (pt == NULL) {
return osErrorParameter;
}
if (millisec == 0U) { return osErrorValue; }
tcnt = (uint32_t)(((1000U * (uint64_t)millisec) + os_clockrate - 1U) / os_clockrate);
switch (pt->state) {
case osTimerRunning:
if (rt_timer_remove(pt) != 0) {
return osErrorResource;
}
break;
case osTimerStopped:
pt->state = osTimerRunning;
pt->icnt = tcnt;
break;
default:
return osErrorResource;
}
rt_timer_insert(pt, tcnt);
return osOK;
}
/// Stop timer
osStatus svcTimerStop (osTimerId timer_id) {
os_timer_cb *pt;
pt = rt_id2obj(timer_id);
if (pt == NULL) {
return osErrorParameter;
}
if (pt->state != osTimerRunning) { return osErrorResource; }
pt->state = osTimerStopped;
if (rt_timer_remove(pt) != 0) {
return osErrorResource;
}
return osOK;
}
/// Delete timer
osStatus svcTimerDelete (osTimerId timer_id) {
os_timer_cb *pt;
pt = rt_id2obj(timer_id);
if (pt == NULL) {
return osErrorParameter;
}
switch (pt->state) {
case osTimerRunning:
rt_timer_remove(pt);
break;
case osTimerStopped:
break;
default:
return osErrorResource;
}
pt->state = osTimerInvalid;
return osOK;
}
/// Get timer callback parameters
os_InRegs osCallback_type svcTimerCall (osTimerId timer_id) {
os_timer_cb *pt;
osCallback ret;
pt = rt_id2obj(timer_id);
if (pt == NULL) {
ret.fp = NULL;
ret.arg = NULL;
return osCallback_ret;
}
ret.fp = (void *)pt->timer->ptimer;
ret.arg = pt->arg;
return osCallback_ret;
}
osStatus isrMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec);
/// Timer Tick (called each SysTick)
void sysTimerTick (void) {
os_timer_cb *pt, *p;
osStatus status;
p = os_timer_head;
if (p == NULL) { return; }
p->tcnt--;
while ((p != NULL) && (p->tcnt == 0U)) {
pt = p;
p = p->next;
os_timer_head = p;
status = isrMessagePut(osMessageQId_osTimerMessageQ, (uint32_t)pt, 0U);
if (status != osOK) {
os_error(OS_ERR_TIMER_OVF);
}
if (pt->type == (uint8_t)osTimerPeriodic) {
rt_timer_insert(pt, pt->icnt);
} else {
pt->state = osTimerStopped;
}
}
}
/// Get user timers wake-up time
uint32_t sysUserTimerWakeupTime (void) {
if (os_timer_head) {
return os_timer_head->tcnt;
}
return 0xFFFFFFFFU;
}
/// Update user timers on resume
void sysUserTimerUpdate (uint32_t sleep_time) {
while ((os_timer_head != NULL) && (sleep_time != 0U)) {
if (sleep_time >= os_timer_head->tcnt) {
sleep_time -= os_timer_head->tcnt;
os_timer_head->tcnt = 1U;
sysTimerTick();
} else {
os_timer_head->tcnt -= sleep_time;
break;
}
}
}
// Timer Management Public API
/// Create timer
osTimerId osTimerCreate (const osTimerDef_t *timer_def, os_timer_type type, void *argument) {
if (__get_IPSR() != 0U) {
return NULL; // Not allowed in ISR
}
if (((__get_CONTROL() & 1U) == 0U) && (os_running == 0U)) {
// Privileged and not running
return svcTimerCreate(timer_def, type, argument);
} else {
return __svcTimerCreate(timer_def, type, argument);
}
}
/// Start or restart timer
osStatus osTimerStart (osTimerId timer_id, uint32_t millisec) {
if (__get_IPSR() != 0U) {
return osErrorISR; // Not allowed in ISR
}
return __svcTimerStart(timer_id, millisec);
}
/// Stop timer
osStatus osTimerStop (osTimerId timer_id) {
if (__get_IPSR() != 0U) {
return osErrorISR; // Not allowed in ISR
}
return __svcTimerStop(timer_id);
}
/// Delete timer
osStatus osTimerDelete (osTimerId timer_id) {
if (__get_IPSR() != 0U) {
return osErrorISR; // Not allowed in ISR
}
return __svcTimerDelete(timer_id);
}
/// INTERNAL - Not Public
/// Get timer callback parameters (used by OS Timer Thread)
os_InRegs osCallback osTimerCall (osTimerId timer_id) {
return __svcTimerCall(timer_id);
}
// Timer Thread
__NO_RETURN void osTimerThread (void const *argument) {
osCallback cb;
osEvent evt;
for (;;) {
evt = osMessageGet(osMessageQId_osTimerMessageQ, osWaitForever);
if (evt.status == osEventMessage) {
cb = osTimerCall(evt.value.p);
if (cb.fp != NULL) {
(*(os_ptimer)cb.fp)(cb.arg);
}
}
}
}
// ==== Signal Management ====
// Signal Service Calls declarations
SVC_2_1(svcSignalSet, int32_t, osThreadId, int32_t, RET_int32_t)
SVC_2_1(svcSignalClear, int32_t, osThreadId, int32_t, RET_int32_t)
SVC_2_3(svcSignalWait, os_InRegs osEvent, int32_t, uint32_t, RET_osEvent)
// Signal Service Calls
/// Set the specified Signal Flags of an active thread
int32_t svcSignalSet (osThreadId thread_id, int32_t signals) {
P_TCB ptcb;
int32_t sig;
ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer
if (ptcb == NULL) {
return (int32_t)0x80000000U;
}
if ((uint32_t)signals & (0xFFFFFFFFU << osFeature_Signals)) {
return (int32_t)0x80000000U;
}
sig = (int32_t)ptcb->events; // Previous signal flags
rt_evt_set((uint16_t)signals, ptcb->task_id); // Set event flags
return sig;
}
/// Clear the specified Signal Flags of an active thread
int32_t svcSignalClear (osThreadId thread_id, int32_t signals) {
P_TCB ptcb;
int32_t sig;
ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer
if (ptcb == NULL) {
return (int32_t)0x80000000U;
}
if ((uint32_t)signals & (0xFFFFFFFFU << osFeature_Signals)) {
return (int32_t)0x80000000U;
}
sig = (int32_t)ptcb->events; // Previous signal flags
rt_evt_clr((uint16_t)signals, ptcb->task_id); // Clear event flags
return sig;
}
/// Wait for one or more Signal Flags to become signaled for the current RUNNING thread
os_InRegs osEvent_type svcSignalWait (int32_t signals, uint32_t millisec) {
OS_RESULT res;
osEvent ret;
if ((uint32_t)signals & (0xFFFFFFFFU << osFeature_Signals)) {
ret.status = osErrorValue;
return osEvent_ret_status;
}
if (signals != 0) { // Wait for all specified signals
res = rt_evt_wait((uint16_t)signals, rt_ms2tick(millisec), __TRUE);
} else { // Wait for any signal
res = rt_evt_wait(0xFFFFU, rt_ms2tick(millisec), __FALSE);
}
if (res == OS_R_EVT) {
ret.status = osEventSignal;
ret.value.signals = (signals != 0) ? signals : (int32_t)os_tsk.run->waits;
} else {
ret.status = (millisec != 0U) ? osEventTimeout : osOK;
ret.value.signals = 0;
}
return osEvent_ret_value;
}
// Signal ISR Calls
/// Set the specified Signal Flags of an active thread
int32_t isrSignalSet (osThreadId thread_id, int32_t signals) {
P_TCB ptcb;
int32_t sig;
ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer
if (ptcb == NULL) {
return (int32_t)0x80000000U;
}
if ((uint32_t)signals & (0xFFFFFFFFU << osFeature_Signals)) {
return (int32_t)0x80000000U;
}
sig = (int32_t)ptcb->events; // Previous signal flags
isr_evt_set((uint16_t)signals, ptcb->task_id);// Set event flags
return sig;
}
// Signal Public API
/// Set the specified Signal Flags of an active thread
int32_t osSignalSet (osThreadId thread_id, int32_t signals) {
if (__get_IPSR() != 0U) { // in ISR
return isrSignalSet(thread_id, signals);
} else { // in Thread
return __svcSignalSet(thread_id, signals);
}
}
/// Clear the specified Signal Flags of an active thread
int32_t osSignalClear (osThreadId thread_id, int32_t signals) {
if (__get_IPSR() != 0U) {
return (int32_t)0x80000000U; // Not allowed in ISR
}
return __svcSignalClear(thread_id, signals);
}
/// Wait for one or more Signal Flags to become signaled for the current RUNNING thread
os_InRegs osEvent osSignalWait (int32_t signals, uint32_t millisec) {
osEvent ret;
if (__get_IPSR() != 0U) { // Not allowed in ISR
ret.status = osErrorISR;
return ret;
}
return __svcSignalWait(signals, millisec);
}
// ==== Mutex Management ====
// Mutex Service Calls declarations
SVC_1_1(svcMutexCreate, osMutexId, const osMutexDef_t *, RET_pointer)
SVC_2_1(svcMutexWait, osStatus, osMutexId, uint32_t, RET_osStatus)
SVC_1_1(svcMutexRelease, osStatus, osMutexId, RET_osStatus)
SVC_1_1(svcMutexDelete, osStatus, osMutexId, RET_osStatus)
// Mutex Service Calls
/// Create and Initialize a Mutex object
osMutexId svcMutexCreate (const osMutexDef_t *mutex_def) {
OS_ID mut;
if (mutex_def == NULL) {
sysThreadError(osErrorParameter);
return NULL;
}
mut = mutex_def->mutex;
if (mut == NULL) {
sysThreadError(osErrorParameter);
return NULL;
}
if (((P_MUCB)mut)->cb_type != 0U) {
sysThreadError(osErrorParameter);
return NULL;
}
rt_mut_init(mut); // Initialize Mutex
return mut;
}
/// Wait until a Mutex becomes available
osStatus svcMutexWait (osMutexId mutex_id, uint32_t millisec) {
OS_ID mut;
OS_RESULT res;
mut = rt_id2obj(mutex_id);
if (mut == NULL) {
return osErrorParameter;
}
if (((P_MUCB)mut)->cb_type != MUCB) {
return osErrorParameter;
}
res = rt_mut_wait(mut, rt_ms2tick(millisec)); // Wait for Mutex
if (res == OS_R_TMO) {
return ((millisec != 0U) ? osErrorTimeoutResource : osErrorResource);
}
if (res == OS_R_NOK) {
return osErrorResource;
}
return osOK;
}
/// Release a Mutex that was obtained with osMutexWait
osStatus svcMutexRelease (osMutexId mutex_id) {
OS_ID mut;
OS_RESULT res;
mut = rt_id2obj(mutex_id);
if (mut == NULL) {
return osErrorParameter;
}
if (((P_MUCB)mut)->cb_type != MUCB) {
return osErrorParameter;
}
res = rt_mut_release(mut); // Release Mutex
if (res == OS_R_NOK) {
return osErrorResource; // Thread not owner or Zero Counter
}
return osOK;
}
/// Delete a Mutex that was created by osMutexCreate
osStatus svcMutexDelete (osMutexId mutex_id) {
OS_ID mut;
mut = rt_id2obj(mutex_id);
if (mut == NULL) {
return osErrorParameter;
}
if (((P_MUCB)mut)->cb_type != MUCB) {
return osErrorParameter;
}
rt_mut_delete(mut); // Release Mutex
return osOK;
}
// Mutex Public API
/// Create and Initialize a Mutex object
osMutexId osMutexCreate (const osMutexDef_t *mutex_def) {
if (__get_IPSR() != 0U) {
return NULL; // Not allowed in ISR
}
if (((__get_CONTROL() & 1U) == 0U) && (os_running == 0U)) {
// Privileged and not running
return svcMutexCreate(mutex_def);
} else {
return __svcMutexCreate(mutex_def);
}
}
/// Wait until a Mutex becomes available
osStatus osMutexWait (osMutexId mutex_id, uint32_t millisec) {
if (__get_IPSR() != 0U) {
return osErrorISR; // Not allowed in ISR
}
return __svcMutexWait(mutex_id, millisec);
}
/// Release a Mutex that was obtained with osMutexWait
osStatus osMutexRelease (osMutexId mutex_id) {
if (__get_IPSR() != 0U) {
return osErrorISR; // Not allowed in ISR
}
return __svcMutexRelease(mutex_id);
}
/// Delete a Mutex that was created by osMutexCreate
osStatus osMutexDelete (osMutexId mutex_id) {
if (__get_IPSR() != 0U) {
return osErrorISR; // Not allowed in ISR
}
return __svcMutexDelete(mutex_id);
}
// ==== Semaphore Management ====
// Semaphore Service Calls declarations
SVC_2_1(svcSemaphoreCreate, osSemaphoreId, const osSemaphoreDef_t *, int32_t, RET_pointer)
SVC_2_1(svcSemaphoreWait, int32_t, osSemaphoreId, uint32_t, RET_int32_t)
SVC_1_1(svcSemaphoreRelease, osStatus, osSemaphoreId, RET_osStatus)
SVC_1_1(svcSemaphoreDelete, osStatus, osSemaphoreId, RET_osStatus)
// Semaphore Service Calls
/// Create and Initialize a Semaphore object
osSemaphoreId svcSemaphoreCreate (const osSemaphoreDef_t *semaphore_def, int32_t count) {
OS_ID sem;
if (semaphore_def == NULL) {
sysThreadError(osErrorParameter);
return NULL;
}
sem = semaphore_def->semaphore;
if (sem == NULL) {
sysThreadError(osErrorParameter);
return NULL;
}
if (((P_SCB)sem)->cb_type != 0U) {
sysThreadError(osErrorParameter);
return NULL;
}
if (count > osFeature_Semaphore) {
sysThreadError(osErrorValue);
return NULL;
}
rt_sem_init(sem, (uint16_t)count); // Initialize Semaphore
return sem;
}
/// Wait until a Semaphore becomes available
int32_t svcSemaphoreWait (osSemaphoreId semaphore_id, uint32_t millisec) {
OS_ID sem;
OS_RESULT res;
sem = rt_id2obj(semaphore_id);
if (sem == NULL) {
return -1;
}
if (((P_SCB)sem)->cb_type != SCB) {
return -1;
}
res = rt_sem_wait(sem, rt_ms2tick(millisec)); // Wait for Semaphore
if (res == OS_R_TMO) { return 0; } // Timeout
return (int32_t)(((P_SCB)sem)->tokens + 1U);
}
/// Release a Semaphore
osStatus svcSemaphoreRelease (osSemaphoreId semaphore_id) {
OS_ID sem;
sem = rt_id2obj(semaphore_id);
if (sem == NULL) {
return osErrorParameter;
}
if (((P_SCB)sem)->cb_type != SCB) {
return osErrorParameter;
}
if ((int32_t)((P_SCB)sem)->tokens == osFeature_Semaphore) {
return osErrorResource;
}
rt_sem_send(sem); // Release Semaphore
return osOK;
}
/// Delete a Semaphore that was created by osSemaphoreCreate
osStatus svcSemaphoreDelete (osSemaphoreId semaphore_id) {
OS_ID sem;
sem = rt_id2obj(semaphore_id);
if (sem == NULL) {
return osErrorParameter;
}
if (((P_SCB)sem)->cb_type != SCB) {
return osErrorParameter;
}
rt_sem_delete(sem); // Delete Semaphore
return osOK;
}
// Semaphore ISR Calls
/// Release a Semaphore
osStatus isrSemaphoreRelease (osSemaphoreId semaphore_id) {
OS_ID sem;
sem = rt_id2obj(semaphore_id);
if (sem == NULL) {
return osErrorParameter;
}
if (((P_SCB)sem)->cb_type != SCB) {
return osErrorParameter;
}
if ((int32_t)((P_SCB)sem)->tokens == osFeature_Semaphore) {
return osErrorResource;
}
isr_sem_send(sem); // Release Semaphore
return osOK;
}
// Semaphore Public API
/// Create and Initialize a Semaphore object
osSemaphoreId osSemaphoreCreate (const osSemaphoreDef_t *semaphore_def, int32_t count) {
if (__get_IPSR() != 0U) {
return NULL; // Not allowed in ISR
}
if (((__get_CONTROL() & 1U) == 0U) && (os_running == 0U)) {
// Privileged and not running
return svcSemaphoreCreate(semaphore_def, count);
} else {
return __svcSemaphoreCreate(semaphore_def, count);
}
}
/// Wait until a Semaphore becomes available
int32_t osSemaphoreWait (osSemaphoreId semaphore_id, uint32_t millisec) {
if (__get_IPSR() != 0U) {
return -1; // Not allowed in ISR
}
return __svcSemaphoreWait(semaphore_id, millisec);
}
/// Release a Semaphore
osStatus osSemaphoreRelease (osSemaphoreId semaphore_id) {
if (__get_IPSR() != 0U) { // in ISR
return isrSemaphoreRelease(semaphore_id);
} else { // in Thread
return __svcSemaphoreRelease(semaphore_id);
}
}
/// Delete a Semaphore that was created by osSemaphoreCreate
osStatus osSemaphoreDelete (osSemaphoreId semaphore_id) {
if (__get_IPSR() != 0U) {
return osErrorISR; // Not allowed in ISR
}
return __svcSemaphoreDelete(semaphore_id);
}
// ==== Memory Management Functions ====
// Memory Management Helper Functions
// Clear Memory Box (Zero init)
static void rt_clr_box (void *box_mem, void *box) {
uint32_t *p, n;
if ((box_mem != NULL) && (box != NULL)) {
p = box;
for (n = ((P_BM)box_mem)->blk_size; n; n -= 4U) {
*p++ = 0U;
}
}
}
// Memory Management Service Calls declarations
SVC_1_1(svcPoolCreate, osPoolId, const osPoolDef_t *, RET_pointer)
SVC_1_1(sysPoolAlloc, void *, osPoolId, RET_pointer)
SVC_2_1(sysPoolFree, osStatus, osPoolId, void *, RET_osStatus)
// Memory Management Service & ISR Calls
/// Create and Initialize memory pool
osPoolId svcPoolCreate (const osPoolDef_t *pool_def) {
uint32_t blk_sz;
if ((pool_def == NULL) ||
(pool_def->pool_sz == 0U) ||
(pool_def->item_sz == 0U) ||
(pool_def->pool == NULL)) {
sysThreadError(osErrorParameter);
return NULL;
}
blk_sz = (pool_def->item_sz + 3U) & (uint32_t)~3U;
_init_box(pool_def->pool, sizeof(struct OS_BM) + (pool_def->pool_sz * blk_sz), blk_sz);
return pool_def->pool;
}
/// Allocate a memory block from a memory pool
void *sysPoolAlloc (osPoolId pool_id) {
void *mem;
if (pool_id == NULL) {
return NULL;
}
mem = rt_alloc_box(pool_id);
return mem;
}
/// Return an allocated memory block back to a specific memory pool
osStatus sysPoolFree (osPoolId pool_id, void *block) {
uint32_t res;
if (pool_id == NULL) {
return osErrorParameter;
}
res = rt_free_box(pool_id, block);
if (res != 0) {
return osErrorValue;
}
return osOK;
}
// Memory Management Public API
/// Create and Initialize memory pool
osPoolId osPoolCreate (const osPoolDef_t *pool_def) {
if (__get_IPSR() != 0U) {
return NULL; // Not allowed in ISR
}
if (((__get_CONTROL() & 1U) == 0U) && (os_running == 0U)) {
// Privileged and not running
return svcPoolCreate(pool_def);
} else {
return __svcPoolCreate(pool_def);
}
}
/// Allocate a memory block from a memory pool
void *osPoolAlloc (osPoolId pool_id) {
if ((__get_IPSR() != 0U) || ((__get_CONTROL() & 1U) == 0U)) { // in ISR or Privileged
return sysPoolAlloc(pool_id);
} else { // in Thread
return __sysPoolAlloc(pool_id);
}
}
/// Allocate a memory block from a memory pool and set memory block to zero
void *osPoolCAlloc (osPoolId pool_id) {
void *mem;
if ((__get_IPSR() != 0U) || ((__get_CONTROL() & 1U) == 0U)) { // in ISR or Privileged
mem = sysPoolAlloc(pool_id);
} else { // in Thread
mem = __sysPoolAlloc(pool_id);
}
rt_clr_box(pool_id, mem);
return mem;
}
/// Return an allocated memory block back to a specific memory pool
osStatus osPoolFree (osPoolId pool_id, void *block) {
if ((__get_IPSR() != 0U) || ((__get_CONTROL() & 1U) == 0U)) { // in ISR or Privileged
return sysPoolFree(pool_id, block);
} else { // in Thread
return __sysPoolFree(pool_id, block);
}
}
// ==== Message Queue Management Functions ====
// Message Queue Management Service Calls declarations
SVC_2_1(svcMessageCreate, osMessageQId, const osMessageQDef_t *, osThreadId, RET_pointer)
SVC_3_1(svcMessagePut, osStatus, osMessageQId, uint32_t, uint32_t, RET_osStatus)
SVC_2_3(svcMessageGet, os_InRegs osEvent, osMessageQId, uint32_t, RET_osEvent)
// Message Queue Service Calls
/// Create and Initialize Message Queue
osMessageQId svcMessageCreate (const osMessageQDef_t *queue_def, osThreadId thread_id) {
if ((queue_def == NULL) ||
(queue_def->queue_sz == 0U) ||
(queue_def->pool == NULL)) {
sysThreadError(osErrorParameter);
return NULL;
}
if (((P_MCB)queue_def->pool)->cb_type != 0U) {
sysThreadError(osErrorParameter);
return NULL;
}
rt_mbx_init(queue_def->pool, (uint16_t)(4U*(queue_def->queue_sz + 4U)));
return queue_def->pool;
}
/// Put a Message to a Queue
osStatus svcMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec) {
OS_RESULT res;
if (queue_id == NULL) {
return osErrorParameter;
}
if (((P_MCB)queue_id)->cb_type != MCB) {
return osErrorParameter;
}
res = rt_mbx_send(queue_id, (void *)info, rt_ms2tick(millisec));
if (res == OS_R_TMO) {
return ((millisec != 0U) ? osErrorTimeoutResource : osErrorResource);
}
return osOK;
}
/// Get a Message or Wait for a Message from a Queue
os_InRegs osEvent_type svcMessageGet (osMessageQId queue_id, uint32_t millisec) {
OS_RESULT res;
osEvent ret;
if (queue_id == NULL) {
ret.status = osErrorParameter;
return osEvent_ret_status;
}
if (((P_MCB)queue_id)->cb_type != MCB) {
ret.status = osErrorParameter;
return osEvent_ret_status;
}
res = rt_mbx_wait(queue_id, &ret.value.p, rt_ms2tick(millisec));
if (res == OS_R_TMO) {
ret.status = (millisec != 0U) ? osEventTimeout : osOK;
return osEvent_ret_value;
}
ret.status = osEventMessage;
return osEvent_ret_value;
}
// Message Queue ISR Calls
/// Put a Message to a Queue
osStatus isrMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec) {
if ((queue_id == NULL) || (millisec != 0U)) {
return osErrorParameter;
}
if (((P_MCB)queue_id)->cb_type != MCB) {
return osErrorParameter;
}
if (rt_mbx_check(queue_id) == 0U) { // Check if Queue is full
return osErrorResource;
}
isr_mbx_send(queue_id, (void *)info);
return osOK;
}
/// Get a Message or Wait for a Message from a Queue
os_InRegs osEvent isrMessageGet (osMessageQId queue_id, uint32_t millisec) {
OS_RESULT res;
osEvent ret;
if ((queue_id == NULL) || (millisec != 0U)) {
ret.status = osErrorParameter;
return ret;
}
if (((P_MCB)queue_id)->cb_type != MCB) {
ret.status = osErrorParameter;
return ret;
}
res = isr_mbx_receive(queue_id, &ret.value.p);
if (res != OS_R_MBX) {
ret.status = osOK;
return ret;
}
ret.status = osEventMessage;
return ret;
}
// Message Queue Management Public API
/// Create and Initialize Message Queue
osMessageQId osMessageCreate (const osMessageQDef_t *queue_def, osThreadId thread_id) {
if (__get_IPSR() != 0U) {
return NULL; // Not allowed in ISR
}
if (((__get_CONTROL() & 1U) == 0U) && (os_running == 0U)) {
// Privileged and not running
return svcMessageCreate(queue_def, thread_id);
} else {
return __svcMessageCreate(queue_def, thread_id);
}
}
/// Put a Message to a Queue
osStatus osMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec) {
if (__get_IPSR() != 0U) { // in ISR
return isrMessagePut(queue_id, info, millisec);
} else { // in Thread
return __svcMessagePut(queue_id, info, millisec);
}
}
/// Get a Message or Wait for a Message from a Queue
os_InRegs osEvent osMessageGet (osMessageQId queue_id, uint32_t millisec) {
if (__get_IPSR() != 0U) { // in ISR
return isrMessageGet(queue_id, millisec);
} else { // in Thread
return __svcMessageGet(queue_id, millisec);
}
}
// ==== Mail Queue Management Functions ====
// Mail Queue Management Service Calls declarations
SVC_2_1(svcMailCreate, osMailQId, const osMailQDef_t *, osThreadId, RET_pointer)
SVC_3_1(sysMailAlloc, void *, osMailQId, uint32_t, uint32_t, RET_pointer)
SVC_3_1(sysMailFree, osStatus, osMailQId, void *, uint32_t, RET_osStatus)
// Mail Queue Management Service & ISR Calls
/// Create and Initialize mail queue
osMailQId svcMailCreate (const osMailQDef_t *queue_def, osThreadId thread_id) {
uint32_t blk_sz;
P_MCB pmcb;
void *pool;
if ((queue_def == NULL) ||
(queue_def->queue_sz == 0U) ||
(queue_def->item_sz == 0U) ||
(queue_def->pool == NULL)) {
sysThreadError(osErrorParameter);
return NULL;
}
pmcb = *(((void **)queue_def->pool) + 0);
pool = *(((void **)queue_def->pool) + 1);
if ((pool == NULL) || (pmcb == NULL) || (pmcb->cb_type != 0U)) {
sysThreadError(osErrorParameter);
return NULL;
}
blk_sz = (queue_def->item_sz + 3U) & (uint32_t)~3U;
_init_box(pool, sizeof(struct OS_BM) + (queue_def->queue_sz * blk_sz), blk_sz);
rt_mbx_init(pmcb, (uint16_t)(4U*(queue_def->queue_sz + 4U)));
return queue_def->pool;
}
/// Allocate a memory block from a mail
void *sysMailAlloc (osMailQId queue_id, uint32_t millisec, uint32_t isr) {
P_MCB pmcb;
void *pool;
void *mem;
if (queue_id == NULL) {
return NULL;
}
pmcb = *(((void **)queue_id) + 0);
pool = *(((void **)queue_id) + 1);
if ((pool == NULL) || (pmcb == NULL)) {
return NULL;
}
if ((isr != 0U) && (millisec != 0U)) {
return NULL;
}
mem = rt_alloc_box(pool);
if ((mem == NULL) && (millisec != 0U)) {
// Put Task to sleep when Memory not available
if (pmcb->p_lnk != NULL) {
rt_put_prio((P_XCB)pmcb, os_tsk.run);
} else {
pmcb->p_lnk = os_tsk.run;
os_tsk.run->p_lnk = NULL;
os_tsk.run->p_rlnk = (P_TCB)pmcb;
// Task is waiting to allocate a message
pmcb->state = 3U;
}
rt_block(rt_ms2tick(millisec), WAIT_MBX);
}
return mem;
}
/// Free a memory block from a mail
osStatus sysMailFree (osMailQId queue_id, void *mail, uint32_t isr) {
P_MCB pmcb;
P_TCB ptcb;
void *pool;
void *mem;
uint32_t res;
if (queue_id == NULL) {
return osErrorParameter;
}
pmcb = *(((void **)queue_id) + 0);
pool = *(((void **)queue_id) + 1);
if ((pmcb == NULL) || (pool == NULL)) {
return osErrorParameter;
}
res = rt_free_box(pool, mail);
if (res != 0U) {
return osErrorValue;
}
if ((pmcb->p_lnk != NULL) && (pmcb->state == 3U)) {
// Task is waiting to allocate a message
if (isr != 0U) {
rt_psq_enq (pmcb, (U32)pool);
rt_psh_req ();
} else {
mem = rt_alloc_box(pool);
if (mem != NULL) {
ptcb = rt_get_first((P_XCB)pmcb);
rt_ret_val(ptcb, (U32)mem);
rt_rmv_dly(ptcb);
rt_dispatch(ptcb);
}
}
}
return osOK;
}
// Mail Queue Management Public API
/// Create and Initialize mail queue
osMailQId osMailCreate (const osMailQDef_t *queue_def, osThreadId thread_id) {
if (__get_IPSR() != 0U) {
return NULL; // Not allowed in ISR
}
if (((__get_CONTROL() & 1U) == 0U) && (os_running == 0U)) {
// Privileged and not running
return svcMailCreate(queue_def, thread_id);
} else {
return __svcMailCreate(queue_def, thread_id);
}
}
/// Allocate a memory block from a mail
void *osMailAlloc (osMailQId queue_id, uint32_t millisec) {
if (__get_IPSR() != 0U) { // in ISR
return sysMailAlloc(queue_id, millisec, 1U);
} else { // in Thread
return __sysMailAlloc(queue_id, millisec, 0U);
}
}
/// Allocate a memory block from a mail and set memory block to zero
void *osMailCAlloc (osMailQId queue_id, uint32_t millisec) {
void *pool;
void *mem;
if (__get_IPSR() != 0U) { // in ISR
mem = sysMailAlloc(queue_id, millisec, 1U);
} else { // in Thread
mem = __sysMailAlloc(queue_id, millisec, 0U);
}
pool = *(((void **)queue_id) + 1);
rt_clr_box(pool, mem);
return mem;
}
/// Free a memory block from a mail
osStatus osMailFree (osMailQId queue_id, void *mail) {
if (__get_IPSR() != 0U) { // in ISR
return sysMailFree(queue_id, mail, 1U);
} else { // in Thread
return __sysMailFree(queue_id, mail, 0U);
}
}
/// Put a mail to a queue
osStatus osMailPut (osMailQId queue_id, void *mail) {
if (queue_id == NULL) {
return osErrorParameter;
}
if (mail == NULL) {
return osErrorValue;
}
return osMessagePut(*((void **)queue_id), (uint32_t)mail, 0U);
}
/// Get a mail from a queue
os_InRegs osEvent osMailGet (osMailQId queue_id, uint32_t millisec) {
osEvent ret;
if (queue_id == NULL) {
ret.status = osErrorParameter;
return ret;
}
ret = osMessageGet(*((void **)queue_id), millisec);
if (ret.status == osEventMessage) ret.status = osEventMail;
return ret;
}
// ==== RTX Extensions ====
// Service Calls declarations
SVC_0_1(rt_suspend, uint32_t, RET_uint32_t)
SVC_1_0(rt_resume, void, uint32_t)
// Public API
/// Suspends the OS task scheduler
uint32_t os_suspend (void) {
return __rt_suspend();
}
/// Resumes the OS task scheduler
void os_resume (uint32_t sleep_time) {
__rt_resume(sleep_time);
}
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/rt_CMSIS.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 17,032 |
```gas
;/*your_sha256_hash------------
; * CMSIS-RTOS - RTX
; *your_sha256_hash------------
; * Name: SVC_TABLE.S
; * Purpose: Pre-defined SVC Table for Cortex-M
; * Rev.: V4.70
; *your_sha256_hash------------
; *
; *
; *
; *
; * www.apache.org/licenses/LICENSE-2.0
; *
; * Unless required by applicable law or agreed to in writing, software
; * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; *your_sha256_hash-----------*/
AREA SVC_TABLE, CODE, READONLY
EXPORT SVC_Count
SVC_Cnt EQU (SVC_End-SVC_Table)/4
SVC_Count DCD SVC_Cnt
; Import user SVC functions here.
; IMPORT __SVC_1
EXPORT SVC_Table
SVC_Table
; Insert user SVC functions here. SVC 0 used by RTL Kernel.
; DCD __SVC_1 ; user SVC function
SVC_End
END
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/ARM/SVC_Table.s | gas | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 255 |
```c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: HAL_CM3.C
* Purpose: Hardware Abstraction Layer for Cortex-M3
* Rev.: V4.70
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#include "rt_TypeDef.h"
#include "RTX_Config.h"
#include "rt_System.h"
#include "rt_HAL_CM.h"
#include "rt_Task.h"
#include "rt_MemBox.h"
/*your_sha256_hash------------
* Functions
*your_sha256_hash-----------*/
/*--------------------------- rt_set_PSP ------------------------------------*/
__asm void rt_set_PSP (U32 stack) {
MSR PSP,R0
BX LR
}
/*--------------------------- rt_get_PSP ------------------------------------*/
__asm U32 rt_get_PSP (void) {
MRS R0,PSP
BX LR
}
/*--------------------------- os_set_env ------------------------------------*/
__asm void os_set_env (void) {
/* Switch to Unprivileged/Privileged Thread mode, use PSP. */
MOV R0,SP ; PSP = MSP
MSR PSP,R0
LDR R0,=__cpp(&os_flags)
LDRB R0,[R0]
LSLS R0,#31
MOVNE R0,#0x02 ; Privileged Thread mode, use PSP
MOVEQ R0,#0x03 ; Unprivileged Thread mode, use PSP
MSR CONTROL,R0
BX LR
ALIGN
}
/*--------------------------- _alloc_box ------------------------------------*/
__asm void *_alloc_box (void *box_mem) {
/* Function wrapper for Unprivileged/Privileged mode. */
LDR R12,=__cpp(rt_alloc_box)
MRS R3,IPSR
LSLS R3,#24
BXNE R12
MRS R3,CONTROL
LSLS R3,#31
BXEQ R12
SVC 0
BX LR
ALIGN
}
/*--------------------------- _free_box -------------------------------------*/
__asm U32 _free_box (void *box_mem, void *box) {
/* Function wrapper for Unprivileged/Privileged mode. */
LDR R12,=__cpp(rt_free_box)
MRS R3,IPSR
LSLS R3,#24
BXNE R12
MRS R3,CONTROL
LSLS R3,#31
BXEQ R12
SVC 0
BX LR
ALIGN
}
/*-------------------------- SVC_Handler ------------------------------------*/
__asm void SVC_Handler (void) {
PRESERVE8
IMPORT SVC_Count
IMPORT SVC_Table
IMPORT rt_stk_check
#ifdef IFX_XMC4XXX
EXPORT SVC_Handler_Veneer
SVC_Handler_Veneer
#endif
MRS R0,PSP ; Read PSP
LDR R1,[R0,#24] ; Read Saved PC from Stack
LDRB R1,[R1,#-2] ; Load SVC Number
CBNZ R1,SVC_User
LDM R0,{R0-R3,R12} ; Read R0-R3,R12 from stack
BLX R12 ; Call SVC Function
MRS R12,PSP ; Read PSP
STM R12,{R0-R2} ; Store return values
LDR R3,=__cpp(&os_tsk)
LDM R3,{R1,R2} ; os_tsk.run, os_tsk.next
CMP R1,R2
BEQ SVC_Exit ; no task switch
CBZ R1,SVC_Next ; Runtask deleted?
STMDB R12!,{R4-R11} ; Save Old context
STR R12,[R1,#TCB_TSTACK] ; Update os_tsk.run->tsk_stack
PUSH {R2,R3}
BL rt_stk_check ; Check for Stack overflow
POP {R2,R3}
SVC_Next
STR R2,[R3] ; os_tsk.run = os_tsk.next
LDR R12,[R2,#TCB_TSTACK] ; os_tsk.next->tsk_stack
LDMIA R12!,{R4-R11} ; Restore New Context
MSR PSP,R12 ; Write PSP
SVC_Exit
MVN LR,#:NOT:0xFFFFFFFD ; set EXC_RETURN value
#ifdef IFX_XMC4XXX
PUSH {LR}
POP {PC}
#else
BX LR
#endif
/*------------------- User SVC ------------------------------*/
SVC_User
PUSH {R4,LR} ; Save Registers
LDR R2,=SVC_Count
LDR R2,[R2]
CMP R1,R2
BHI SVC_Done ; Overflow
LDR R4,=SVC_Table-4
LDR R4,[R4,R1,LSL #2] ; Load SVC Function Address
LDM R0,{R0-R3,R12} ; Read R0-R3,R12 from stack
BLX R4 ; Call SVC Function
MRS R12,PSP
STM R12,{R0-R3} ; Function return values
SVC_Done
POP {R4,PC} ; RETI
ALIGN
}
/*-------------------------- PendSV_Handler ---------------------------------*/
__asm void PendSV_Handler (void) {
PRESERVE8
#ifdef IFX_XMC4XXX
EXPORT PendSV_Handler_Veneer
PendSV_Handler_Veneer
#endif
BL __cpp(rt_pop_req)
Sys_Switch
LDR R3,=__cpp(&os_tsk)
LDM R3,{R1,R2} ; os_tsk.run, os_tsk.next
CMP R1,R2
BEQ Sys_Exit
MRS R12,PSP ; Read PSP
STMDB R12!,{R4-R11} ; Save Old context
STR R12,[R1,#TCB_TSTACK] ; Update os_tsk.run->tsk_stack
PUSH {R2,R3}
BL rt_stk_check ; Check for Stack overflow
POP {R2,R3}
STR R2,[R3] ; os_tsk.run = os_tsk.next
LDR R12,[R2,#TCB_TSTACK] ; os_tsk.next->tsk_stack
LDMIA R12!,{R4-R11} ; Restore New Context
MSR PSP,R12 ; Write PSP
Sys_Exit
MVN LR,#:NOT:0xFFFFFFFD ; set EXC_RETURN value
#ifdef IFX_XMC4XXX
PUSH {LR}
POP {PC}
#else
BX LR ; Return to Thread Mode
#endif
ALIGN
}
/*-------------------------- SysTick_Handler --------------------------------*/
__asm void SysTick_Handler (void) {
PRESERVE8
#ifdef IFX_XMC4XXX
EXPORT SysTick_Handler_Veneer
SysTick_Handler_Veneer
#endif
BL __cpp(rt_systick)
B Sys_Switch
ALIGN
}
/*-------------------------- OS_Tick_Handler --------------------------------*/
__asm void OS_Tick_Handler (void) {
PRESERVE8
BL __cpp(os_tick_irqack)
BL __cpp(rt_systick)
B Sys_Switch
ALIGN
}
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/ARM/HAL_CM3.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 1,799 |
```c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: HAL_CM0.C
* Purpose: Hardware Abstraction Layer for Cortex-M0
* Rev.: V4.70
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#include "rt_TypeDef.h"
#include "RTX_Config.h"
#include "rt_System.h"
#include "rt_HAL_CM.h"
#include "rt_Task.h"
#include "rt_MemBox.h"
/*your_sha256_hash------------
* Functions
*your_sha256_hash-----------*/
/*--------------------------- rt_set_PSP ------------------------------------*/
__asm void rt_set_PSP (U32 stack) {
MSR PSP,R0
BX LR
}
/*--------------------------- rt_get_PSP ------------------------------------*/
__asm U32 rt_get_PSP (void) {
MRS R0,PSP
BX LR
}
/*--------------------------- os_set_env ------------------------------------*/
__asm void os_set_env (void) {
/* Switch to Unprivileged/Privileged Thread mode, use PSP. */
MOV R0,SP ; PSP = MSP
MSR PSP,R0
LDR R0,=__cpp(&os_flags)
LDRB R0,[R0]
LSLS R0,#31
BNE PrivilegedE
MOVS R0,#0x03 ; Unprivileged Thread mode, use PSP
MSR CONTROL,R0
BX LR
PrivilegedE
MOVS R0,#0x02 ; Privileged Thread mode, use PSP
MSR CONTROL,R0
BX LR
ALIGN
}
/*--------------------------- _alloc_box ------------------------------------*/
__asm void *_alloc_box (void *box_mem) {
/* Function wrapper for Unprivileged/Privileged mode. */
LDR R3,=__cpp(rt_alloc_box)
MOV R12,R3
MRS R3,IPSR
LSLS R3,#24
BNE PrivilegedA
MRS R3,CONTROL
LSLS R3,#31
BEQ PrivilegedA
SVC 0
BX LR
PrivilegedA
BX R12
ALIGN
}
/*--------------------------- _free_box -------------------------------------*/
__asm U32 _free_box (void *box_mem, void *box) {
/* Function wrapper for Unprivileged/Privileged mode. */
LDR R3,=__cpp(rt_free_box)
MOV R12,R3
MRS R3,IPSR
LSLS R3,#24
BNE PrivilegedF
MRS R3,CONTROL
LSLS R3,#31
BEQ PrivilegedF
SVC 0
BX LR
PrivilegedF
BX R12
ALIGN
}
/*-------------------------- SVC_Handler ------------------------------------*/
__asm void SVC_Handler (void) {
PRESERVE8
IMPORT SVC_Count
IMPORT SVC_Table
IMPORT rt_stk_check
MRS R0,PSP ; Read PSP
LDR R1,[R0,#24] ; Read Saved PC from Stack
SUBS R1,R1,#2 ; Point to SVC Instruction
LDRB R1,[R1] ; Load SVC Number
CMP R1,#0
BNE SVC_User ; User SVC Number > 0
MOV LR,R4
LDMIA R0,{R0-R3,R4} ; Read R0-R3,R12 from stack
MOV R12,R4
MOV R4,LR
BLX R12 ; Call SVC Function
MRS R3,PSP ; Read PSP
STMIA R3!,{R0-R2} ; Store return values
LDR R3,=__cpp(&os_tsk)
LDMIA R3!,{R1,R2} ; os_tsk.run, os_tsk.next
CMP R1,R2
BEQ SVC_Exit ; no task switch
SUBS R3,#8
CMP R1,#0 ; Runtask deleted?
BEQ SVC_Next
MRS R0,PSP ; Read PSP
SUBS R0,R0,#32 ; Adjust Start Address
STR R0,[R1,#TCB_TSTACK] ; Update os_tsk.run->tsk_stack
STMIA R0!,{R4-R7} ; Save old context (R4-R7)
MOV R4,R8
MOV R5,R9
MOV R6,R10
MOV R7,R11
STMIA R0!,{R4-R7} ; Save old context (R8-R11)
PUSH {R2,R3}
BL rt_stk_check ; Check for Stack overflow
POP {R2,R3}
SVC_Next
STR R2,[R3] ; os_tsk.run = os_tsk.next
LDR R0,[R2,#TCB_TSTACK] ; os_tsk.next->tsk_stack
ADDS R0,R0,#16 ; Adjust Start Address
LDMIA R0!,{R4-R7} ; Restore new Context (R8-R11)
MOV R8,R4
MOV R9,R5
MOV R10,R6
MOV R11,R7
MSR PSP,R0 ; Write PSP
SUBS R0,R0,#32 ; Adjust Start Address
LDMIA R0!,{R4-R7} ; Restore new Context (R4-R7)
SVC_Exit
MOVS R0,#:NOT:0xFFFFFFFD ; Set EXC_RETURN value
MVNS R0,R0
BX R0 ; RETI to Thread Mode, use PSP
/*------------------- User SVC ------------------------------*/
SVC_User
PUSH {R4,LR} ; Save Registers
LDR R2,=SVC_Count
LDR R2,[R2]
CMP R1,R2
BHI SVC_Done ; Overflow
LDR R4,=SVC_Table-4
LSLS R1,R1,#2
LDR R4,[R4,R1] ; Load SVC Function Address
MOV LR,R4
LDMIA R0,{R0-R3,R4} ; Read R0-R3,R12 from stack
MOV R12,R4
BLX LR ; Call SVC Function
MRS R4,PSP ; Read PSP
STMIA R4!,{R0-R3} ; Function return values
SVC_Done
POP {R4,PC} ; RETI
ALIGN
}
/*-------------------------- PendSV_Handler ---------------------------------*/
__asm void PendSV_Handler (void) {
PRESERVE8
BL __cpp(rt_pop_req)
Sys_Switch
LDR R3,=__cpp(&os_tsk)
LDMIA R3!,{R1,R2} ; os_tsk.run, os_tsk.next
CMP R1,R2
BEQ Sys_Exit ; no task switch
SUBS R3,#8
MRS R0,PSP ; Read PSP
SUBS R0,R0,#32 ; Adjust Start Address
STR R0,[R1,#TCB_TSTACK] ; Update os_tsk.run->tsk_stack
STMIA R0!,{R4-R7} ; Save old context (R4-R7)
MOV R4,R8
MOV R5,R9
MOV R6,R10
MOV R7,R11
STMIA R0!,{R4-R7} ; Save old context (R8-R11)
PUSH {R2,R3}
BL rt_stk_check ; Check for Stack overflow
POP {R2,R3}
STR R2,[R3] ; os_tsk.run = os_tsk.next
LDR R0,[R2,#TCB_TSTACK] ; os_tsk.next->tsk_stack
ADDS R0,R0,#16 ; Adjust Start Address
LDMIA R0!,{R4-R7} ; Restore new Context (R8-R11)
MOV R8,R4
MOV R9,R5
MOV R10,R6
MOV R11,R7
MSR PSP,R0 ; Write PSP
SUBS R0,R0,#32 ; Adjust Start Address
LDMIA R0!,{R4-R7} ; Restore new Context (R4-R7)
Sys_Exit
MOVS R0,#:NOT:0xFFFFFFFD ; Set EXC_RETURN value
MVNS R0,R0
BX R0 ; RETI to Thread Mode, use PSP
ALIGN
}
/*-------------------------- SysTick_Handler --------------------------------*/
__asm void SysTick_Handler (void) {
PRESERVE8
BL __cpp(rt_systick)
B Sys_Switch
ALIGN
}
/*-------------------------- OS_Tick_Handler --------------------------------*/
__asm void OS_Tick_Handler (void) {
PRESERVE8
BL __cpp(os_tick_irqack)
BL __cpp(rt_systick)
B Sys_Switch
ALIGN
}
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/ARM/HAL_CM0.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 2,233 |
```c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: HAL_CM4.C
* Purpose: Hardware Abstraction Layer for Cortex-M4
* Rev.: V4.79
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#include "rt_TypeDef.h"
#include "RTX_Config.h"
#include "rt_System.h"
#include "rt_HAL_CM.h"
#include "rt_Task.h"
#include "rt_MemBox.h"
/*your_sha256_hash------------
* Functions
*your_sha256_hash-----------*/
/*--------------------------- rt_set_PSP ------------------------------------*/
__asm void rt_set_PSP (U32 stack) {
MSR PSP,R0
BX LR
}
/*--------------------------- rt_get_PSP ------------------------------------*/
__asm U32 rt_get_PSP (void) {
MRS R0,PSP
BX LR
}
/*--------------------------- os_set_env ------------------------------------*/
__asm void os_set_env (void) {
/* Switch to Unprivileged/Privileged Thread mode, use PSP. */
MOV R0,SP ; PSP = MSP
MSR PSP,R0
LDR R0,=__cpp(&os_flags)
LDRB R0,[R0]
LSLS R0,#31
MOVNE R0,#0x02 ; Privileged Thread mode, use PSP
MOVEQ R0,#0x03 ; Unprivileged Thread mode, use PSP
MSR CONTROL,R0
BX LR
ALIGN
}
/*--------------------------- _alloc_box ------------------------------------*/
__asm void *_alloc_box (void *box_mem) {
/* Function wrapper for Unprivileged/Privileged mode. */
LDR R12,=__cpp(rt_alloc_box)
MRS R3,IPSR
LSLS R3,#24
BXNE R12
MRS R3,CONTROL
LSLS R3,#31
BXEQ R12
SVC 0
BX LR
ALIGN
}
/*--------------------------- _free_box -------------------------------------*/
__asm U32 _free_box (void *box_mem, void *box) {
/* Function wrapper for Unprivileged/Privileged mode. */
LDR R12,=__cpp(rt_free_box)
MRS R3,IPSR
LSLS R3,#24
BXNE R12
MRS R3,CONTROL
LSLS R3,#31
BXEQ R12
SVC 0
BX LR
ALIGN
}
/*-------------------------- SVC_Handler ------------------------------------*/
__asm void SVC_Handler (void) {
PRESERVE8
IMPORT SVC_Count
IMPORT SVC_Table
IMPORT rt_stk_check
#ifdef IFX_XMC4XXX
EXPORT SVC_Handler_Veneer
SVC_Handler_Veneer
#endif
MRS R0,PSP ; Read PSP
LDR R1,[R0,#24] ; Read Saved PC from Stack
LDRB R1,[R1,#-2] ; Load SVC Number
CBNZ R1,SVC_User
LDM R0,{R0-R3,R12} ; Read R0-R3,R12 from stack
PUSH {R4,LR} ; Save EXC_RETURN
BLX R12 ; Call SVC Function
POP {R4,LR} ; Restore EXC_RETURN
MRS R12,PSP ; Read PSP
STM R12,{R0-R2} ; Store return values
LDR R3,=__cpp(&os_tsk)
LDM R3,{R1,R2} ; os_tsk.run, os_tsk.next
CMP R1,R2
#ifdef IFX_XMC4XXX
PUSHEQ {LR}
POPEQ {PC}
#else
BXEQ LR ; RETI, no task switch
#endif
CBNZ R1,SVC_ContextSave ; Runtask not deleted?
TST LR,#0x10 ; is it extended frame?
BNE SVC_ContextRestore
LDR R1,=0xE000EF34
LDR R0,[R1] ; Load FPCCR
BIC R0,#1 ; Clear LSPACT (Lazy state)
STR R0,[R1] ; Store FPCCR
B SVC_ContextRestore
SVC_ContextSave
TST LR,#0x10 ; is it extended frame?
VSTMDBEQ R12!,{S16-S31} ; yes, stack also VFP hi-regs
MOVEQ R0,#0x01 ; os_tsk->stack_frame val
MOVNE R0,#0x00
STRB R0,[R1,#TCB_STACKF] ; os_tsk.run->stack_frame = val
STMDB R12!,{R4-R11} ; Save Old context
STR R12,[R1,#TCB_TSTACK] ; Update os_tsk.run->tsk_stack
PUSH {R2,R3}
BL rt_stk_check ; Check for Stack overflow
POP {R2,R3}
SVC_ContextRestore
STR R2,[R3] ; os_tsk.run = os_tsk.next
LDR R12,[R2,#TCB_TSTACK] ; os_tsk.next->tsk_stack
LDMIA R12!,{R4-R11} ; Restore New Context
LDRB R0,[R2,#TCB_STACKF] ; Stack Frame
CMP R0,#0 ; Basic/Extended Stack Frame
MVNEQ LR,#:NOT:0xFFFFFFFD ; set EXC_RETURN value
MVNNE LR,#:NOT:0xFFFFFFED
VLDMIANE R12!,{S16-S31} ; restore VFP hi-registers
MSR PSP,R12 ; Write PSP
SVC_Exit
#ifdef IFX_XMC4XXX
PUSH {LR}
POP {PC}
#else
BX LR
#endif
/*------------------- User SVC ------------------------------*/
SVC_User
PUSH {R4,LR} ; Save Registers
LDR R2,=SVC_Count
LDR R2,[R2]
CMP R1,R2
BHI SVC_Done ; Overflow
LDR R4,=SVC_Table-4
LDR R4,[R4,R1,LSL #2] ; Load SVC Function Address
LDM R0,{R0-R3,R12} ; Read R0-R3,R12 from stack
BLX R4 ; Call SVC Function
MRS R12,PSP
STM R12,{R0-R3} ; Function return values
SVC_Done
POP {R4,PC} ; RETI
ALIGN
}
/*-------------------------- PendSV_Handler ---------------------------------*/
__asm void PendSV_Handler (void) {
PRESERVE8
#ifdef IFX_XMC4XXX
EXPORT PendSV_Handler_Veneer
PendSV_Handler_Veneer
#endif
PUSH {R4,LR} ; Save EXC_RETURN
BL __cpp(rt_pop_req)
Sys_Switch
POP {R4,LR} ; Restore EXC_RETURN
LDR R3,=__cpp(&os_tsk)
LDM R3,{R1,R2} ; os_tsk.run, os_tsk.next
CMP R1,R2
#ifdef IFX_XMC4XXX
PUSHEQ {LR}
POPEQ {PC}
#else
BXEQ LR ; RETI, no task switch
#endif
MRS R12,PSP ; Read PSP
TST LR,#0x10 ; is it extended frame?
VSTMDBEQ R12!,{S16-S31} ; yes, stack also VFP hi-regs
MOVEQ R0,#0x01 ; os_tsk->stack_frame val
MOVNE R0,#0x00
STRB R0,[R1,#TCB_STACKF] ; os_tsk.run->stack_frame = val
STMDB R12!,{R4-R11} ; Save Old context
STR R12,[R1,#TCB_TSTACK] ; Update os_tsk.run->tsk_stack
PUSH {R2,R3}
BL rt_stk_check ; Check for Stack overflow
POP {R2,R3}
STR R2,[R3] ; os_tsk.run = os_tsk.next
LDR R12,[R2,#TCB_TSTACK] ; os_tsk.next->tsk_stack
LDMIA R12!,{R4-R11} ; Restore New Context
LDRB R0,[R2,#TCB_STACKF] ; Stack Frame
CMP R0,#0 ; Basic/Extended Stack Frame
MVNEQ LR,#:NOT:0xFFFFFFFD ; set EXC_RETURN value
MVNNE LR,#:NOT:0xFFFFFFED
VLDMIANE R12!,{S16-S31} ; restore VFP hi-regs
MSR PSP,R12 ; Write PSP
Sys_Exit
#ifdef IFX_XMC4XXX
PUSH {LR}
POP {PC}
#else
BX LR ; Return to Thread Mode
#endif
ALIGN
}
/*-------------------------- SysTick_Handler --------------------------------*/
__asm void SysTick_Handler (void) {
PRESERVE8
#ifdef IFX_XMC4XXX
EXPORT SysTick_Handler_Veneer
SysTick_Handler_Veneer
#endif
PUSH {R4,LR} ; Save EXC_RETURN
BL __cpp(rt_systick)
B Sys_Switch
ALIGN
}
/*-------------------------- OS_Tick_Handler --------------------------------*/
__asm void OS_Tick_Handler (void) {
PRESERVE8
PUSH {R4,LR} ; Save EXC_RETURN
BL __cpp(os_tick_irqack)
BL __cpp(rt_systick)
B Sys_Switch
ALIGN
}
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/ARM/HAL_CM4.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 2,409 |
```gas
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: HAL_CM4.S
* Purpose: Hardware Abstraction Layer for Cortex-M4
* Rev.: V4.79
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
NAME HAL_CM4.S
#define TCB_STACKF 37
#define TCB_TSTACK 40
EXTERN os_flags
EXTERN os_tsk
EXTERN rt_alloc_box
EXTERN rt_free_box
EXTERN rt_stk_check
EXTERN rt_pop_req
EXTERN rt_systick
EXTERN os_tick_irqack
EXTERN SVC_Table
EXTERN SVC_Count
/*your_sha256_hash------------
* Functions
*your_sha256_hash-----------*/
SECTION .text:CODE:NOROOT(2)
THUMB
/*--------------------------- rt_set_PSP ------------------------------------*/
; void rt_set_PSP (U32 stack);
PUBLIC rt_set_PSP
rt_set_PSP:
MSR PSP,R0
BX LR
/*--------------------------- rt_get_PSP ------------------------------------*/
; U32 rt_get_PSP (void);
PUBLIC rt_get_PSP
rt_get_PSP:
MRS R0,PSP
BX LR
/*--------------------------- os_set_env ------------------------------------*/
; void os_set_env (void);
/* Switch to Unprivileged/Privileged Thread mode, use PSP. */
PUBLIC os_set_env
os_set_env:
MOV R0,SP /* PSP = MSP */
MSR PSP,R0
LDR R0,=os_flags
LDRB R0,[R0]
LSLS R0,#31
ITE NE
MOVNE R0,#0x02 /* Privileged Thread mode, use PSP */
MOVEQ R0,#0x03 /* Unprivileged Thread mode, use PSP */
MSR CONTROL,R0
BX LR
/*--------------------------- _alloc_box ------------------------------------*/
; void *_alloc_box (void *box_mem);
/* Function wrapper for Unprivileged/Privileged mode. */
PUBLIC _alloc_box
_alloc_box:
LDR R12,=rt_alloc_box
MRS R3,IPSR
LSLS R3,#24
IT NE
BXNE R12
MRS R3,CONTROL
LSLS R3,#31
IT EQ
BXEQ R12
SVC 0
BX LR
/*--------------------------- _free_box -------------------------------------*/
; U32 _free_box (void *box_mem, void *box);
/* Function wrapper for Unprivileged/Privileged mode. */
PUBLIC _free_box
_free_box:
LDR R12,=rt_free_box
MRS R3,IPSR
LSLS R3,#24
IT NE
BXNE R12
MRS R3,CONTROL
LSLS R3,#31
IT EQ
BXEQ R12
SVC 0
BX LR
/*-------------------------- SVC_Handler ------------------------------------*/
; void SVC_Handler (void);
PUBLIC SVC_Handler
SVC_Handler:
MRS R0,PSP /* Read PSP */
LDR R1,[R0,#24] /* Read Saved PC from Stack */
LDRB R1,[R1,#-2] /* Load SVC Number */
CBNZ R1,SVC_User
LDM R0,{R0-R3,R12} /* Read R0-R3,R12 from stack */
PUSH {R4,LR} /* Save EXC_RETURN */
BLX R12 /* Call SVC Function */
POP {R4,LR} /* Restore EXC_RETURN */
MRS R12,PSP /* Read PSP */
STM R12,{R0-R2} /* Store return values */
LDR R3,=os_tsk
LDM R3,{R1,R2} /* os_tsk.run, os_tsk.next */
CMP R1,R2
IT EQ
BXEQ LR /* RETI, no task switch */
CBNZ R1,SVC_ContextSave /* Runtask not deleted? */
TST LR,#0x10 /* is it extended frame? */
BNE SVC_ContextRestore
LDR R1,=0xE000EF34
LDR R0,[R1] /* Load FPCCR */
BIC R0,R0,#1 /* Clear LSPACT (Lazy state) */
STR R0,[R1] /* Store FPCCR */
B SVC_ContextRestore
SVC_ContextSave:
TST LR,#0x10 /* is it extended frame? */
ITTE EQ
VSTMDBEQ R12!,{S16-S31} /* yes, stack also VFP hi-regs */
MOVEQ R0,#0x01 /* os_tsk->stack_frame val */
MOVNE R0,#0x00
STRB R0,[R1,#TCB_STACKF] /* os_tsk.run->stack_frame = val */
STMDB R12!,{R4-R11} /* Save Old context */
STR R12,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */
PUSH {R2,R3}
BL rt_stk_check /* Check for Stack overflow */
POP {R2,R3}
SVC_ContextRestore:
STR R2,[R3] /* os_tsk.run = os_tsk.next */
LDR R12,[R2,#TCB_TSTACK] /* os_tsk.next->tsk_stack */
LDMIA R12!,{R4-R11} /* Restore New Context */
LDRB R0,[R2,#TCB_STACKF] /* Stack Frame */
CMP R0,#0 /* Basic/Extended Stack Frame */
ITEE EQ
MVNEQ LR,#~0xFFFFFFFD /* set EXC_RETURN value */
MVNNE LR,#~0xFFFFFFED
VLDMIANE R12!,{S16-S31} /* restore VFP hi-registers */
MSR PSP,R12 /* Write PSP */
SVC_Exit:
BX LR
/*------------------- User SVC ------------------------------*/
SVC_User:
PUSH {R4,LR} /* Save Registers */
LDR R2,=SVC_Count
LDR R2,[R2]
CMP R1,R2
BHI SVC_Done /* Overflow */
LDR R4,=SVC_Table-4
LDR R4,[R4,R1,LSL #2] /* Load SVC Function Address */
LDM R0,{R0-R3,R12} /* Read R0-R3,R12 from stack */
BLX R4 /* Call SVC Function */
MRS R12,PSP
STM R12,{R0-R3} /* Function return values */
SVC_Done:
POP {R4,PC} /* RETI */
/*-------------------------- PendSV_Handler ---------------------------------*/
; void PendSV_Handler (void);
PUBLIC PendSV_Handler
PendSV_Handler:
PUSH {R4,LR} /* Save EXC_RETURN */
BL rt_pop_req
Sys_Switch:
POP {R4,LR} /* Restore EXC_RETURN */
LDR R3,=os_tsk
LDM R3,{R1,R2} /* os_tsk.run, os_tsk.next */
CMP R1,R2
IT EQ
BXEQ LR /* RETI, no task switch */
MRS R12,PSP /* Read PSP */
TST LR,#0x10 /* is it extended frame? */
ITTE EQ
VSTMDBEQ R12!,{S16-S31} /* yes, stack also VFP hi-regs */
MOVEQ R0,#0x01 /* os_tsk->stack_frame val */
MOVNE R0,#0x00
STRB R0,[R1,#TCB_STACKF] /* os_tsk.run->stack_frame = val */
STMDB R12!,{R4-R11} /* Save Old context */
STR R12,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */
PUSH {R2,R3}
BL rt_stk_check /* Check for Stack overflow */
POP {R2,R3}
STR R2,[R3] /* os_tsk.run = os_tsk.next */
LDR R12,[R2,#TCB_TSTACK] /* os_tsk.next->tsk_stack */
LDMIA R12!,{R4-R11} /* Restore New Context */
LDRB R0,[R2,#TCB_STACKF] /* Stack Frame */
CMP R0,#0 /* Basic/Extended Stack Frame */
ITEE EQ
MVNEQ LR,#~0xFFFFFFFD /* set EXC_RETURN value */
MVNNE LR,#~0xFFFFFFED
VLDMIANE R12!,{S16-S31} /* restore VFP hi-registers */
MSR PSP,R12 /* Write PSP */
Sys_Exit:
BX LR /* Return to Thread Mode */
/*-------------------------- SysTick_Handler --------------------------------*/
; void SysTick_Handler (void);
PUBLIC SysTick_Handler
SysTick_Handler:
PUSH {R4,LR} /* Save EXC_RETURN */
BL rt_systick
B Sys_Switch
/*-------------------------- OS_Tick_Handler --------------------------------*/
; void OS_Tick_Handler (void);
PUBLIC OS_Tick_Handler
OS_Tick_Handler:
PUSH {R4,LR} /* Save EXC_RETURN */
BL os_tick_irqack
BL rt_systick
B Sys_Switch
END
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/IAR/HAL_CM4.s | gas | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 2,368 |
```gas
;/*your_sha256_hash------------
; * CMSIS-RTOS - RTX
; *your_sha256_hash------------
; * Name: SVC_TABLE.S
; * Purpose: Pre-defined SVC Table for Cortex-M
; * Rev.: V4.70
; *your_sha256_hash------------
; *
; * All rights reserved.
; *
; *
; *
; * www.apache.org/licenses/LICENSE-2.0
; *
; * Unless required by applicable law or agreed to in writing, software
; * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; *your_sha256_hash-----------*/
NAME SVC_TABLE
SECTION .text:CONST (2)
PUBLIC SVC_Count
SVC_Cnt EQU (SVC_End-SVC_Table)/4
SVC_Count DCD SVC_Cnt
; Import user SVC functions here.
; IMPORT __SVC_1
PUBLIC SVC_Table
SVC_Table
; Insert user SVC functions here. SVC 0 used by RTL Kernel.
; DCD __SVC_1 ; user SVC function
SVC_End
END
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/IAR/SVC_Table.s | gas | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 265 |
```gas
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: HAL_CM3.S
* Purpose: Hardware Abstraction Layer for Cortex-M3
* Rev.: V4.70
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
NAME HAL_CM3.S
#define TCB_TSTACK 40
EXTERN os_flags
EXTERN os_tsk
EXTERN rt_alloc_box
EXTERN rt_free_box
EXTERN rt_stk_check
EXTERN rt_pop_req
EXTERN rt_systick
EXTERN os_tick_irqack
EXTERN SVC_Table
EXTERN SVC_Count
/*your_sha256_hash------------
* Functions
*your_sha256_hash-----------*/
SECTION .text:CODE:NOROOT(2)
THUMB
/*--------------------------- rt_set_PSP ------------------------------------*/
; void rt_set_PSP (U32 stack);
PUBLIC rt_set_PSP
rt_set_PSP:
MSR PSP,R0
BX LR
/*--------------------------- rt_get_PSP ------------------------------------*/
; U32 rt_get_PSP (void);
PUBLIC rt_get_PSP
rt_get_PSP:
MRS R0,PSP
BX LR
/*--------------------------- os_set_env ------------------------------------*/
; void os_set_env (void);
/* Switch to Unprivileged/Privileged Thread mode, use PSP. */
PUBLIC os_set_env
os_set_env:
MOV R0,SP /* PSP = MSP */
MSR PSP,R0
LDR R0,=os_flags
LDRB R0,[R0]
LSLS R0,#31
ITE NE
MOVNE R0,#0x02 /* Privileged Thread mode, use PSP */
MOVEQ R0,#0x03 /* Unprivileged Thread mode, use PSP */
MSR CONTROL,R0
BX LR
/*--------------------------- _alloc_box ------------------------------------*/
; void *_alloc_box (void *box_mem);
/* Function wrapper for Unprivileged/Privileged mode. */
PUBLIC _alloc_box
_alloc_box:
LDR R12,=rt_alloc_box
MRS R3,IPSR
LSLS R3,#24
IT NE
BXNE R12
MRS R3,CONTROL
LSLS R3,#31
IT EQ
BXEQ R12
SVC 0
BX LR
/*--------------------------- _free_box -------------------------------------*/
; U32 _free_box (void *box_mem, void *box);
/* Function wrapper for Unprivileged/Privileged mode. */
PUBLIC _free_box
_free_box:
LDR R12,=rt_free_box
MRS R3,IPSR
LSLS R3,#24
IT NE
BXNE R12
MRS R3,CONTROL
LSLS R3,#31
IT EQ
BXEQ R12
SVC 0
BX LR
/*-------------------------- SVC_Handler ------------------------------------*/
; void SVC_Handler (void);
PUBLIC SVC_Handler
SVC_Handler:
MRS R0,PSP /* Read PSP */
LDR R1,[R0,#24] /* Read Saved PC from Stack */
LDRB R1,[R1,#-2] /* Load SVC Number */
CBNZ R1,SVC_User
LDM R0,{R0-R3,R12} /* Read R0-R3,R12 from stack */
BLX R12 /* Call SVC Function */
MRS R12,PSP /* Read PSP */
STM R12,{R0-R2} /* Store return values */
LDR R3,=os_tsk
LDM R3,{R1,R2} /* os_tsk.run, os_tsk.next */
CMP R1,R2
BEQ SVC_Exit /* no task switch */
CBZ R1,SVC_Next /* Runtask deleted? */
STMDB R12!,{R4-R11} /* Save Old context */
STR R12,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */
PUSH {R2,R3}
BL rt_stk_check /* Check for Stack overflow */
POP {R2,R3}
SVC_Next:
STR R2,[R3] /* os_tsk.run = os_tsk.next */
LDR R12,[R2,#TCB_TSTACK] /* os_tsk.next->tsk_stack */
LDMIA R12!,{R4-R11} /* Restore New Context */
MSR PSP,R12 /* Write PSP */
SVC_Exit:
MVN LR,#~0xFFFFFFFD /* set EXC_RETURN value */
BX LR
/*------------------- User SVC ------------------------------*/
SVC_User:
PUSH {R4,LR} /* Save Registers */
LDR R2,=SVC_Count
LDR R2,[R2]
CMP R1,R2
BHI SVC_Done /* Overflow */
LDR R4,=SVC_Table-4
LDR R4,[R4,R1,LSL #2] /* Load SVC Function Address */
LDM R0,{R0-R3,R12} /* Read R0-R3,R12 from stack */
BLX R4 /* Call SVC Function */
MRS R12,PSP
STM R12,{R0-R3} /* Function return values */
SVC_Done:
POP {R4,PC} /* RETI */
/*-------------------------- PendSV_Handler ---------------------------------*/
; void PendSV_Handler (void);
PUBLIC PendSV_Handler
PendSV_Handler:
BL rt_pop_req
Sys_Switch:
LDR R3,=os_tsk
LDM R3,{R1,R2} /* os_tsk.run, os_tsk.next */
CMP R1,R2
BEQ Sys_Exit
MRS R12,PSP /* Read PSP */
STMDB R12!,{R4-R11} /* Save Old context */
STR R12,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */
PUSH {R2,R3}
BL rt_stk_check /* Check for Stack overflow */
POP {R2,R3}
STR R2,[R3] /* os_tsk.run = os_tsk.next */
LDR R12,[R2,#TCB_TSTACK] /* os_tsk.next->tsk_stack */
LDMIA R12!,{R4-R11} /* Restore New Context */
MSR PSP,R12 /* Write PSP */
Sys_Exit:
MVN LR,#~0xFFFFFFFD /* set EXC_RETURN value */
BX LR /* Return to Thread Mode */
/*-------------------------- SysTick_Handler --------------------------------*/
; void SysTick_Handler (void);
PUBLIC SysTick_Handler
SysTick_Handler:
BL rt_systick
B Sys_Switch
/*-------------------------- OS_Tick_Handler --------------------------------*/
; void OS_Tick_Handler (void);
PUBLIC OS_Tick_Handler
OS_Tick_Handler:
BL os_tick_irqack
BL rt_systick
B Sys_Switch
END
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/IAR/HAL_CM3.s | gas | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 1,770 |
```gas
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: HAL_CM0.S
* Purpose: Hardware Abstraction Layer for Cortex-M0
* Rev.: V4.70
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
NAME HAL_CM0.S
#define TCB_TSTACK 40
EXTERN os_flags
EXTERN os_tsk
EXTERN rt_alloc_box
EXTERN rt_free_box
EXTERN rt_stk_check
EXTERN rt_pop_req
EXTERN rt_systick
EXTERN os_tick_irqack
EXTERN SVC_Table
EXTERN SVC_Count
/*your_sha256_hash------------
* Functions
*your_sha256_hash-----------*/
SECTION .text:CODE:NOROOT(2)
THUMB
/*--------------------------- rt_set_PSP ------------------------------------*/
; void rt_set_PSP (U32 stack);
PUBLIC rt_set_PSP
rt_set_PSP:
MSR PSP,R0
BX LR
/*--------------------------- rt_get_PSP ------------------------------------*/
; U32 rt_get_PSP (void);
PUBLIC rt_get_PSP
rt_get_PSP:
MRS R0,PSP
BX LR
/*--------------------------- os_set_env ------------------------------------*/
; void os_set_env (void);
/* Switch to Unprivileged/Privileged Thread mode, use PSP. */
PUBLIC os_set_env
os_set_env:
MOV R0,SP /* PSP = MSP */
MSR PSP,R0
LDR R0,=os_flags
LDRB R0,[R0]
LSLS R0,#31
BNE PrivilegedE
MOVS R0,#0x03 /* Unprivileged Thread mode, use PSP */
MSR CONTROL,R0
BX LR
PrivilegedE:
MOVS R0,#0x02 /* Privileged Thread mode, use PSP */
MSR CONTROL,R0
BX LR
/*--------------------------- _alloc_box ------------------------------------*/
; void *_alloc_box (void *box_mem);
/* Function wrapper for Unprivileged/Privileged mode. */
PUBLIC _alloc_box
_alloc_box:
LDR R3,=rt_alloc_box
MOV R12,R3
MRS R3,IPSR
LSLS R3,#24
BNE PrivilegedA
MRS R3,CONTROL
LSLS R3,#31
BEQ PrivilegedA
SVC 0
BX LR
PrivilegedA:
BX R12
/*--------------------------- _free_box -------------------------------------*/
; U32 _free_box (void *box_mem, void *box);
/* Function wrapper for Unprivileged/Privileged mode. */
PUBLIC _free_box
_free_box:
LDR R3,=rt_free_box
MOV R12,R3
MRS R3,IPSR
LSLS R3,#24
BNE PrivilegedF
MRS R3,CONTROL
LSLS R3,#31
BEQ PrivilegedF
SVC 0
BX LR
PrivilegedF:
BX R12
/*-------------------------- SVC_Handler ------------------------------------*/
; void SVC_Handler (void);
PUBLIC SVC_Handler
SVC_Handler:
MRS R0,PSP /* Read PSP */
LDR R1,[R0,#24] /* Read Saved PC from Stack */
SUBS R1,R1,#2 /* Point to SVC Instruction */
LDRB R1,[R1] /* Load SVC Number */
CMP R1,#0
BNE SVC_User /* User SVC Number > 0 */
MOV LR,R4
LDMIA R0,{R0-R3,R4} /* Read R0-R3,R12 from stack */
MOV R12,R4
MOV R4,LR
BLX R12 /* Call SVC Function */
MRS R3,PSP /* Read PSP */
STMIA R3!,{R0-R2} /* Store return values */
LDR R3,=os_tsk
LDMIA R3!,{R1,R2} /* os_tsk.run, os_tsk.next */
CMP R1,R2
BEQ SVC_Exit /* no task switch */
SUBS R3,#8
CMP R1,#0 /* Runtask deleted? */
BEQ SVC_Next
MRS R0,PSP /* Read PSP */
SUBS R0,R0,#32 /* Adjust Start Address */
STR R0,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */
STMIA R0!,{R4-R7} /* Save old context (R4-R7) */
MOV R4,R8
MOV R5,R9
MOV R6,R10
MOV R7,R11
STMIA R0!,{R4-R7} /* Save old context (R8-R11) */
PUSH {R2,R3}
BL rt_stk_check /* Check for Stack overflow */
POP {R2,R3}
SVC_Next:
STR R2,[R3] /* os_tsk.run = os_tsk.next */
LDR R0,[R2,#TCB_TSTACK] /* os_tsk.next->tsk_stack */
ADDS R0,R0,#16 /* Adjust Start Address */
LDMIA R0!,{R4-R7} /* Restore new Context (R8-R11) */
MOV R8,R4
MOV R9,R5
MOV R10,R6
MOV R11,R7
MSR PSP,R0 /* Write PSP */
SUBS R0,R0,#32 /* Adjust Start Address */
LDMIA R0!,{R4-R7} /* Restore new Context (R4-R7) */
SVC_Exit:
MOVS R0,#~0xFFFFFFFD /* Set EXC_RETURN value */
MVNS R0,R0
BX R0 /* RETI to Thread Mode, use PSP */
/*------------------- User SVC ------------------------------*/
SVC_User:
PUSH {R4,LR} /* Save Registers */
LDR R2,=SVC_Count
LDR R2,[R2]
CMP R1,R2
BHI SVC_Done /* Overflow */
LDR R4,=SVC_Table-4
LSLS R1,R1,#2
LDR R4,[R4,R1] /* Load SVC Function Address */
MOV LR,R4
LDMIA R0,{R0-R3,R4} /* Read R0-R3,R12 from stack */
MOV R12,R4
BLX LR /* Call SVC Function */
MRS R4,PSP /* Read PSP */
STMIA R4!,{R0-R3} /* Function return values */
SVC_Done:
POP {R4,PC} /* RETI */
/*-------------------------- PendSV_Handler ---------------------------------*/
; void PendSV_Handler (void);
PUBLIC PendSV_Handler
PendSV_Handler:
BL rt_pop_req
Sys_Switch:
LDR R3,=os_tsk
LDMIA R3!,{R1,R2} /* os_tsk.run, os_tsk.next */
CMP R1,R2
BEQ Sys_Exit /* no task switch */
SUBS R3,#8
MRS R0,PSP /* Read PSP */
SUBS R0,R0,#32 /* Adjust Start Address */
STR R0,[R1,#TCB_TSTACK] /* Update os_tsk.run->tsk_stack */
STMIA R0!,{R4-R7} /* Save old context (R4-R7) */
MOV R4,R8
MOV R5,R9
MOV R6,R10
MOV R7,R11
STMIA R0!,{R4-R7} /* Save old context (R8-R11) */
PUSH {R2,R3}
BL rt_stk_check /* Check for Stack overflow */
POP {R2,R3}
STR R2,[R3] /* os_tsk.run = os_tsk.next */
LDR R0,[R2,#TCB_TSTACK] /* os_tsk.next->tsk_stack */
ADDS R0,R0,#16 /* Adjust Start Address */
LDMIA R0!,{R4-R7} /* Restore new Context (R8-R11) */
MOV R8,R4
MOV R9,R5
MOV R10,R6
MOV R11,R7
MSR PSP,R0 /* Write PSP */
SUBS R0,R0,#32 /* Adjust Start Address */
LDMIA R0!,{R4-R7} /* Restore new Context (R4-R7) */
Sys_Exit:
MOVS R0,#~0xFFFFFFFD /* Set EXC_RETURN value */
MVNS R0,R0
BX R0 /* RETI to Thread Mode, use PSP */
/*-------------------------- SysTick_Handler --------------------------------*/
; void SysTick_Handler (void);
PUBLIC SysTick_Handler
SysTick_Handler:
BL rt_systick
B Sys_Switch
/*-------------------------- OS_Tick_Handler --------------------------------*/
; void OS_Tick_Handler (void);
PUBLIC OS_Tick_Handler
OS_Tick_Handler:
BL os_tick_irqack
BL rt_systick
B Sys_Switch
END
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/SRC/IAR/HAL_CM0.s | gas | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 2,320 |
```c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RTX_Conf_CM.C
* Purpose: Configuration of CMSIS RTX Kernel for Cortex-M
* Rev.: V4.70.1
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#include "cmsis_os.h"
/*your_sha256_hash------------
* RTX User configuration part BEGIN
*your_sha256_hash-----------*/
//-------- <<< Use Configuration Wizard in Context Menu >>> -----------------
//
// <h>Thread Configuration
// =======================
//
// <o>Number of concurrent running user threads <1-250>
// <i> Defines max. number of user threads that will run at the same time.
// <i> Default: 6
#ifndef OS_TASKCNT
#define OS_TASKCNT 6
#endif
// <o>Default Thread stack size [bytes] <64-4096:8><#/4>
// <i> Defines default stack size for threads with osThreadDef stacksz = 0
// <i> Default: 200
#ifndef OS_STKSIZE
#define OS_STKSIZE 50 // this stack size value is in words
#endif
// <o>Main Thread stack size [bytes] <64-32768:8><#/4>
// <i> Defines stack size for main thread.
// <i> Default: 200
#ifndef OS_MAINSTKSIZE
#define OS_MAINSTKSIZE 50 // this stack size value is in words
#endif
// <o>Number of threads with user-provided stack size <0-250>
// <i> Defines the number of threads with user-provided stack size.
// <i> Default: 0
#ifndef OS_PRIVCNT
#define OS_PRIVCNT 0
#endif
// <o>Total stack size [bytes] for threads with user-provided stack size <0-1048576:8><#/4>
// <i> Defines the combined stack size for threads with user-provided stack size.
// <i> Default: 0
#ifndef OS_PRIVSTKSIZE
#define OS_PRIVSTKSIZE 0 // this stack size value is in words
#endif
// <q>Stack overflow checking
// <i> Enable stack overflow checks at thread switch.
// <i> Enabling this option increases slightly the execution time of a thread switch.
#ifndef OS_STKCHECK
#define OS_STKCHECK 1
#endif
// <q>Stack usage watermark
// <i> Initialize thread stack with watermark pattern for analyzing stack usage (current/maximum) in System and Thread Viewer.
// <i> Enabling this option increases significantly the execution time of osThreadCreate.
#ifndef OS_STKINIT
#define OS_STKINIT 0
#endif
// <o>Processor mode for thread execution
// <0=> Unprivileged mode
// <1=> Privileged mode
// <i> Default: Privileged mode
#ifndef OS_RUNPRIV
#define OS_RUNPRIV 1
#endif
// </h>
// <h>RTX Kernel Timer Tick Configuration
// ======================================
// <q> Use Cortex-M SysTick timer as RTX Kernel Timer
// <i> Cortex-M processors provide in most cases a SysTick timer that can be used as
// <i> as time-base for RTX.
#ifndef OS_SYSTICK
#define OS_SYSTICK 1
#endif
//
// <o>RTOS Kernel Timer input clock frequency [Hz] <1-1000000000>
// <i> Defines the input frequency of the RTOS Kernel Timer.
// <i> When the Cortex-M SysTick timer is used, the input clock
// <i> is on most systems identical with the core clock.
#ifndef OS_CLOCK
#define OS_CLOCK 12000000
#endif
// <o>RTX Timer tick interval value [us] <1-1000000>
// <i> The RTX Timer tick interval value is used to calculate timeout values.
// <i> When the Cortex-M SysTick timer is enabled, the value also configures the SysTick timer.
// <i> Default: 1000 (1ms)
#ifndef OS_TICK
#define OS_TICK 1000
#endif
// </h>
// <h>System Configuration
// =======================
//
// <e>Round-Robin Thread switching
// ===============================
//
// <i> Enables Round-Robin Thread switching.
#ifndef OS_ROBIN
#define OS_ROBIN 1
#endif
// <o>Round-Robin Timeout [ticks] <1-1000>
// <i> Defines how long a thread will execute before a thread switch.
// <i> Default: 5
#ifndef OS_ROBINTOUT
#define OS_ROBINTOUT 5
#endif
// </e>
// <e>User Timers
// ==============
// <i> Enables user Timers
#ifndef OS_TIMERS
#define OS_TIMERS 1
#endif
// <o>Timer Thread Priority
// <1=> Low
// <2=> Below Normal <3=> Normal <4=> Above Normal
// <5=> High
// <6=> Realtime (highest)
// <i> Defines priority for Timer Thread
// <i> Default: High
#ifndef OS_TIMERPRIO
#define OS_TIMERPRIO 5
#endif
// <o>Timer Thread stack size [bytes] <64-4096:8><#/4>
// <i> Defines stack size for Timer thread.
// <i> Default: 200
#ifndef OS_TIMERSTKSZ
#define OS_TIMERSTKSZ 50 // this stack size value is in words
#endif
// <o>Timer Callback Queue size <1-32>
// <i> Number of concurrent active timer callback functions.
// <i> Default: 4
#ifndef OS_TIMERCBQS
#define OS_TIMERCBQS 4
#endif
// </e>
// <o>ISR FIFO Queue size<4=> 4 entries <8=> 8 entries
// <12=> 12 entries <16=> 16 entries
// <24=> 24 entries <32=> 32 entries
// <48=> 48 entries <64=> 64 entries
// <96=> 96 entries
// <i> ISR functions store requests to this buffer,
// <i> when they are called from the interrupt handler.
// <i> Default: 16 entries
#ifndef OS_FIFOSZ
#define OS_FIFOSZ 16
#endif
// </h>
//------------- <<< end of configuration section >>> -----------------------
// Standard library system mutexes
// ===============================
// Define max. number system mutexes that are used to protect
// the arm standard runtime library. For microlib they are not used.
#ifndef OS_MUTEXCNT
#define OS_MUTEXCNT 8
#endif
/*your_sha256_hash------------
* RTX User configuration part END
*your_sha256_hash-----------*/
#define OS_TRV ((uint32_t)(((double)OS_CLOCK*(double)OS_TICK)/1E6)-1)
/*your_sha256_hash------------
* Global Functions
*your_sha256_hash-----------*/
/*--------------------------- os_idle_demon ---------------------------------*/
/// \brief The idle demon is running when no other thread is ready to run
void os_idle_demon (void) {
for (;;) {
/* HERE: include optional user code to be executed when no thread runs.*/
}
}
#if (OS_SYSTICK == 0) // Functions for alternative timer as RTX kernel timer
/*--------------------------- os_tick_init ----------------------------------*/
/// \brief Initializes an alternative hardware timer as RTX kernel timer
/// \return IRQ number of the alternative hardware timer
int os_tick_init (void) {
return (-1); /* Return IRQ number of timer (0..239) */
}
/*--------------------------- os_tick_val -----------------------------------*/
/// \brief Get alternative hardware timer's current value (0 .. OS_TRV)
/// \return Current value of the alternative hardware timer
uint32_t os_tick_val (void) {
return (0);
}
/*--------------------------- os_tick_ovf -----------------------------------*/
/// \brief Get alternative hardware timer's overflow flag
/// \return Overflow flag\n
/// - 1 : overflow
/// - 0 : no overflow
uint32_t os_tick_ovf (void) {
return (0);
}
/*--------------------------- os_tick_irqack --------------------------------*/
/// \brief Acknowledge alternative hardware timer interrupt
void os_tick_irqack (void) {
/* ... */
}
#endif // (OS_SYSTICK == 0)
/*--------------------------- os_error --------------------------------------*/
/* OS Error Codes */
#define OS_ERROR_STACK_OVF 1
#define OS_ERROR_FIFO_OVF 2
#define OS_ERROR_MBX_OVF 3
#define OS_ERROR_TIMER_OVF 4
extern osThreadId svcThreadGetId (void);
/// \brief Called when a runtime error is detected
/// \param[in] error_code actual error code that has been detected
void os_error (uint32_t error_code) {
/* HERE: include optional code to be executed on runtime error. */
switch (error_code) {
case OS_ERROR_STACK_OVF:
/* Stack overflow detected for the currently running task. */
/* Thread can be identified by calling svcThreadGetId(). */
break;
case OS_ERROR_FIFO_OVF:
/* ISR FIFO Queue buffer overflow detected. */
break;
case OS_ERROR_MBX_OVF:
/* Mailbox overflow detected. */
break;
case OS_ERROR_TIMER_OVF:
/* User Timer Callback Queue overflow detected. */
break;
default:
break;
}
for (;;);
}
/*your_sha256_hash------------
* RTX Configuration Functions
*your_sha256_hash-----------*/
#include "RTX_CM_lib.h"
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/Templates/RTX_Conf_CM.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 2,274 |
```objective-c
/* your_sha256_hash------
* $Date: 5. February 2013
* $Revision: V1.02
*
* Project: CMSIS-RTOS API
* Title: cmsis_os.h RTX header file
*
* Version 0.02
* Initial Proposal Phase
* Version 0.03
* osKernelStart added, optional feature: main started as thread
* osSemaphores have standard behavior
* osTimerCreate does not start the timer, added osTimerStart
* osThreadPass is renamed to osThreadYield
* Version 1.01
* Support for C++ interface
* - const attribute removed from the osXxxxDef_t typedef's
* - const attribute added to the osXxxxDef macros
* Added: osTimerDelete, osMutexDelete, osSemaphoreDelete
* Added: osKernelInitialize
* Version 1.02
* Control functions for short timeouts in microsecond resolution:
* Added: osKernelSysTick, osKernelSysTickFrequency, osKernelSysTickMicroSec
* Removed: osSignalGet
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#ifndef _CMSIS_OS_H
#define _CMSIS_OS_H
#define osCMSIS 0x10002U ///< CMSIS-RTOS API version (main [31:16] .sub [15:0])
#define osCMSIS_RTX ((4<<16)|82) ///< RTOS identification and version (main [31:16] .sub [15:0])
#define osKernelSystemId "RTX V4.82" ///< RTOS identification string
#define osFeature_MainThread 1 ///< main can be thread
#define osFeature_Pool 1 ///< Memory Pools available
#define osFeature_MailQ 1 ///< Mail Queues available
#define osFeature_MessageQ 1 ///< Message Queues available
#define osFeature_Signals 16 ///< 16 Signal Flags available per thread
#define osFeature_Semaphore 65535 ///< Maximum count for \ref osSemaphoreCreate function
#define osFeature_Wait 0 ///< osWait not available
#define osFeature_SysTick 1 ///< osKernelSysTick functions available
#if defined(__CC_ARM)
#define os_InRegs __value_in_regs // Compiler specific: force struct in registers
#else
#define os_InRegs
#endif
#if defined(__CC_ARM)
#define __NO_RETURN __declspec(noreturn)
#elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
#define __NO_RETURN __attribute__((noreturn))
#elif defined(__GNUC__)
#define __NO_RETURN __attribute__((noreturn))
#elif defined(__ICCARM__)
#define __NO_RETURN __noreturn
#else
#define __NO_RETURN
#endif
#include <stdint.h>
#include <stddef.h>
#ifdef __cplusplus
extern "C"
{
#endif
// ==== Enumeration, structures, defines ====
/// Priority used for thread control.
typedef enum {
osPriorityIdle = -3, ///< priority: idle (lowest)
osPriorityLow = -2, ///< priority: low
osPriorityBelowNormal = -1, ///< priority: below normal
osPriorityNormal = 0, ///< priority: normal (default)
osPriorityAboveNormal = +1, ///< priority: above normal
osPriorityHigh = +2, ///< priority: high
osPriorityRealtime = +3, ///< priority: realtime (highest)
osPriorityError = 0x84, ///< system cannot determine priority or thread has illegal priority
os_priority_reserved = 0x7FFFFFFF ///< prevent from enum down-size compiler optimization.
} osPriority;
/// Timeout value.
#define osWaitForever 0xFFFFFFFFU ///< wait forever timeout value
/// Status code values returned by CMSIS-RTOS functions.
typedef enum {
osOK = 0, ///< function completed; no error or event occurred.
osEventSignal = 0x08, ///< function completed; signal event occurred.
osEventMessage = 0x10, ///< function completed; message event occurred.
osEventMail = 0x20, ///< function completed; mail event occurred.
osEventTimeout = 0x40, ///< function completed; timeout occurred.
osErrorParameter = 0x80, ///< parameter error: a mandatory parameter was missing or specified an incorrect object.
osErrorResource = 0x81, ///< resource not available: a specified resource was not available.
osErrorTimeoutResource = 0xC1, ///< resource not available within given time: a specified resource was not available within the timeout period.
osErrorISR = 0x82, ///< not allowed in ISR context: the function cannot be called from interrupt service routines.
osErrorISRRecursive = 0x83, ///< function called multiple times from ISR with same object.
osErrorPriority = 0x84, ///< system cannot determine priority or thread has illegal priority.
osErrorNoMemory = 0x85, ///< system is out of memory: it was impossible to allocate or reserve memory for the operation.
osErrorValue = 0x86, ///< value of a parameter is out of range.
osErrorOS = 0xFF, ///< unspecified RTOS error: run-time error but no other error message fits.
os_status_reserved = 0x7FFFFFFF ///< prevent from enum down-size compiler optimization.
} osStatus;
/// Timer type value for the timer definition.
typedef enum {
osTimerOnce = 0, ///< one-shot timer
osTimerPeriodic = 1 ///< repeating timer
} os_timer_type;
/// Entry point of a thread.
typedef void (*os_pthread) (void const *argument);
/// Entry point of a timer call back function.
typedef void (*os_ptimer) (void const *argument);
// >>> the following data type definitions may shall adapted towards a specific RTOS
/// Thread ID identifies the thread (pointer to a thread control block).
typedef struct os_thread_cb *osThreadId;
/// Timer ID identifies the timer (pointer to a timer control block).
typedef struct os_timer_cb *osTimerId;
/// Mutex ID identifies the mutex (pointer to a mutex control block).
typedef struct os_mutex_cb *osMutexId;
/// Semaphore ID identifies the semaphore (pointer to a semaphore control block).
typedef struct os_semaphore_cb *osSemaphoreId;
/// Pool ID identifies the memory pool (pointer to a memory pool control block).
typedef struct os_pool_cb *osPoolId;
/// Message ID identifies the message queue (pointer to a message queue control block).
typedef struct os_messageQ_cb *osMessageQId;
/// Mail ID identifies the mail queue (pointer to a mail queue control block).
typedef struct os_mailQ_cb *osMailQId;
/// Thread Definition structure contains startup information of a thread.
typedef struct os_thread_def {
os_pthread pthread; ///< start address of thread function
osPriority tpriority; ///< initial thread priority
uint32_t instances; ///< maximum number of instances of that thread function
uint32_t stacksize; ///< stack size requirements in bytes; 0 is default stack size
} osThreadDef_t;
/// Timer Definition structure contains timer parameters.
typedef struct os_timer_def {
os_ptimer ptimer; ///< start address of a timer function
void *timer; ///< pointer to internal data
} osTimerDef_t;
/// Mutex Definition structure contains setup information for a mutex.
typedef struct os_mutex_def {
void *mutex; ///< pointer to internal data
} osMutexDef_t;
/// Semaphore Definition structure contains setup information for a semaphore.
typedef struct os_semaphore_def {
void *semaphore; ///< pointer to internal data
} osSemaphoreDef_t;
/// Definition structure for memory block allocation.
typedef struct os_pool_def {
uint32_t pool_sz; ///< number of items (elements) in the pool
uint32_t item_sz; ///< size of an item
void *pool; ///< pointer to memory for pool
} osPoolDef_t;
/// Definition structure for message queue.
typedef struct os_messageQ_def {
uint32_t queue_sz; ///< number of elements in the queue
void *pool; ///< memory array for messages
} osMessageQDef_t;
/// Definition structure for mail queue.
typedef struct os_mailQ_def {
uint32_t queue_sz; ///< number of elements in the queue
uint32_t item_sz; ///< size of an item
void *pool; ///< memory array for mail
} osMailQDef_t;
/// Event structure contains detailed information about an event.
typedef struct {
osStatus status; ///< status code: event or error information
union {
uint32_t v; ///< message as 32-bit value
void *p; ///< message or mail as void pointer
int32_t signals; ///< signal flags
} value; ///< event value
union {
osMailQId mail_id; ///< mail id obtained by \ref osMailCreate
osMessageQId message_id; ///< message id obtained by \ref osMessageCreate
} def; ///< event definition
} osEvent;
// ==== Kernel Control Functions ====
/// Initialize the RTOS Kernel for creating objects.
/// \return status code that indicates the execution status of the function.
osStatus osKernelInitialize (void);
/// Start the RTOS Kernel.
/// \return status code that indicates the execution status of the function.
osStatus osKernelStart (void);
/// Check if the RTOS kernel is already started.
/// \return 0 RTOS is not started, 1 RTOS is started.
int32_t osKernelRunning(void);
#if (defined (osFeature_SysTick) && (osFeature_SysTick != 0)) // System Timer available
/// \cond INTERNAL_VARIABLES
extern uint32_t const os_tickfreq;
extern uint16_t const os_tickus_i;
extern uint16_t const os_tickus_f;
/// \endcond
/// Get the RTOS kernel system timer counter.
/// \return RTOS kernel system timer as 32-bit value
uint32_t osKernelSysTick (void);
/// The RTOS kernel system timer frequency in Hz.
/// \note Reflects the system timer setting and is typically defined in a configuration file.
#define osKernelSysTickFrequency os_tickfreq
/// Convert a microseconds value to a RTOS kernel system timer value.
/// \param microsec time value in microseconds.
/// \return time value normalized to the \ref osKernelSysTickFrequency
/*
#define osKernelSysTickMicroSec(microsec) (((uint64_t)microsec * (osKernelSysTickFrequency)) / 1000000)
*/
#define osKernelSysTickMicroSec(microsec) ((microsec * os_tickus_i) + ((microsec * os_tickus_f) >> 16))
#endif // System Timer available
// ==== Thread Management ====
/// Create a Thread Definition with function, priority, and stack requirements.
/// \param name name of the thread function.
/// \param priority initial priority of the thread function.
/// \param instances number of possible thread instances.
/// \param stacksz stack size (in bytes) requirements for the thread function.
/// macro body is implementation specific in every CMSIS-RTOS.
#if defined (osObjectsExternal) // object is external
#define osThreadDef(name, priority, instances, stacksz) \
extern const osThreadDef_t os_thread_def_##name
#else // define the object
#define osThreadDef(name, priority, instances, stacksz) \
const osThreadDef_t os_thread_def_##name = \
{ (name), (priority), (instances), (stacksz) }
#endif
/// Access a Thread definition.
/// \param name name of the thread definition object.
/// macro body is implementation specific in every CMSIS-RTOS.
#define osThread(name) \
&os_thread_def_##name
/// Create a thread and add it to Active Threads and set it to state READY.
/// \param[in] thread_def thread definition referenced with \ref osThread.
/// \param[in] argument pointer that is passed to the thread function as start argument.
/// \return thread ID for reference by other functions or NULL in case of error.
osThreadId osThreadCreate (const osThreadDef_t *thread_def, void *argument);
/// Return the thread ID of the current running thread.
/// \return thread ID for reference by other functions or NULL in case of error.
osThreadId osThreadGetId (void);
/// Terminate execution of a thread and remove it from Active Threads.
/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
/// \return status code that indicates the execution status of the function.
osStatus osThreadTerminate (osThreadId thread_id);
/// Pass control to next thread that is in state \b READY.
/// \return status code that indicates the execution status of the function.
osStatus osThreadYield (void);
/// Change priority of an active thread.
/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
/// \param[in] priority new priority value for the thread function.
/// \return status code that indicates the execution status of the function.
osStatus osThreadSetPriority (osThreadId thread_id, osPriority priority);
/// Get current priority of an active thread.
/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
/// \return current priority value of the thread function.
osPriority osThreadGetPriority (osThreadId thread_id);
// ==== Generic Wait Functions ====
/// Wait for Timeout (Time Delay).
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue "Time delay" value
/// \return status code that indicates the execution status of the function.
osStatus osDelay (uint32_t millisec);
#if (defined (osFeature_Wait) && (osFeature_Wait != 0)) // Generic Wait available
/// Wait for Signal, Message, Mail, or Timeout.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out
/// \return event that contains signal, message, or mail information or error code.
os_InRegs osEvent osWait (uint32_t millisec);
#endif // Generic Wait available
// ==== Timer Management Functions ====
/// Define a Timer object.
/// \param name name of the timer object.
/// \param function name of the timer call back function.
#if defined (osObjectsExternal) // object is external
#define osTimerDef(name, function) \
extern const osTimerDef_t os_timer_def_##name
#else // define the object
#define osTimerDef(name, function) \
uint32_t os_timer_cb_##name[6]; \
const osTimerDef_t os_timer_def_##name = \
{ (function), (os_timer_cb_##name) }
#endif
/// Access a Timer definition.
/// \param name name of the timer object.
#define osTimer(name) \
&os_timer_def_##name
/// Create a timer.
/// \param[in] timer_def timer object referenced with \ref osTimer.
/// \param[in] type osTimerOnce for one-shot or osTimerPeriodic for periodic behavior.
/// \param[in] argument argument to the timer call back function.
/// \return timer ID for reference by other functions or NULL in case of error.
osTimerId osTimerCreate (const osTimerDef_t *timer_def, os_timer_type type, void *argument);
/// Start or restart a timer.
/// \param[in] timer_id timer ID obtained by \ref osTimerCreate.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue "Time delay" value of the timer.
/// \return status code that indicates the execution status of the function.
osStatus osTimerStart (osTimerId timer_id, uint32_t millisec);
/// Stop the timer.
/// \param[in] timer_id timer ID obtained by \ref osTimerCreate.
/// \return status code that indicates the execution status of the function.
osStatus osTimerStop (osTimerId timer_id);
/// Delete a timer that was created by \ref osTimerCreate.
/// \param[in] timer_id timer ID obtained by \ref osTimerCreate.
/// \return status code that indicates the execution status of the function.
osStatus osTimerDelete (osTimerId timer_id);
// ==== Signal Management ====
/// Set the specified Signal Flags of an active thread.
/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
/// \param[in] signals specifies the signal flags of the thread that should be set.
/// \return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters.
int32_t osSignalSet (osThreadId thread_id, int32_t signals);
/// Clear the specified Signal Flags of an active thread.
/// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
/// \param[in] signals specifies the signal flags of the thread that shall be cleared.
/// \return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters or call from ISR.
int32_t osSignalClear (osThreadId thread_id, int32_t signals);
/// Wait for one or more Signal Flags to become signaled for the current \b RUNNING thread.
/// \param[in] signals wait until all specified signal flags set or 0 for any single signal flag.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out.
/// \return event flag information or error code.
#if defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
#define osSignalWait __osSignalWait
osEvent __osSignalWait (int32_t signals, uint32_t millisec);
#else
os_InRegs osEvent osSignalWait (int32_t signals, uint32_t millisec);
#endif
// ==== Mutex Management ====
/// Define a Mutex.
/// \param name name of the mutex object.
#if defined (osObjectsExternal) // object is external
#define osMutexDef(name) \
extern const osMutexDef_t os_mutex_def_##name
#else // define the object
#define osMutexDef(name) \
uint32_t os_mutex_cb_##name[4] = { 0 }; \
const osMutexDef_t os_mutex_def_##name = { (os_mutex_cb_##name) }
#endif
/// Access a Mutex definition.
/// \param name name of the mutex object.
#define osMutex(name) \
&os_mutex_def_##name
/// Create and Initialize a Mutex object.
/// \param[in] mutex_def mutex definition referenced with \ref osMutex.
/// \return mutex ID for reference by other functions or NULL in case of error.
osMutexId osMutexCreate (const osMutexDef_t *mutex_def);
/// Wait until a Mutex becomes available.
/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out.
/// \return status code that indicates the execution status of the function.
osStatus osMutexWait (osMutexId mutex_id, uint32_t millisec);
/// Release a Mutex that was obtained by \ref osMutexWait.
/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate.
/// \return status code that indicates the execution status of the function.
osStatus osMutexRelease (osMutexId mutex_id);
/// Delete a Mutex that was created by \ref osMutexCreate.
/// \param[in] mutex_id mutex ID obtained by \ref osMutexCreate.
/// \return status code that indicates the execution status of the function.
osStatus osMutexDelete (osMutexId mutex_id);
// ==== Semaphore Management Functions ====
#if (defined (osFeature_Semaphore) && (osFeature_Semaphore != 0)) // Semaphore available
/// Define a Semaphore object.
/// \param name name of the semaphore object.
#if defined (osObjectsExternal) // object is external
#define osSemaphoreDef(name) \
extern const osSemaphoreDef_t os_semaphore_def_##name
#else // define the object
#define osSemaphoreDef(name) \
uint32_t os_semaphore_cb_##name[2] = { 0 }; \
const osSemaphoreDef_t os_semaphore_def_##name = { (os_semaphore_cb_##name) }
#endif
/// Access a Semaphore definition.
/// \param name name of the semaphore object.
#define osSemaphore(name) \
&os_semaphore_def_##name
/// Create and Initialize a Semaphore object used for managing resources.
/// \param[in] semaphore_def semaphore definition referenced with \ref osSemaphore.
/// \param[in] count number of available resources.
/// \return semaphore ID for reference by other functions or NULL in case of error.
osSemaphoreId osSemaphoreCreate (const osSemaphoreDef_t *semaphore_def, int32_t count);
/// Wait until a Semaphore token becomes available.
/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out.
/// \return number of available tokens, or -1 in case of incorrect parameters.
int32_t osSemaphoreWait (osSemaphoreId semaphore_id, uint32_t millisec);
/// Release a Semaphore token.
/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate.
/// \return status code that indicates the execution status of the function.
osStatus osSemaphoreRelease (osSemaphoreId semaphore_id);
/// Delete a Semaphore that was created by \ref osSemaphoreCreate.
/// \param[in] semaphore_id semaphore object referenced with \ref osSemaphoreCreate.
/// \return status code that indicates the execution status of the function.
osStatus osSemaphoreDelete (osSemaphoreId semaphore_id);
#endif // Semaphore available
// ==== Memory Pool Management Functions ====
#if (defined (osFeature_Pool) && (osFeature_Pool != 0)) // Memory Pool Management available
/// \brief Define a Memory Pool.
/// \param name name of the memory pool.
/// \param no maximum number of blocks (objects) in the memory pool.
/// \param type data type of a single block (object).
#if defined (osObjectsExternal) // object is external
#define osPoolDef(name, no, type) \
extern const osPoolDef_t os_pool_def_##name
#else // define the object
#define osPoolDef(name, no, type) \
uint32_t os_pool_m_##name[3+((sizeof(type)+3)/4)*(no)]; \
const osPoolDef_t os_pool_def_##name = \
{ (no), sizeof(type), (os_pool_m_##name) }
#endif
/// \brief Access a Memory Pool definition.
/// \param name name of the memory pool
#define osPool(name) \
&os_pool_def_##name
/// Create and Initialize a memory pool.
/// \param[in] pool_def memory pool definition referenced with \ref osPool.
/// \return memory pool ID for reference by other functions or NULL in case of error.
osPoolId osPoolCreate (const osPoolDef_t *pool_def);
/// Allocate a memory block from a memory pool.
/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate.
/// \return address of the allocated memory block or NULL in case of no memory available.
void *osPoolAlloc (osPoolId pool_id);
/// Allocate a memory block from a memory pool and set memory block to zero.
/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate.
/// \return address of the allocated memory block or NULL in case of no memory available.
void *osPoolCAlloc (osPoolId pool_id);
/// Return an allocated memory block back to a specific memory pool.
/// \param[in] pool_id memory pool ID obtain referenced with \ref osPoolCreate.
/// \param[in] block address of the allocated memory block that is returned to the memory pool.
/// \return status code that indicates the execution status of the function.
osStatus osPoolFree (osPoolId pool_id, void *block);
#endif // Memory Pool Management available
// ==== Message Queue Management Functions ====
#if (defined (osFeature_MessageQ) && (osFeature_MessageQ != 0)) // Message Queues available
/// \brief Create a Message Queue Definition.
/// \param name name of the queue.
/// \param queue_sz maximum number of messages in the queue.
/// \param type data type of a single message element (for debugger).
#if defined (osObjectsExternal) // object is external
#define osMessageQDef(name, queue_sz, type) \
extern const osMessageQDef_t os_messageQ_def_##name
#else // define the object
#define osMessageQDef(name, queue_sz, type) \
uint32_t os_messageQ_q_##name[4+(queue_sz)] = { 0 }; \
const osMessageQDef_t os_messageQ_def_##name = \
{ (queue_sz), (os_messageQ_q_##name) }
#endif
/// \brief Access a Message Queue Definition.
/// \param name name of the queue
#define osMessageQ(name) \
&os_messageQ_def_##name
/// Create and Initialize a Message Queue.
/// \param[in] queue_def queue definition referenced with \ref osMessageQ.
/// \param[in] thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL.
/// \return message queue ID for reference by other functions or NULL in case of error.
osMessageQId osMessageCreate (const osMessageQDef_t *queue_def, osThreadId thread_id);
/// Put a Message to a Queue.
/// \param[in] queue_id message queue ID obtained with \ref osMessageCreate.
/// \param[in] info message information.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out.
/// \return status code that indicates the execution status of the function.
osStatus osMessagePut (osMessageQId queue_id, uint32_t info, uint32_t millisec);
/// Get a Message or Wait for a Message from a Queue.
/// \param[in] queue_id message queue ID obtained with \ref osMessageCreate.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out.
/// \return event information that includes status code.
#if defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
#define osMessageGet __osMessageGet
osEvent __osMessageGet (osMessageQId queue_id, uint32_t millisec);
#else
os_InRegs osEvent osMessageGet (osMessageQId queue_id, uint32_t millisec);
#endif
#endif // Message Queues available
// ==== Mail Queue Management Functions ====
#if (defined (osFeature_MailQ) && (osFeature_MailQ != 0)) // Mail Queues available
/// \brief Create a Mail Queue Definition.
/// \param name name of the queue
/// \param queue_sz maximum number of messages in queue
/// \param type data type of a single message element
#if defined (osObjectsExternal) // object is external
#define osMailQDef(name, queue_sz, type) \
extern const osMailQDef_t os_mailQ_def_##name
#else // define the object
#define osMailQDef(name, queue_sz, type) \
uint32_t os_mailQ_q_##name[4+(queue_sz)] = { 0 }; \
uint32_t os_mailQ_m_##name[3+((sizeof(type)+3)/4)*(queue_sz)]; \
void * os_mailQ_p_##name[2] = { (os_mailQ_q_##name), os_mailQ_m_##name }; \
const osMailQDef_t os_mailQ_def_##name = \
{ (queue_sz), sizeof(type), (os_mailQ_p_##name) }
#endif
/// \brief Access a Mail Queue Definition.
/// \param name name of the queue
#define osMailQ(name) \
&os_mailQ_def_##name
/// Create and Initialize mail queue.
/// \param[in] queue_def reference to the mail queue definition obtain with \ref osMailQ
/// \param[in] thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL.
/// \return mail queue ID for reference by other functions or NULL in case of error.
osMailQId osMailCreate (const osMailQDef_t *queue_def, osThreadId thread_id);
/// Allocate a memory block from a mail.
/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out
/// \return pointer to memory block that can be filled with mail or NULL in case of error.
void *osMailAlloc (osMailQId queue_id, uint32_t millisec);
/// Allocate a memory block from a mail and set memory block to zero.
/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out
/// \return pointer to memory block that can be filled with mail or NULL in case of error.
void *osMailCAlloc (osMailQId queue_id, uint32_t millisec);
/// Put a mail to a queue.
/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate.
/// \param[in] mail memory block previously allocated with \ref osMailAlloc or \ref osMailCAlloc.
/// \return status code that indicates the execution status of the function.
osStatus osMailPut (osMailQId queue_id, void *mail);
/// Get a mail from a queue.
/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate.
/// \param[in] millisec \ref CMSIS_RTOS_TimeOutValue or 0 in case of no time-out
/// \return event that contains mail information or error code.
#if defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
#define osMailGet __osMailGet
osEvent __osMailGet (osMailQId queue_id, uint32_t millisec);
#else
os_InRegs osEvent osMailGet (osMailQId queue_id, uint32_t millisec);
#endif
/// Free a memory block from a mail.
/// \param[in] queue_id mail queue ID obtained with \ref osMailCreate.
/// \param[in] mail pointer to the memory block that was obtained with \ref osMailGet.
/// \return status code that indicates the execution status of the function.
osStatus osMailFree (osMailQId queue_id, void *mail);
#endif // Mail Queues available
// ==== RTX Extensions ====
/// Suspend the RTX task scheduler.
/// \return number of ticks, for how long the system can sleep or power-down.
uint32_t os_suspend (void);
/// Resume the RTX task scheduler.
/// \param[in] sleep_time specifies how long the system was in sleep or power-down mode.
void os_resume (uint32_t sleep_time);
/// OS idle demon (running when no other thread is ready to run).
__NO_RETURN void os_idle_demon (void);
/// OS error callback (called when a runtime error is detected).
/// \param[in] error_code actual error code that has been detected.
__NO_RETURN void os_error (uint32_t error_code);
#ifdef __cplusplus
}
#endif
#endif // _CMSIS_OS_H
``` | /content/code_sandbox/CMSIS/RTOS/RTX/INC/cmsis_os.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 7,127 |
```objective-c
/*your_sha256_hash------------
* CMSIS-RTOS - RTX
*your_sha256_hash------------
* Name: RTX_CM_LIB.H
* Purpose: RTX Kernel System Configuration
* Rev.: V4.82
*your_sha256_hash------------
*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*your_sha256_hash-----------*/
#if defined (__CC_ARM)
#pragma O3
#define __USED __attribute__((used))
#elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
#define __USED __attribute__((used))
#elif defined (__GNUC__)
#pragma GCC optimize ("O3")
#define __USED __attribute__((used))
#elif defined (__ICCARM__)
#define __USED __root
#endif
/*your_sha256_hash------------
* Definitions
*your_sha256_hash-----------*/
#define _declare_box(pool,size,cnt) uint32_t pool[(((size)+3)/4)*(cnt) + 3]
#define _declare_box8(pool,size,cnt) uint64_t pool[(((size)+7)/8)*(cnt) + 2]
#define OS_TCB_SIZE 52
#define OS_TMR_SIZE 8
#if (( defined(__CC_ARM) || \
(defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050))) && \
!defined(__MICROLIB))
typedef void *OS_ID;
typedef uint32_t OS_TID;
typedef uint32_t OS_MUT[4];
typedef uint32_t OS_RESULT;
#define runtask_id() rt_tsk_self()
#define mutex_init(m) rt_mut_init(m)
#define mutex_wait(m) os_mut_wait(m,0xFFFFU)
#define mutex_rel(m) os_mut_release(m)
extern uint8_t os_running;
extern OS_TID rt_tsk_self (void);
extern void rt_mut_init (OS_ID mutex);
extern OS_RESULT rt_mut_release (OS_ID mutex);
extern OS_RESULT rt_mut_wait (OS_ID mutex, uint16_t timeout);
#if defined(__CC_ARM)
#define os_mut_wait(mutex,timeout) _os_mut_wait((uint32_t)rt_mut_wait,mutex,timeout)
#define os_mut_release(mutex) _os_mut_release((uint32_t)rt_mut_release,mutex)
OS_RESULT _os_mut_release (uint32_t p, OS_ID mutex) __svc_indirect(0);
OS_RESULT _os_mut_wait (uint32_t p, OS_ID mutex, uint16_t timeout) __svc_indirect(0);
#else
__attribute__((always_inline))
static __inline OS_RESULT os_mut_release (OS_ID mutex) {
register uint32_t __rf __asm("r12") = (uint32_t)rt_mut_release;
register uint32_t __r0 __asm("r0") = (uint32_t)mutex;
__asm volatile \
( \
"svc 0" \
: "=r" (__r0) \
: "r" (__rf), "r" (__r0) \
: "r1", "r2" \
);
return (OS_RESULT)__r0;
}
__attribute__((always_inline))
static __inline OS_RESULT os_mut_wait (OS_ID mutex, uint16_t timeout) {
register uint32_t __rf __asm("r12") = (uint32_t)rt_mut_wait;
register uint32_t __r0 __asm("r0") = (uint32_t)mutex;
register uint32_t __r1 __asm("r1") = (uint32_t)timeout;
__asm volatile \
( \
"svc 0" \
: "=r" (__r0) \
: "r" (__rf), "r" (__r0), "r" (__r1) \
: "r2" \
);
return (OS_RESULT)__r0;
}
#endif
#endif
/*your_sha256_hash------------
* Global Variables
*your_sha256_hash-----------*/
#if (OS_TASKCNT == 0)
#error "Invalid number of concurrent running threads!"
#endif
#if (OS_PRIVCNT >= OS_TASKCNT)
#error "Too many threads with user-provided stack size!"
#endif
#if (OS_TIMERS != 0)
#define OS_TASK_CNT (OS_TASKCNT + 1)
#define OS_PRIV_CNT (OS_PRIVCNT + 2)
#define OS_STACK_SZ (4*(OS_PRIVSTKSIZE+OS_MAINSTKSIZE+OS_TIMERSTKSZ))
#else
#define OS_TASK_CNT OS_TASKCNT
#define OS_PRIV_CNT (OS_PRIVCNT + 1)
#define OS_STACK_SZ (4*(OS_PRIVSTKSIZE+OS_MAINSTKSIZE))
#endif
#ifndef OS_STKINIT
#define OS_STKINIT 0
#endif
extern uint16_t const os_maxtaskrun;
extern uint32_t const os_stackinfo;
extern uint32_t const os_rrobin;
extern uint32_t const os_trv;
extern uint8_t const os_flags;
uint16_t const os_maxtaskrun = OS_TASK_CNT;
uint32_t const os_stackinfo = (OS_STKINIT<<28) | (OS_STKCHECK<<24) | (OS_PRIV_CNT<<16) | (OS_STKSIZE*4);
uint32_t const os_rrobin = (OS_ROBIN << 16) | OS_ROBINTOUT;
uint32_t const os_tickfreq = OS_CLOCK;
uint16_t const os_tickus_i = OS_CLOCK/1000000;
uint16_t const os_tickus_f = (((uint64_t)(OS_CLOCK-1000000*(OS_CLOCK/1000000)))<<16)/1000000;
uint32_t const os_trv = OS_TRV;
uint8_t const os_flags = OS_RUNPRIV;
/* Export following defines to uVision debugger. */
extern uint32_t const CMSIS_RTOS_API_Version;
__USED uint32_t const CMSIS_RTOS_API_Version = osCMSIS;
extern uint32_t const CMSIS_RTOS_RTX_Version;
__USED uint32_t const CMSIS_RTOS_RTX_Version = osCMSIS_RTX;
extern uint32_t const os_clockrate;
__USED uint32_t const os_clockrate = OS_TICK;
extern uint32_t const os_timernum;
__USED uint32_t const os_timernum = 0U;
/* Memory pool for TCB allocation */
extern
uint32_t mp_tcb[];
_declare_box (mp_tcb, OS_TCB_SIZE, OS_TASK_CNT);
extern
uint16_t const mp_tcb_size;
uint16_t const mp_tcb_size = sizeof(mp_tcb);
/* Memory pool for System stack allocation (+os_idle_demon). */
extern
uint64_t mp_stk[];
_declare_box8 (mp_stk, OS_STKSIZE*4, OS_TASK_CNT-OS_PRIV_CNT+1);
extern
uint32_t const mp_stk_size;
uint32_t const mp_stk_size = sizeof(mp_stk);
/* Memory pool for user specified stack allocation (+main, +timer) */
extern
uint64_t os_stack_mem[];
uint64_t os_stack_mem[2+OS_PRIV_CNT+(OS_STACK_SZ/8)];
extern
uint32_t const os_stack_sz;
uint32_t const os_stack_sz = sizeof(os_stack_mem);
#ifndef OS_FIFOSZ
#define OS_FIFOSZ 16
#endif
/* Fifo Queue buffer for ISR requests.*/
extern
uint32_t os_fifo[];
uint32_t os_fifo[OS_FIFOSZ*2+1];
extern
uint8_t const os_fifo_size;
uint8_t const os_fifo_size = OS_FIFOSZ;
/* An array of Active task pointers. */
extern
void *os_active_TCB[];
void *os_active_TCB[OS_TASK_CNT];
/* User Timers Resources */
#if (OS_TIMERS != 0)
extern void osTimerThread (void const *argument);
extern const osThreadDef_t os_thread_def_osTimerThread;
osThreadDef(osTimerThread, (osPriority)(OS_TIMERPRIO-3), 1, 4*OS_TIMERSTKSZ);
extern
osThreadId osThreadId_osTimerThread;
osThreadId osThreadId_osTimerThread;
extern uint32_t os_messageQ_q_osTimerMessageQ[];
extern const osMessageQDef_t os_messageQ_def_osTimerMessageQ;
osMessageQDef(osTimerMessageQ, OS_TIMERCBQS, void *);
extern
osMessageQId osMessageQId_osTimerMessageQ;
osMessageQId osMessageQId_osTimerMessageQ;
#else
extern
const osThreadDef_t os_thread_def_osTimerThread;
const osThreadDef_t os_thread_def_osTimerThread = { NULL, osPriorityNormal, 0U, 0U };
extern
osThreadId osThreadId_osTimerThread;
osThreadId osThreadId_osTimerThread;
extern uint32_t os_messageQ_q_osTimerMessageQ[];
extern const osMessageQDef_t os_messageQ_def_osTimerMessageQ;
osMessageQDef(osTimerMessageQ, 0U, void *);
extern
osMessageQId osMessageQId_osTimerMessageQ;
osMessageQId osMessageQId_osTimerMessageQ;
#endif
/* Legacy RTX User Timers not used */
extern
uint32_t os_tmr;
uint32_t os_tmr = 0U;
extern
uint32_t const *m_tmr;
uint32_t const *m_tmr = NULL;
extern
uint16_t const mp_tmr_size;
uint16_t const mp_tmr_size = 0U;
#if (( defined(__CC_ARM) || \
(defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050))) && \
!defined(__MICROLIB))
/* A memory space for arm standard library. */
static uint32_t std_libspace[OS_TASK_CNT][96/4];
static OS_MUT std_libmutex[OS_MUTEXCNT];
static uint32_t nr_mutex;
extern void *__libspace_start;
#endif
/*your_sha256_hash------------
* RTX Optimizations (empty functions)
*your_sha256_hash-----------*/
#if OS_ROBIN == 0
extern
void rt_init_robin (void);
void rt_init_robin (void) {;}
extern
void rt_chk_robin (void);
void rt_chk_robin (void) {;}
#endif
#if OS_STKCHECK == 0
extern
void rt_stk_check (void);
void rt_stk_check (void) {;}
#endif
/*your_sha256_hash------------
* Standard Library multithreading interface
*your_sha256_hash-----------*/
#if (( defined(__CC_ARM) || \
(defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050))) && \
!defined(__MICROLIB))
/*--------------------------- __user_perthread_libspace ---------------------*/
void *__user_perthread_libspace (void);
void *__user_perthread_libspace (void) {
/* Provide a separate libspace for each task. */
uint32_t idx;
idx = (os_running != 0U) ? runtask_id () : 0U;
if (idx == 0U) {
/* RTX not running yet. */
return (&__libspace_start);
}
return ((void *)&std_libspace[idx-1]);
}
/*--------------------------- _mutex_initialize -----------------------------*/
int _mutex_initialize (OS_ID *mutex);
int _mutex_initialize (OS_ID *mutex) {
/* Allocate and initialize a system mutex. */
if (nr_mutex >= OS_MUTEXCNT) {
/* If you are here, you need to increase the number OS_MUTEXCNT. */
for (;;);
}
*mutex = &std_libmutex[nr_mutex++];
mutex_init (*mutex);
return (1);
}
/*--------------------------- _mutex_acquire --------------------------------*/
__attribute__((used))
void _mutex_acquire (OS_ID *mutex);
void _mutex_acquire (OS_ID *mutex) {
/* Acquire a system mutex, lock stdlib resources. */
if (os_running) {
/* RTX running, acquire a mutex. */
mutex_wait (*mutex);
}
}
/*--------------------------- _mutex_release --------------------------------*/
__attribute__((used))
void _mutex_release (OS_ID *mutex);
void _mutex_release (OS_ID *mutex) {
/* Release a system mutex, unlock stdlib resources. */
if (os_running) {
/* RTX running, release a mutex. */
mutex_rel (*mutex);
}
}
#endif
/*your_sha256_hash------------
* ARMCC6 Wrappers for ARMCC5 Binary
*your_sha256_hash-----------*/
#if defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
typedef uint32_t __attribute__((vector_size(8))) vect64_t;
#undef osSignalWait
__attribute__((pcs("aapcs")))
vect64_t osSignalWait (int32_t signals, uint32_t millisec);
osEvent __osSignalWait (int32_t signals, uint32_t millisec) {
vect64_t v;
osEvent e;
v = osSignalWait(signals, millisec);
e.status = v[0];
e.value.v = v[1];
return e;
}
#undef osMessageGet
__attribute__((pcs("aapcs")))
vect64_t osMessageGet (osMessageQId queue_id, uint32_t millisec);
osEvent __osMessageGet (osMessageQId queue_id, uint32_t millisec) {
vect64_t v;
osEvent e;
v = osMessageGet(queue_id, millisec);
e.status = v[0];
e.value.v = v[1];
return e;
}
#undef osMailGet
__attribute__((pcs("aapcs")))
vect64_t osMailGet (osMailQId queue_id, uint32_t millisec);
osEvent __osMailGet (osMailQId queue_id, uint32_t millisec) {
vect64_t v;
osEvent e;
v = osMailGet(queue_id, millisec);
e.status = v[0];
e.value.v = v[1];
return e;
}
#endif
/*your_sha256_hash------------
* RTX Startup
*your_sha256_hash-----------*/
/* Main Thread definition */
extern int main (void);
extern
const osThreadDef_t os_thread_def_main;
const osThreadDef_t os_thread_def_main = {(os_pthread)main, osPriorityNormal, 1U, 4*OS_MAINSTKSIZE };
#if defined (__CC_ARM)
#ifdef __MICROLIB
__attribute__((section(".ARM.Collect$$$$000000FF")))
void _main_init (void);
void _main_init (void) {
osKernelInitialize();
osThreadCreate(&os_thread_def_main, NULL);
osKernelStart();
for (;;);
}
#else
__asm void _platform_post_lib_init (void) {
IMPORT os_thread_def_main
IMPORT osKernelInitialize
IMPORT osKernelStart
IMPORT osThreadCreate
IMPORT exit
ADD SP,#0x10
BL osKernelInitialize
LDR R0,=os_thread_def_main
MOVS R1,#0
BL osThreadCreate
BL osKernelStart
BL exit
ALIGN
}
#endif
#elif defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050)
#ifdef __MICROLIB
__attribute__((noreturn, section(".ARM.Collect$$$$000000FF")))
void _main_init (void);
void _main_init (void) {
#else
__asm(" .global __ARM_use_no_argv\n");
__attribute__((noreturn))
void _platform_post_lib_init (void);
void _platform_post_lib_init (void) {
#endif
osKernelInitialize();
osThreadCreate(&os_thread_def_main, NULL);
osKernelStart();
for (;;);
}
#elif defined (__GNUC__)
#ifdef __CS3__
/* CS3 start_c routine.
*
*
* The authors hereby grant permission to use, copy, modify, distribute,
* and license this software and its documentation for any purpose, provided
* that existing copyright notices are retained in all copies and that this
* notice is included verbatim in any distributions. No written agreement,
* license, or royalty fee is required for any of the authorized uses.
* Modifications to this software may be copyrighted by their authors
* and need not follow the licensing terms described here, provided that
* the new terms are clearly indicated on the first page of each file where
* they apply.
*/
#include "cs3.h"
extern void __libc_init_array (void);
__attribute ((noreturn)) void __cs3_start_c (void){
unsigned regions = __cs3_region_num;
const struct __cs3_region *rptr = __cs3_regions;
/* Initialize memory */
for (regions = __cs3_region_num, rptr = __cs3_regions; regions--; rptr++) {
long long *src = (long long *)rptr->init;
long long *dst = (long long *)rptr->data;
unsigned limit = rptr->init_size;
unsigned count;
if (src != dst)
for (count = 0; count != limit; count += sizeof (long long))
*dst++ = *src++;
else
dst = (long long *)((char *)dst + limit);
limit = rptr->zero_size;
for (count = 0; count != limit; count += sizeof (long long))
*dst++ = 0;
}
/* Run initializers. */
__libc_init_array ();
osKernelInitialize();
osThreadCreate(&os_thread_def_main, NULL);
osKernelStart();
for (;;);
}
#else
__attribute__((naked)) void software_init_hook (void) {
__asm (
".syntax unified\n"
".thumb\n"
"movs r0,#0\n"
"movs r1,#0\n"
"mov r4,r0\n"
"mov r5,r1\n"
"ldr r0,= __libc_fini_array\n"
"bl atexit\n"
"bl __libc_init_array\n"
"mov r0,r4\n"
"mov r1,r5\n"
"bl osKernelInitialize\n"
"ldr r0,=os_thread_def_main\n"
"movs r1,#0\n"
"bl osThreadCreate\n"
"bl osKernelStart\n"
"bl exit\n"
);
}
#endif
#elif defined (__ICCARM__)
extern int __low_level_init(void);
extern void __iar_data_init3(void);
extern void exit(int arg);
__noreturn __stackless void __cmain(void) {
int a;
if (__low_level_init() != 0) {
__iar_data_init3();
}
osKernelInitialize();
osThreadCreate(&os_thread_def_main, NULL);
a = osKernelStart();
exit(a);
}
#endif
/*your_sha256_hash------------
* end of file
*your_sha256_hash-----------*/
``` | /content/code_sandbox/CMSIS/RTOS/RTX/INC/RTX_CM_lib.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 4,159 |
```shell
#!/bin/bash
VERSION=4.82.0
if [ -z "$JENKINS_FAMILY_ENV" ]; then
ARTIFACTORY_URL=path_to_url
else
ARTIFACTORY_URL=path_to_url
fi
if [ -z "$ARTIFACTORY_API_KEY" ]; then
echo "Please set your Artifactory in ARTIFACTORY_API_KEY"
echo ""
echo "1. Browse to $(dirname $(dirname $ARTIFACTORY_URL))/ui/admin/artifactory/user_profile"
echo "2. Copy the API Key"
echo "3. Add 'export ARTIFACTORY_API_KEY=\"<API Key>\"' to ~/.bashrc"
exit 1
fi
set -o pipefail
function usage {
echo "$(basename $0) [-h|--help] [-f|--force]"
echo ""
echo "Arguments:"
echo " -h|--help Print this usage message and exit."
echo " -f|--force Force (re)download."
echo ""
echo "Environment:"
echo " curl"
echo " sha256sum"
echo ""
}
POSITIONAL=()
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
'-h'|'--help')
usage
exit 1
;;
'-f'|'--force')
FORCE=1
;;
*) # unknown option
POSITIONAL+=("$1") # save it in an array for later
;;
esac
shift # past argument
done
set -- "${POSITIONAL[@]}" # restore positional parameters
pushd $(dirname $0) > /dev/null
ARCHIVE_NAME="RTX-${VERSION}.zip"
ARCHIVE_URL="${ARTIFACTORY_URL}/CMSIS_5/Libraries/${ARCHIVE_NAME}"
echo "Fetching ${ARCHIVE_URL}..."
if [[ $FORCE == 1 ]]; then
rm ${ARCHIVE_NAME}
fi
if [[ -f ${ARCHIVE_NAME} ]]; then
sha256sum=$(curl -s -I -H "X-JFrog-Art-Api:${ARTIFACTORY_API_KEY}" "${ARCHIVE_URL}" | grep "X-Checksum-Sha256" | cut -d" " -f2)
if echo "${sha256sum} *${ARCHIVE_NAME}" | sha256sum -c --status; then
echo "Already up-to-date"
else
rm ${ARCHIVE_NAME}
fi
fi
if [[ ! -f ${ARCHIVE_NAME} ]]; then
curl -C - -H "X-JFrog-Art-Api:${ARTIFACTORY_API_KEY}" -O "${ARCHIVE_URL}"
fi
unzip -u ${ARCHIVE_NAME}
exit 0
``` | /content/code_sandbox/CMSIS/RTOS/RTX/LIB/fetch_libs.sh | shell | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 596 |
```c
#include "cmsis_os.h" // CMSIS RTOS header file
/*your_sha256_hash------------
* Timer: Sample timer functions
*your_sha256_hash-----------*/
/*----- One-Shoot Timer Example -----*/
static void Timer1_Callback (void const *arg); // prototype for timer callback function
static osTimerId id1; // timer id
static uint32_t exec1; // argument for the timer call back function
static osTimerDef (Timer1, Timer1_Callback); // define timers
// One-Shoot Timer Function
static void Timer1_Callback (void const *arg) {
// add user code here
}
/*----- Periodic Timer Example -----*/
static void Timer2_Callback (void const *arg); // prototype for timer callback function
static osTimerId id2; // timer id
static uint32_t exec2; // argument for the timer call back function
static osTimerDef (Timer2, Timer2_Callback);
// Periodic Timer Example
static void Timer2_Callback (void const *arg) {
// add user code here
}
// Example: Create and Start timers
void Init_Timers (void) {
osStatus status; // function return status
// Create one-shoot timer
exec1 = 1;
id1 = osTimerCreate (osTimer(Timer1), osTimerOnce, &exec1);
if (id1 != NULL) { // One-shot timer created
// start timer with delay 100ms
status = osTimerStart (id1, 100);
if (status != osOK) {
// Timer could not be started
}
}
// Create periodic timer
exec2 = 2;
id2 = osTimerCreate (osTimer(Timer2), osTimerPeriodic, &exec2);
if (id2 != NULL) { // Periodic timer created
// start timer with periodic 1000ms interval
status = osTimerStart (id2, 1000);
if (status != osOK) {
// Timer could not be started
}
}
}
``` | /content/code_sandbox/CMSIS/RTOS/RTX/UserCodeTemplates/Timer.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 464 |
```c
#include "cmsis_os.h" // CMSIS RTOS header file
/*your_sha256_hash------------
* Mutex creation & usage
*your_sha256_hash-----------*/
void Thread_Mutex (void const *argument); // thread function
osThreadId tid_Thread_Mutex; // thread id
osThreadDef (Thread_Mutex, osPriorityNormal, 1, 0); // thread object
osMutexId mid_Thread_Mutex; // mutex id
osMutexDef (SampleMutex); // mutex name definition
int Init_Mutex (void) {
mid_Thread_Mutex = osMutexCreate (osMutex (SampleMutex));
if (!tid_Thread_Mutex) {
; // Mutex object not created, handle failure
}
tid_Thread_Mutex = osThreadCreate (osThread(Thread_Mutex), NULL);
if (!tid_Thread_Mutex) return(-1);
return(0);
}
void Thread_Mutex (void const *argument) {
osStatus status;
while (1) {
; // Insert thread code here...
status = osMutexWait (mid_Thread_Mutex, NULL);
switch (status) {
case osOK:
; // Use protected code here...
osMutexRelease (mid_Thread_Mutex);
break;
case osErrorTimeoutResource:
break;
case osErrorResource:
break;
case osErrorParameter:
break;
case osErrorISR:
break;
default:
break;
}
osThreadYield (); // suspend thread
}
}
``` | /content/code_sandbox/CMSIS/RTOS/RTX/UserCodeTemplates/Mutex.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 333 |
```c
#include "cmsis_os.h" // CMSIS RTOS header file
/*your_sha256_hash------------
* Memory Pool creation & usage
*your_sha256_hash-----------*/
#define MEMPOOL_OBJECTS 16 // number of Memory Pool Objects
typedef struct { // object data type
uint8_t Buf[32];
uint8_t Idx;
} MEM_BLOCK_t;
void Thread_MemPool (void const *argument); // thread function
osThreadId tid_Thread_MemPool; // thread id
osThreadDef (Thread_MemPool, osPriorityNormal, 1, 0); // thread object
osPoolId mpid_MemPool; // memory pool id
osPoolDef (MemPool, MEMPOOL_OBJECTS, MEM_BLOCK_t); // memory pool object
int Init_MemPool (void) {
mpid_MemPool = osPoolCreate (osPool (MemPool)); // create Mem Pool
if (!mpid_MemPool) {
; // MemPool object not created, handle failure
}
tid_Thread_MemPool = osThreadCreate (osThread(Thread_MemPool), NULL);
if (!tid_Thread_MemPool) return(-1);
return(0);
}
void Thread_MemPool (void const *argument) {
osStatus status;
MEM_BLOCK_t *pMem = 0;
while (1) {
; // Insert thread code here...
pMem = (MEM_BLOCK_t *)osPoolCAlloc (mpid_MemPool); // get Mem Block
if (pMem) { // Mem Block was available
pMem->Buf[0] = 0x55; // do some work...
pMem->Idx = 0;
status = osPoolFree (mpid_MemPool, pMem); // free mem block
switch (status) {
case osOK:
break;
case osErrorParameter:
break;
case osErrorValue:
break;
default:
break;
}
}
osThreadYield (); // suspend thread
}
}
``` | /content/code_sandbox/CMSIS/RTOS/RTX/UserCodeTemplates/MemPool.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 464 |
```c
/*your_sha256_hash------------
* CMSIS-RTOS 'main' function template
*your_sha256_hash-----------*/
#define osObjectsPublic // define objects in main module
#include "osObjects.h" // RTOS object definitions
/*
* main: initialize and start the system
*/
int main (void) {
osKernelInitialize (); // initialize CMSIS-RTOS
// initialize peripherals here
// create 'thread' functions that start executing,
// example: tid_name = osThreadCreate (osThread(name), NULL);
osKernelStart (); // start thread execution
}
``` | /content/code_sandbox/CMSIS/RTOS/RTX/UserCodeTemplates/main.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 126 |
```c
#include "cmsis_os.h" // CMSIS RTOS header file
/*your_sha256_hash------------
* Message Queue creation & usage
*your_sha256_hash-----------*/
void Thread_MsgQueue1 (void const *argument); // thread function 1
void Thread_MsgQueue2 (void const *argument); // thread function 2
osThreadId tid_Thread_MsgQueue1; // thread id 1
osThreadId tid_Thread_MsgQueue2; // thread id 2
osThreadDef (Thread_MsgQueue1, osPriorityNormal, 1, 0); // thread object 1
osThreadDef (Thread_MsgQueue2, osPriorityNormal, 1, 0); // thread object 2
#define MSGQUEUE_OBJECTS 16 // number of Message Queue Objects
typedef struct { // object data type
uint8_t Buf[32];
uint8_t Idx;
} MEM_BLOCK_t;
typedef struct { // object data type
uint8_t Buf[32];
uint8_t Idx;
} MSGQUEUE_OBJ_t;
osPoolId mpid_MemPool2; // memory pool id
osPoolDef (MemPool2, MSGQUEUE_OBJECTS, MEM_BLOCK_t); // memory pool object
osMessageQId mid_MsgQueue; // message queue id
osMessageQDef (MsgQueue, MSGQUEUE_OBJECTS, MSGQUEUE_OBJ_t); // message queue object
int Init_MsgQueue (void) {
mpid_MemPool2 = osPoolCreate (osPool (MemPool2)); // create Mem Pool
if (!mpid_MemPool2) {
; // MemPool object not created, handle failure
}
mid_MsgQueue = osMessageCreate (osMessageQ(MsgQueue), NULL); // create msg queue
if (!mid_MsgQueue) {
; // Message Queue object not created, handle failure
}
tid_Thread_MsgQueue1 = osThreadCreate (osThread(Thread_MsgQueue1), NULL);
if (!tid_Thread_MsgQueue1) return(-1);
tid_Thread_MsgQueue2 = osThreadCreate (osThread(Thread_MsgQueue2), NULL);
if (!tid_Thread_MsgQueue2) return(-1);
return(0);
}
void Thread_MsgQueue1 (void const *argument) {
MEM_BLOCK_t *pMsg = 0;
while (1) {
; // Insert thread code here...
pMsg = (MEM_BLOCK_t *)osPoolCAlloc (mpid_MemPool2); // get Mem Block
if (pMsg) { // Mem Block was available
pMsg->Buf[0] = 0x55; // do some work...
pMsg->Idx = 0;
osMessagePut (mid_MsgQueue, (uint32_t)pMsg, osWaitForever); // Send Message
}
osThreadYield (); // suspend thread
}
}
void Thread_MsgQueue2 (void const *argument) {
osEvent evt;
MEM_BLOCK_t *pMsg = 0;
while (1) {
; // Insert thread code here...
evt = osMessageGet (mid_MsgQueue, osWaitForever); // wait for message
if (evt.status == osEventMessage) {
pMsg = evt.value.p;
if (pMsg) {
; // process data
osPoolFree (mpid_MemPool2, pMsg); // free memory allocated for message
}
}
}
}
``` | /content/code_sandbox/CMSIS/RTOS/RTX/UserCodeTemplates/MsgQueue.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 761 |
```objective-c
/*your_sha256_hash------------
* osObjects.h: CMSIS-RTOS global object definitions for an application
*your_sha256_hash------------
*
* This header file defines global RTOS objects used throughout a project
*
* #define osObjectsPublic indicates that objects are defined; without that
* definition the objects are defined as external symbols.
*
*your_sha256_hash----------*/
#ifndef __osObjects
#define __osObjects
#if (!defined (osObjectsPublic))
#define osObjectsExternal // define RTOS objects with extern attribute
#endif
#include "cmsis_os.h" // CMSIS RTOS header file
// global 'thread' functions ---------------------------------------------------
/*
Example:
extern void sample_name (void const *argument); // thread function
osThreadId tid_sample_name; // thread id
osThreadDef (sample_name, osPriorityNormal, 1, 0); // thread object
*/
// global 'semaphores' ----------------------------------------------------------
/*
Example:
osSemaphoreId sid_sample_name; // semaphore id
osSemaphoreDef (sample_name); // semaphore object
*/
// global 'memory pools' --------------------------------------------------------
/*
Example:
typedef struct sample_name type_sample_name; // object data type
osPoolId mpid_sample_name; // memory pool id
osPoolDef (sample_name, 16, type_sample_name); // memory pool object
*/
// global 'message queues' -------------------------------------------------------
/*
Example:
typedef struct sample_name type_sample_name; // object data type
osMessageQId mid_sample_name; // message queue id
osMessageQDef (sample_name, 16, type_sample_name); // message queue object
*/
// global 'mail queues' ----------------------------------------------------------
/*
Example:
typedef struct sample_name type_sample_name; // object data type
osMailQId qid_sample_name; // mail queue id
osMailQDef (sample_name, 16, type_sample_name); // mail queue object
*/
#endif // __osObjects
``` | /content/code_sandbox/CMSIS/RTOS/RTX/UserCodeTemplates/osObjects.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 420 |
```c
#include "cmsis_os.h" // CMSIS RTOS header file
/*your_sha256_hash------------
* Thread 1 'Thread_Name': Sample thread
*your_sha256_hash-----------*/
void Thread (void const *argument); // thread function
osThreadId tid_Thread; // thread id
osThreadDef (Thread, osPriorityNormal, 1, 0); // thread object
int Init_Thread (void) {
tid_Thread = osThreadCreate (osThread(Thread), NULL);
if (!tid_Thread) return(-1);
return(0);
}
void Thread (void const *argument) {
while (1) {
; // Insert thread code here...
osThreadYield (); // suspend thread
}
}
``` | /content/code_sandbox/CMSIS/RTOS/RTX/UserCodeTemplates/Thread.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 162 |
```c
#include "cmsis_os.h" // CMSIS RTOS header file
/*your_sha256_hash------------
* Semaphore creation & usage
*your_sha256_hash-----------*/
void Thread_Semaphore (void const *argument); // thread function
osThreadId tid_Thread_Semaphore; // thread id
osThreadDef (Thread_Semaphore, osPriorityNormal, 1, 0); // thread object
osSemaphoreId sid_Thread_Semaphore; // semaphore id
osSemaphoreDef (SampleSemaphore); // semaphore object
int Init_Semaphore (void) {
sid_Thread_Semaphore = osSemaphoreCreate (osSemaphore(SampleSemaphore), 1);
if (!sid_Thread_Semaphore) {
; // Semaphore object not created, handle failure
}
tid_Thread_Semaphore = osThreadCreate (osThread(Thread_Semaphore), NULL);
if (!tid_Thread_Semaphore) return(-1);
return(0);
}
void Thread_Semaphore (void const *argument) {
int32_t val;
while (1) {
; // Insert thread code here...
val = osSemaphoreWait (sid_Thread_Semaphore, 10); // wait 10 mSec
switch (val) {
case osOK:
; // Use protected code here...
osSemaphoreRelease (sid_Thread_Semaphore); // Return a token back to a semaphore
break;
case osErrorResource:
break;
case osErrorParameter:
break;
default:
break;
}
osThreadYield (); // suspend thread
}
}
``` | /content/code_sandbox/CMSIS/RTOS/RTX/UserCodeTemplates/Semaphore.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 349 |
```c
#include "cmsis_os.h" // CMSIS RTOS header file
/*your_sha256_hash------------
* Mail Queue creation & usage
*your_sha256_hash-----------*/
void Thread_MailQueue1 (void const *argument); // thread function 1
void Thread_MailQueue2 (void const *argument); // thread function 2
osThreadId tid_Thread_MailQueue1; // thread id 1
osThreadId tid_Thread_MailQueue2; // thread id 2
osThreadDef (Thread_MailQueue1, osPriorityNormal, 1, 0); // thread object 1
osThreadDef (Thread_MailQueue2, osPriorityNormal, 1, 0); // thread object 2
#define MAILQUEUE_OBJECTS 16 // number of Message Queue Objects
typedef struct { // object data type
uint8_t Buf[32];
uint8_t Idx;
} MAILQUEUE_OBJ_t;
osMailQId qid_MailQueue; // mail queue id
osMailQDef (MailQueue, MAILQUEUE_OBJECTS, MAILQUEUE_OBJ_t); // mail queue object
int Init_MailQueue (void) {
qid_MailQueue = osMailCreate (osMailQ(MailQueue), NULL); // create mail queue
if (!qid_MailQueue) {
; // Mail Queue object not created, handle failure
}
tid_Thread_MailQueue1 = osThreadCreate (osThread(Thread_MailQueue1), NULL);
if (!tid_Thread_MailQueue1) return(-1);
tid_Thread_MailQueue2 = osThreadCreate (osThread(Thread_MailQueue2), NULL);
if (!tid_Thread_MailQueue2) return(-1);
return(0);
}
void Thread_MailQueue1 (void const *argument) {
MAILQUEUE_OBJ_t *pMail = 0;
while (1) {
; // Insert thread code here...
pMail = osMailAlloc (qid_MailQueue, osWaitForever); // Allocate memory
if (pMail) {
pMail->Buf[0] = 0xff; // Set the mail content
pMail->Idx = 0;
osMailPut (qid_MailQueue, pMail); // Send Mail
}
osThreadYield (); // suspend thread
}
}
void Thread_MailQueue2 (void const *argument) {
MAILQUEUE_OBJ_t *pMail = 0;
osEvent evt;
while (1) {
; // Insert thread code here...
evt = osMailGet (qid_MailQueue, osWaitForever); // wait for mail
if (evt.status == osEventMail) {
pMail = evt.value.p;
if (pMail) {
; // process data
osMailFree (qid_MailQueue, pMail); // free memory allocated for mail
}
}
}
}
``` | /content/code_sandbox/CMSIS/RTOS/RTX/UserCodeTemplates/MailQueue.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 648 |
```objective-c
/*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* your_sha256_hash------
*
* $Date: 5. December 2022
* $Revision: V2.1.2
*
* Project: CMSIS-DAP Include
* Title: DAP.h Definitions
*
*your_sha256_hash-----------*/
#ifndef __DAP_H__
#define __DAP_H__
// DAP Firmware Version
#ifdef DAP_FW_V1
#define DAP_FW_VER "1.3.0"
#else
#define DAP_FW_VER "2.1.2"
#endif
// DAP Command IDs
#define ID_DAP_Info 0x00U
#define ID_DAP_HostStatus 0x01U
#define ID_DAP_Connect 0x02U
#define ID_DAP_Disconnect 0x03U
#define ID_DAP_TransferConfigure 0x04U
#define ID_DAP_Transfer 0x05U
#define ID_DAP_TransferBlock 0x06U
#define ID_DAP_TransferAbort 0x07U
#define ID_DAP_WriteABORT 0x08U
#define ID_DAP_Delay 0x09U
#define ID_DAP_ResetTarget 0x0AU
#define ID_DAP_SWJ_Pins 0x10U
#define ID_DAP_SWJ_Clock 0x11U
#define ID_DAP_SWJ_Sequence 0x12U
#define ID_DAP_SWD_Configure 0x13U
#define ID_DAP_SWD_Sequence 0x1DU
#define ID_DAP_JTAG_Sequence 0x14U
#define ID_DAP_JTAG_Configure 0x15U
#define ID_DAP_JTAG_IDCODE 0x16U
#define ID_DAP_SWO_Transport 0x17U
#define ID_DAP_SWO_Mode 0x18U
#define ID_DAP_SWO_Baudrate 0x19U
#define ID_DAP_SWO_Control 0x1AU
#define ID_DAP_SWO_Status 0x1BU
#define ID_DAP_SWO_ExtendedStatus 0x1EU
#define ID_DAP_SWO_Data 0x1CU
#define ID_DAP_UART_Transport 0x1FU
#define ID_DAP_UART_Configure 0x20U
#define ID_DAP_UART_Control 0x22U
#define ID_DAP_UART_Status 0x23U
#define ID_DAP_UART_Transfer 0x21U
#define ID_DAP_QueueCommands 0x7EU
#define ID_DAP_ExecuteCommands 0x7FU
// DAP Vendor Command IDs
#define ID_DAP_Vendor0 0x80U
#define ID_DAP_Vendor1 0x81U
#define ID_DAP_Vendor2 0x82U
#define ID_DAP_Vendor3 0x83U
#define ID_DAP_Vendor4 0x84U
#define ID_DAP_Vendor5 0x85U
#define ID_DAP_Vendor6 0x86U
#define ID_DAP_Vendor7 0x87U
#define ID_DAP_Vendor8 0x88U
#define ID_DAP_Vendor9 0x89U
#define ID_DAP_Vendor10 0x8AU
#define ID_DAP_Vendor11 0x8BU
#define ID_DAP_Vendor12 0x8CU
#define ID_DAP_Vendor13 0x8DU
#define ID_DAP_Vendor14 0x8EU
#define ID_DAP_Vendor15 0x8FU
#define ID_DAP_Vendor16 0x90U
#define ID_DAP_Vendor17 0x91U
#define ID_DAP_Vendor18 0x92U
#define ID_DAP_Vendor19 0x93U
#define ID_DAP_Vendor20 0x94U
#define ID_DAP_Vendor21 0x95U
#define ID_DAP_Vendor22 0x96U
#define ID_DAP_Vendor23 0x97U
#define ID_DAP_Vendor24 0x98U
#define ID_DAP_Vendor25 0x99U
#define ID_DAP_Vendor26 0x9AU
#define ID_DAP_Vendor27 0x9BU
#define ID_DAP_Vendor28 0x9CU
#define ID_DAP_Vendor29 0x9DU
#define ID_DAP_Vendor30 0x9EU
#define ID_DAP_Vendor31 0x9FU
#define ID_DAP_Invalid 0xFFU
// DAP Status Code
#define DAP_OK 0U
#define DAP_ERROR 0xFFU
// DAP ID
#define DAP_ID_VENDOR 1U
#define DAP_ID_PRODUCT 2U
#define DAP_ID_SER_NUM 3U
#define DAP_ID_DAP_FW_VER 4U
#define DAP_ID_DEVICE_VENDOR 5U
#define DAP_ID_DEVICE_NAME 6U
#define DAP_ID_BOARD_VENDOR 7U
#define DAP_ID_BOARD_NAME 8U
#define DAP_ID_PRODUCT_FW_VER 9U
#define DAP_ID_CAPABILITIES 0xF0U
#define DAP_ID_TIMESTAMP_CLOCK 0xF1U
#define DAP_ID_UART_RX_BUFFER_SIZE 0xFBU
#define DAP_ID_UART_TX_BUFFER_SIZE 0xFCU
#define DAP_ID_SWO_BUFFER_SIZE 0xFDU
#define DAP_ID_PACKET_COUNT 0xFEU
#define DAP_ID_PACKET_SIZE 0xFFU
// DAP Host Status
#define DAP_DEBUGGER_CONNECTED 0U
#define DAP_TARGET_RUNNING 1U
// DAP Port
#define DAP_PORT_AUTODETECT 0U // Autodetect Port
#define DAP_PORT_DISABLED 0U // Port Disabled (I/O pins in High-Z)
#define DAP_PORT_SWD 1U // SWD Port (SWCLK, SWDIO) + nRESET
#define DAP_PORT_JTAG 2U // JTAG Port (TCK, TMS, TDI, TDO, nTRST) + nRESET
// DAP SWJ Pins
#define DAP_SWJ_SWCLK_TCK 0 // SWCLK/TCK
#define DAP_SWJ_SWDIO_TMS 1 // SWDIO/TMS
#define DAP_SWJ_TDI 2 // TDI
#define DAP_SWJ_TDO 3 // TDO
#define DAP_SWJ_nTRST 5 // nTRST
#define DAP_SWJ_nRESET 7 // nRESET
// DAP Transfer Request
#define DAP_TRANSFER_APnDP (1U<<0)
#define DAP_TRANSFER_RnW (1U<<1)
#define DAP_TRANSFER_A2 (1U<<2)
#define DAP_TRANSFER_A3 (1U<<3)
#define DAP_TRANSFER_MATCH_VALUE (1U<<4)
#define DAP_TRANSFER_MATCH_MASK (1U<<5)
#define DAP_TRANSFER_TIMESTAMP (1U<<7)
// DAP Transfer Response
#define DAP_TRANSFER_OK (1U<<0)
#define DAP_TRANSFER_WAIT (1U<<1)
#define DAP_TRANSFER_FAULT (1U<<2)
#define DAP_TRANSFER_ERROR (1U<<3)
#define DAP_TRANSFER_MISMATCH (1U<<4)
// DAP SWO Trace Mode
#define DAP_SWO_OFF 0U
#define DAP_SWO_UART 1U
#define DAP_SWO_MANCHESTER 2U
// DAP SWO Trace Status
#define DAP_SWO_CAPTURE_ACTIVE (1U<<0)
#define DAP_SWO_CAPTURE_PAUSED (1U<<1)
#define DAP_SWO_STREAM_ERROR (1U<<6)
#define DAP_SWO_BUFFER_OVERRUN (1U<<7)
// DAP UART Transport
#define DAP_UART_TRANSPORT_NONE 0U
#define DAP_UART_TRANSPORT_USB_COM_PORT 1U
#define DAP_UART_TRANSPORT_DAP_COMMAND 2U
// DAP UART Control
#define DAP_UART_CONTROL_RX_ENABLE (1U<<0)
#define DAP_UART_CONTROL_RX_DISABLE (1U<<1)
#define DAP_UART_CONTROL_RX_BUF_FLUSH (1U<<2)
#define DAP_UART_CONTROL_TX_ENABLE (1U<<4)
#define DAP_UART_CONTROL_TX_DISABLE (1U<<5)
#define DAP_UART_CONTROL_TX_BUF_FLUSH (1U<<6)
// DAP UART Status
#define DAP_UART_STATUS_RX_ENABLED (1U<<0)
#define DAP_UART_STATUS_RX_DATA_LOST (1U<<1)
#define DAP_UART_STATUS_FRAMING_ERROR (1U<<2)
#define DAP_UART_STATUS_PARITY_ERROR (1U<<3)
#define DAP_UART_STATUS_TX_ENABLED (1U<<4)
// DAP UART Configure Error
#define DAP_UART_CFG_ERROR_DATA_BITS (1U<<0)
#define DAP_UART_CFG_ERROR_PARITY (1U<<1)
#define DAP_UART_CFG_ERROR_STOP_BITS (1U<<2)
// Debug Port Register Addresses
#define DP_IDCODE 0x00U // IDCODE Register (SW Read only)
#define DP_ABORT 0x00U // Abort Register (SW Write only)
#define DP_CTRL_STAT 0x04U // Control & Status
#define DP_WCR 0x04U // Wire Control Register (SW Only)
#define DP_SELECT 0x08U // Select Register (JTAG R/W & SW W)
#define DP_RESEND 0x08U // Resend (SW Read Only)
#define DP_RDBUFF 0x0CU // Read Buffer (Read Only)
// JTAG IR Codes
#define JTAG_ABORT 0x08U
#define JTAG_DPACC 0x0AU
#define JTAG_APACC 0x0BU
#define JTAG_IDCODE 0x0EU
#define JTAG_BYPASS 0x0FU
// JTAG Sequence Info
#define JTAG_SEQUENCE_TCK 0x3FU // TCK count
#define JTAG_SEQUENCE_TMS 0x40U // TMS value
#define JTAG_SEQUENCE_TDO 0x80U // TDO capture
// SWD Sequence Info
#define SWD_SEQUENCE_CLK 0x3FU // SWCLK count
#define SWD_SEQUENCE_DIN 0x80U // SWDIO capture
#include <stddef.h>
#include <stdint.h>
#include "cmsis_compiler.h"
// DAP Data structure
typedef struct {
uint8_t debug_port; // Debug Port
uint8_t fast_clock; // Fast Clock Flag
uint8_t padding[2];
uint32_t clock_delay; // Clock Delay
uint32_t timestamp; // Last captured Timestamp
struct { // Transfer Configuration
uint8_t idle_cycles; // Idle cycles after transfer
uint8_t padding[3];
uint16_t retry_count; // Number of retries after WAIT response
uint16_t match_retry; // Number of retries if read value does not match
uint32_t match_mask; // Match Mask
} transfer;
#if (DAP_SWD != 0)
struct { // SWD Configuration
uint8_t turnaround; // Turnaround period
uint8_t data_phase; // Always generate Data Phase
} swd_conf;
#endif
#if (DAP_JTAG != 0)
struct { // JTAG Device Chain
uint8_t count; // Number of devices
uint8_t index; // Device index (device at TDO has index 0)
#if (DAP_JTAG_DEV_CNT != 0)
uint8_t ir_length[DAP_JTAG_DEV_CNT]; // IR Length in bits
uint16_t ir_before[DAP_JTAG_DEV_CNT]; // Bits before IR
uint16_t ir_after [DAP_JTAG_DEV_CNT]; // Bits after IR
#endif
} jtag_dev;
#endif
} DAP_Data_t;
extern DAP_Data_t DAP_Data; // DAP Data
extern volatile uint8_t DAP_TransferAbort; // Transfer Abort Flag
#ifdef __cplusplus
extern "C"
{
#endif
// Functions
extern void SWJ_Sequence (uint32_t count, const uint8_t *data);
extern void SWD_Sequence (uint32_t info, const uint8_t *swdo, uint8_t *swdi);
extern void JTAG_Sequence (uint32_t info, const uint8_t *tdi, uint8_t *tdo);
extern void JTAG_IR (uint32_t ir);
extern uint32_t JTAG_ReadIDCode (void);
extern void JTAG_WriteAbort (uint32_t data);
extern uint8_t JTAG_Transfer (uint32_t request, uint32_t *data);
extern uint8_t SWD_Transfer (uint32_t request, uint32_t *data);
extern void Delayms (uint32_t delay);
extern uint32_t SWO_Transport (const uint8_t *request, uint8_t *response);
extern uint32_t SWO_Mode (const uint8_t *request, uint8_t *response);
extern uint32_t SWO_Baudrate (const uint8_t *request, uint8_t *response);
extern uint32_t SWO_Control (const uint8_t *request, uint8_t *response);
extern uint32_t SWO_Status (uint8_t *response);
extern uint32_t SWO_ExtendedStatus (const uint8_t *request, uint8_t *response);
extern uint32_t SWO_Data (const uint8_t *request, uint8_t *response);
extern void SWO_QueueTransfer (uint8_t *buf, uint32_t num);
extern void SWO_AbortTransfer (void);
extern void SWO_TransferComplete (void);
extern uint32_t SWO_Mode_UART (uint32_t enable);
extern uint32_t SWO_Baudrate_UART (uint32_t baudrate);
extern uint32_t SWO_Control_UART (uint32_t active);
extern void SWO_Capture_UART (uint8_t *buf, uint32_t num);
extern uint32_t SWO_GetCount_UART (void);
extern uint32_t SWO_Mode_Manchester (uint32_t enable);
extern uint32_t SWO_Baudrate_Manchester (uint32_t baudrate);
extern uint32_t SWO_Control_Manchester (uint32_t active);
extern void SWO_Capture_Manchester (uint8_t *buf, uint32_t num);
extern uint32_t SWO_GetCount_Manchester (void);
extern uint32_t UART_Transport (const uint8_t *request, uint8_t *response);
extern uint32_t UART_Configure (const uint8_t *request, uint8_t *response);
extern uint32_t UART_Control (const uint8_t *request, uint8_t *response);
extern uint32_t UART_Status (uint8_t *response);
extern uint32_t UART_Transfer (const uint8_t *request, uint8_t *response);
extern uint8_t USB_COM_PORT_Activate (uint32_t cmd);
extern uint32_t DAP_ProcessVendorCommand (const uint8_t *request, uint8_t *response);
extern uint32_t DAP_ProcessCommand (const uint8_t *request, uint8_t *response);
extern uint32_t DAP_ExecuteCommand (const uint8_t *request, uint8_t *response);
extern void DAP_Setup (void);
// Configurable delay for clock generation
#ifndef DELAY_SLOW_CYCLES
#define DELAY_SLOW_CYCLES 3U // Number of cycles for one iteration
#endif
#if defined(__CC_ARM)
__STATIC_FORCEINLINE void PIN_DELAY_SLOW (uint32_t delay) {
uint32_t count = delay;
while (--count);
}
#else
__STATIC_FORCEINLINE void PIN_DELAY_SLOW (uint32_t delay) {
__ASM volatile (
".syntax unified\n"
"0:\n\t"
"subs %0,%0,#1\n\t"
"bne 0b\n"
: "+l" (delay) : : "cc"
);
}
#endif
// Fixed delay for fast clock generation
#ifndef DELAY_FAST_CYCLES
#define DELAY_FAST_CYCLES 0U // Number of cycles: 0..3
#endif
__STATIC_FORCEINLINE void PIN_DELAY_FAST (void) {
#if (DELAY_FAST_CYCLES >= 1U)
__NOP();
#endif
#if (DELAY_FAST_CYCLES >= 2U)
__NOP();
#endif
#if (DELAY_FAST_CYCLES >= 3U)
__NOP();
#endif
}
#ifdef __cplusplus
}
#endif
#endif /* __DAP_H__ */
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Include/DAP.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 3,851 |
```objective-c
/*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* your_sha256_hash------
*
* $Date: 16. June 2021
* $Revision: V2.1.0
*
* Project: CMSIS-DAP Configuration
* Title: DAP_config.h CMSIS-DAP Configuration File (Template)
*
*your_sha256_hash-----------*/
#ifndef __DAP_CONFIG_H__
#define __DAP_CONFIG_H__
//**************************************************************************************************
/**
\defgroup DAP_Config_Debug_gr CMSIS-DAP Debug Unit Information
\ingroup DAP_ConfigIO_gr
@{
Provides definitions about the hardware and configuration of the Debug Unit.
This information includes:
- Definition of Cortex-M processor parameters used in CMSIS-DAP Debug Unit.
- Debug Unit Identification strings (Vendor, Product, Serial Number).
- Debug Unit communication packet size.
- Debug Access Port supported modes and settings (JTAG/SWD and SWO).
- Optional information about a connected Target Device (for Evaluation Boards).
*/
#ifdef _RTE_
#include "RTE_Components.h"
#include CMSIS_device_header
#else
#include "device.h" // Debug Unit Cortex-M Processor Header File
#endif
/// Processor Clock of the Cortex-M MCU used in the Debug Unit.
/// This value is used to calculate the SWD/JTAG clock speed.
#define CPU_CLOCK 100000000U ///< Specifies the CPU Clock in Hz.
/// Number of processor cycles for I/O Port write operations.
/// This value is used to calculate the SWD/JTAG clock speed that is generated with I/O
/// Port write operations in the Debug Unit by a Cortex-M MCU. Most Cortex-M processors
/// require 2 processor cycles for a I/O Port Write operation. If the Debug Unit uses
/// a Cortex-M0+ processor with high-speed peripheral I/O only 1 processor cycle might be
/// required.
#define IO_PORT_WRITE_CYCLES 2U ///< I/O Cycles: 2=default, 1=Cortex-M0+ fast I/0.
/// Indicate that Serial Wire Debug (SWD) communication mode is available at the Debug Access Port.
/// This information is returned by the command \ref DAP_Info as part of <b>Capabilities</b>.
#define DAP_SWD 1 ///< SWD Mode: 1 = available, 0 = not available.
/// Indicate that JTAG communication mode is available at the Debug Port.
/// This information is returned by the command \ref DAP_Info as part of <b>Capabilities</b>.
#define DAP_JTAG 1 ///< JTAG Mode: 1 = available, 0 = not available.
/// Configure maximum number of JTAG devices on the scan chain connected to the Debug Access Port.
/// This setting impacts the RAM requirements of the Debug Unit. Valid range is 1 .. 255.
#define DAP_JTAG_DEV_CNT 8U ///< Maximum number of JTAG devices on scan chain.
/// Default communication mode on the Debug Access Port.
/// Used for the command \ref DAP_Connect when Port Default mode is selected.
#define DAP_DEFAULT_PORT 1U ///< Default JTAG/SWJ Port Mode: 1 = SWD, 2 = JTAG.
/// Default communication speed on the Debug Access Port for SWD and JTAG mode.
/// Used to initialize the default SWD/JTAG clock frequency.
/// The command \ref DAP_SWJ_Clock can be used to overwrite this default setting.
#define DAP_DEFAULT_SWJ_CLOCK 1000000U ///< Default SWD/JTAG clock frequency in Hz.
/// Maximum Package Size for Command and Response data.
/// This configuration settings is used to optimize the communication performance with the
/// debugger and depends on the USB peripheral. Typical vales are 64 for Full-speed USB HID or WinUSB,
/// 1024 for High-speed USB HID and 512 for High-speed USB WinUSB.
#define DAP_PACKET_SIZE 512U ///< Specifies Packet Size in bytes.
/// Maximum Package Buffers for Command and Response data.
/// This configuration settings is used to optimize the communication performance with the
/// debugger and depends on the USB peripheral. For devices with limited RAM or USB buffer the
/// setting can be reduced (valid range is 1 .. 255).
#define DAP_PACKET_COUNT 8U ///< Specifies number of packets buffered.
/// Indicate that UART Serial Wire Output (SWO) trace is available.
/// This information is returned by the command \ref DAP_Info as part of <b>Capabilities</b>.
#define SWO_UART 1 ///< SWO UART: 1 = available, 0 = not available.
/// USART Driver instance number for the UART SWO.
#define SWO_UART_DRIVER 0 ///< USART Driver instance number (Driver_USART#).
/// Maximum SWO UART Baudrate.
#define SWO_UART_MAX_BAUDRATE 10000000U ///< SWO UART Maximum Baudrate in Hz.
/// Indicate that Manchester Serial Wire Output (SWO) trace is available.
/// This information is returned by the command \ref DAP_Info as part of <b>Capabilities</b>.
#define SWO_MANCHESTER 0 ///< SWO Manchester: 1 = available, 0 = not available.
/// SWO Trace Buffer Size.
#define SWO_BUFFER_SIZE 4096U ///< SWO Trace Buffer Size in bytes (must be 2^n).
/// SWO Streaming Trace.
#define SWO_STREAM 0 ///< SWO Streaming Trace: 1 = available, 0 = not available.
/// Clock frequency of the Test Domain Timer. Timer value is returned with \ref TIMESTAMP_GET.
#define TIMESTAMP_CLOCK 100000000U ///< Timestamp clock in Hz (0 = timestamps not supported).
/// Indicate that UART Communication Port is available.
/// This information is returned by the command \ref DAP_Info as part of <b>Capabilities</b>.
#define DAP_UART 1 ///< DAP UART: 1 = available, 0 = not available.
/// USART Driver instance number for the UART Communication Port.
#define DAP_UART_DRIVER 1 ///< USART Driver instance number (Driver_USART#).
/// UART Receive Buffer Size.
#define DAP_UART_RX_BUFFER_SIZE 1024U ///< Uart Receive Buffer Size in bytes (must be 2^n).
/// UART Transmit Buffer Size.
#define DAP_UART_TX_BUFFER_SIZE 1024U ///< Uart Transmit Buffer Size in bytes (must be 2^n).
/// Indicate that UART Communication via USB COM Port is available.
/// This information is returned by the command \ref DAP_Info as part of <b>Capabilities</b>.
#define DAP_UART_USB_COM_PORT 1 ///< USB COM Port: 1 = available, 0 = not available.
/// Debug Unit is connected to fixed Target Device.
/// The Debug Unit may be part of an evaluation board and always connected to a fixed
/// known device. In this case a Device Vendor, Device Name, Board Vendor and Board Name strings
/// are stored and may be used by the debugger or IDE to configure device parameters.
#define TARGET_FIXED 0 ///< Target: 1 = known, 0 = unknown;
#define TARGET_DEVICE_VENDOR "Arm" ///< String indicating the Silicon Vendor
#define TARGET_DEVICE_NAME "Cortex-M" ///< String indicating the Target Device
#define TARGET_BOARD_VENDOR "Arm" ///< String indicating the Board Vendor
#define TARGET_BOARD_NAME "Arm board" ///< String indicating the Board Name
#if TARGET_FIXED != 0
#include <string.h>
static const char TargetDeviceVendor [] = TARGET_DEVICE_VENDOR;
static const char TargetDeviceName [] = TARGET_DEVICE_NAME;
static const char TargetBoardVendor [] = TARGET_BOARD_VENDOR;
static const char TargetBoardName [] = TARGET_BOARD_NAME;
#endif
/** Get Vendor Name string.
\param str Pointer to buffer to store the string (max 60 characters).
\return String length (including terminating NULL character) or 0 (no string).
*/
__STATIC_INLINE uint8_t DAP_GetVendorString (char *str) {
(void)str;
return (0U);
}
/** Get Product Name string.
\param str Pointer to buffer to store the string (max 60 characters).
\return String length (including terminating NULL character) or 0 (no string).
*/
__STATIC_INLINE uint8_t DAP_GetProductString (char *str) {
(void)str;
return (0U);
}
/** Get Serial Number string.
\param str Pointer to buffer to store the string (max 60 characters).
\return String length (including terminating NULL character) or 0 (no string).
*/
__STATIC_INLINE uint8_t DAP_GetSerNumString (char *str) {
(void)str;
return (0U);
}
/** Get Target Device Vendor string.
\param str Pointer to buffer to store the string (max 60 characters).
\return String length (including terminating NULL character) or 0 (no string).
*/
__STATIC_INLINE uint8_t DAP_GetTargetDeviceVendorString (char *str) {
#if TARGET_FIXED != 0
uint8_t len;
strcpy(str, TargetDeviceVendor);
len = (uint8_t)(strlen(TargetDeviceVendor) + 1U);
return (len);
#else
(void)str;
return (0U);
#endif
}
/** Get Target Device Name string.
\param str Pointer to buffer to store the string (max 60 characters).
\return String length (including terminating NULL character) or 0 (no string).
*/
__STATIC_INLINE uint8_t DAP_GetTargetDeviceNameString (char *str) {
#if TARGET_FIXED != 0
uint8_t len;
strcpy(str, TargetDeviceName);
len = (uint8_t)(strlen(TargetDeviceName) + 1U);
return (len);
#else
(void)str;
return (0U);
#endif
}
/** Get Target Board Vendor string.
\param str Pointer to buffer to store the string (max 60 characters).
\return String length (including terminating NULL character) or 0 (no string).
*/
__STATIC_INLINE uint8_t DAP_GetTargetBoardVendorString (char *str) {
#if TARGET_FIXED != 0
uint8_t len;
strcpy(str, TargetBoardVendor);
len = (uint8_t)(strlen(TargetBoardVendor) + 1U);
return (len);
#else
(void)str;
return (0U);
#endif
}
/** Get Target Board Name string.
\param str Pointer to buffer to store the string (max 60 characters).
\return String length (including terminating NULL character) or 0 (no string).
*/
__STATIC_INLINE uint8_t DAP_GetTargetBoardNameString (char *str) {
#if TARGET_FIXED != 0
uint8_t len;
strcpy(str, TargetBoardName);
len = (uint8_t)(strlen(TargetBoardName) + 1U);
return (len);
#else
(void)str;
return (0U);
#endif
}
/** Get Product Firmware Version string.
\param str Pointer to buffer to store the string (max 60 characters).
\return String length (including terminating NULL character) or 0 (no string).
*/
__STATIC_INLINE uint8_t DAP_GetProductFirmwareVersionString (char *str) {
(void)str;
return (0U);
}
///@}
//**************************************************************************************************
/**
\defgroup DAP_Config_PortIO_gr CMSIS-DAP Hardware I/O Pin Access
\ingroup DAP_ConfigIO_gr
@{
Standard I/O Pins of the CMSIS-DAP Hardware Debug Port support standard JTAG mode
and Serial Wire Debug (SWD) mode. In SWD mode only 2 pins are required to implement the debug
interface of a device. The following I/O Pins are provided:
JTAG I/O Pin | SWD I/O Pin | CMSIS-DAP Hardware pin mode
---------------------------- | -------------------- | ---------------------------------------------
TCK: Test Clock | SWCLK: Clock | Output Push/Pull
TMS: Test Mode Select | SWDIO: Data I/O | Output Push/Pull; Input (for receiving data)
TDI: Test Data Input | | Output Push/Pull
TDO: Test Data Output | | Input
nTRST: Test Reset (optional) | | Output Open Drain with pull-up resistor
nRESET: Device Reset | nRESET: Device Reset | Output Open Drain with pull-up resistor
DAP Hardware I/O Pin Access Functions
-------------------------------------
The various I/O Pins are accessed by functions that implement the Read, Write, Set, or Clear to
these I/O Pins.
For the SWDIO I/O Pin there are additional functions that are called in SWD I/O mode only.
This functions are provided to achieve faster I/O that is possible with some advanced GPIO
peripherals that can independently write/read a single I/O pin without affecting any other pins
of the same I/O port. The following SWDIO I/O Pin functions are provided:
- \ref PIN_SWDIO_OUT_ENABLE to enable the output mode from the DAP hardware.
- \ref PIN_SWDIO_OUT_DISABLE to enable the input mode to the DAP hardware.
- \ref PIN_SWDIO_IN to read from the SWDIO I/O pin with utmost possible speed.
- \ref PIN_SWDIO_OUT to write to the SWDIO I/O pin with utmost possible speed.
*/
// Configure DAP I/O pins ------------------------------
/** Setup JTAG I/O pins: TCK, TMS, TDI, TDO, nTRST, and nRESET.
Configures the DAP Hardware I/O pins for JTAG mode:
- TCK, TMS, TDI, nTRST, nRESET to output mode and set to high level.
- TDO to input mode.
*/
__STATIC_INLINE void PORT_JTAG_SETUP (void) {
;
}
/** Setup SWD I/O pins: SWCLK, SWDIO, and nRESET.
Configures the DAP Hardware I/O pins for Serial Wire Debug (SWD) mode:
- SWCLK, SWDIO, nRESET to output mode and set to default high level.
- TDI, nTRST to HighZ mode (pins are unused in SWD mode).
*/
__STATIC_INLINE void PORT_SWD_SETUP (void) {
;
}
/** Disable JTAG/SWD I/O Pins.
Disables the DAP Hardware I/O pins which configures:
- TCK/SWCLK, TMS/SWDIO, TDI, TDO, nTRST, nRESET to High-Z mode.
*/
__STATIC_INLINE void PORT_OFF (void) {
;
}
// SWCLK/TCK I/O pin -------------------------------------
/** SWCLK/TCK I/O pin: Get Input.
\return Current status of the SWCLK/TCK DAP hardware I/O pin.
*/
__STATIC_FORCEINLINE uint32_t PIN_SWCLK_TCK_IN (void) {
return (0U);
}
/** SWCLK/TCK I/O pin: Set Output to High.
Set the SWCLK/TCK DAP hardware I/O pin to high level.
*/
__STATIC_FORCEINLINE void PIN_SWCLK_TCK_SET (void) {
;
}
/** SWCLK/TCK I/O pin: Set Output to Low.
Set the SWCLK/TCK DAP hardware I/O pin to low level.
*/
__STATIC_FORCEINLINE void PIN_SWCLK_TCK_CLR (void) {
;
}
// SWDIO/TMS Pin I/O --------------------------------------
/** SWDIO/TMS I/O pin: Get Input.
\return Current status of the SWDIO/TMS DAP hardware I/O pin.
*/
__STATIC_FORCEINLINE uint32_t PIN_SWDIO_TMS_IN (void) {
return (0U);
}
/** SWDIO/TMS I/O pin: Set Output to High.
Set the SWDIO/TMS DAP hardware I/O pin to high level.
*/
__STATIC_FORCEINLINE void PIN_SWDIO_TMS_SET (void) {
;
}
/** SWDIO/TMS I/O pin: Set Output to Low.
Set the SWDIO/TMS DAP hardware I/O pin to low level.
*/
__STATIC_FORCEINLINE void PIN_SWDIO_TMS_CLR (void) {
;
}
/** SWDIO I/O pin: Get Input (used in SWD mode only).
\return Current status of the SWDIO DAP hardware I/O pin.
*/
__STATIC_FORCEINLINE uint32_t PIN_SWDIO_IN (void) {
return (0U);
}
/** SWDIO I/O pin: Set Output (used in SWD mode only).
\param bit Output value for the SWDIO DAP hardware I/O pin.
*/
__STATIC_FORCEINLINE void PIN_SWDIO_OUT (uint32_t bit) {
;
}
/** SWDIO I/O pin: Switch to Output mode (used in SWD mode only).
Configure the SWDIO DAP hardware I/O pin to output mode. This function is
called prior \ref PIN_SWDIO_OUT function calls.
*/
__STATIC_FORCEINLINE void PIN_SWDIO_OUT_ENABLE (void) {
;
}
/** SWDIO I/O pin: Switch to Input mode (used in SWD mode only).
Configure the SWDIO DAP hardware I/O pin to input mode. This function is
called prior \ref PIN_SWDIO_IN function calls.
*/
__STATIC_FORCEINLINE void PIN_SWDIO_OUT_DISABLE (void) {
;
}
// TDI Pin I/O ---------------------------------------------
/** TDI I/O pin: Get Input.
\return Current status of the TDI DAP hardware I/O pin.
*/
__STATIC_FORCEINLINE uint32_t PIN_TDI_IN (void) {
return (0U);
}
/** TDI I/O pin: Set Output.
\param bit Output value for the TDI DAP hardware I/O pin.
*/
__STATIC_FORCEINLINE void PIN_TDI_OUT (uint32_t bit) {
;
}
// TDO Pin I/O ---------------------------------------------
/** TDO I/O pin: Get Input.
\return Current status of the TDO DAP hardware I/O pin.
*/
__STATIC_FORCEINLINE uint32_t PIN_TDO_IN (void) {
return (0U);
}
// nTRST Pin I/O -------------------------------------------
/** nTRST I/O pin: Get Input.
\return Current status of the nTRST DAP hardware I/O pin.
*/
__STATIC_FORCEINLINE uint32_t PIN_nTRST_IN (void) {
return (0U);
}
/** nTRST I/O pin: Set Output.
\param bit JTAG TRST Test Reset pin status:
- 0: issue a JTAG TRST Test Reset.
- 1: release JTAG TRST Test Reset.
*/
__STATIC_FORCEINLINE void PIN_nTRST_OUT (uint32_t bit) {
;
}
// nRESET Pin I/O------------------------------------------
/** nRESET I/O pin: Get Input.
\return Current status of the nRESET DAP hardware I/O pin.
*/
__STATIC_FORCEINLINE uint32_t PIN_nRESET_IN (void) {
return (0U);
}
/** nRESET I/O pin: Set Output.
\param bit target device hardware reset pin status:
- 0: issue a device hardware reset.
- 1: release device hardware reset.
*/
__STATIC_FORCEINLINE void PIN_nRESET_OUT (uint32_t bit) {
;
}
///@}
//**************************************************************************************************
/**
\defgroup DAP_Config_LEDs_gr CMSIS-DAP Hardware Status LEDs
\ingroup DAP_ConfigIO_gr
@{
CMSIS-DAP Hardware may provide LEDs that indicate the status of the CMSIS-DAP Debug Unit.
It is recommended to provide the following LEDs for status indication:
- Connect LED: is active when the DAP hardware is connected to a debugger.
- Running LED: is active when the debugger has put the target device into running state.
*/
/** Debug Unit: Set status of Connected LED.
\param bit status of the Connect LED.
- 1: Connect LED ON: debugger is connected to CMSIS-DAP Debug Unit.
- 0: Connect LED OFF: debugger is not connected to CMSIS-DAP Debug Unit.
*/
__STATIC_INLINE void LED_CONNECTED_OUT (uint32_t bit) {}
/** Debug Unit: Set status Target Running LED.
\param bit status of the Target Running LED.
- 1: Target Running LED ON: program execution in target started.
- 0: Target Running LED OFF: program execution in target stopped.
*/
__STATIC_INLINE void LED_RUNNING_OUT (uint32_t bit) {}
///@}
//**************************************************************************************************
/**
\defgroup DAP_Config_Timestamp_gr CMSIS-DAP Timestamp
\ingroup DAP_ConfigIO_gr
@{
Access function for Test Domain Timer.
The value of the Test Domain Timer in the Debug Unit is returned by the function \ref TIMESTAMP_GET. By
default, the DWT timer is used. The frequency of this timer is configured with \ref TIMESTAMP_CLOCK.
*/
/** Get timestamp of Test Domain Timer.
\return Current timestamp value.
*/
__STATIC_INLINE uint32_t TIMESTAMP_GET (void) {
return (DWT->CYCCNT);
}
///@}
//**************************************************************************************************
/**
\defgroup DAP_Config_Initialization_gr CMSIS-DAP Initialization
\ingroup DAP_ConfigIO_gr
@{
CMSIS-DAP Hardware I/O and LED Pins are initialized with the function \ref DAP_SETUP.
*/
/** Setup of the Debug Unit I/O pins and LEDs (called when Debug Unit is initialized).
This function performs the initialization of the CMSIS-DAP Hardware I/O Pins and the
Status LEDs. In detail the operation of Hardware I/O and LED pins are enabled and set:
- I/O clock system enabled.
- all I/O pins: input buffer enabled, output pins are set to HighZ mode.
- for nTRST, nRESET a weak pull-up (if available) is enabled.
- LED output pins are enabled and LEDs are turned off.
*/
__STATIC_INLINE void DAP_SETUP (void) {
;
}
/** Reset Target Device with custom specific I/O pin or command sequence.
This function allows the optional implementation of a device specific reset sequence.
It is called when the command \ref DAP_ResetTarget and is for example required
when a device needs a time-critical unlock sequence that enables the debug port.
\return 0 = no device specific reset sequence is implemented.\n
1 = a device specific reset sequence is implemented.
*/
__STATIC_INLINE uint8_t RESET_TARGET (void) {
return (0U); // change to '1' when a device reset sequence is implemented
}
///@}
#endif /* __DAP_CONFIG_H__ */
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Config/DAP_config.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 4,834 |
```c
/*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* your_sha256_hash------
*
* $Date: 1. December 2017
* $Revision: V2.0.0
*
* Project: CMSIS-DAP Source
* Title: JTAG_DP.c CMSIS-DAP JTAG DP I/O
*
*your_sha256_hash-----------*/
#include "DAP_config.h"
#include "DAP.h"
// JTAG Macros
#define PIN_TCK_SET PIN_SWCLK_TCK_SET
#define PIN_TCK_CLR PIN_SWCLK_TCK_CLR
#define PIN_TMS_SET PIN_SWDIO_TMS_SET
#define PIN_TMS_CLR PIN_SWDIO_TMS_CLR
#define JTAG_CYCLE_TCK() \
PIN_TCK_CLR(); \
PIN_DELAY(); \
PIN_TCK_SET(); \
PIN_DELAY()
#define JTAG_CYCLE_TDI(tdi) \
PIN_TDI_OUT(tdi); \
PIN_TCK_CLR(); \
PIN_DELAY(); \
PIN_TCK_SET(); \
PIN_DELAY()
#define JTAG_CYCLE_TDO(tdo) \
PIN_TCK_CLR(); \
PIN_DELAY(); \
tdo = PIN_TDO_IN(); \
PIN_TCK_SET(); \
PIN_DELAY()
#define JTAG_CYCLE_TDIO(tdi,tdo) \
PIN_TDI_OUT(tdi); \
PIN_TCK_CLR(); \
PIN_DELAY(); \
tdo = PIN_TDO_IN(); \
PIN_TCK_SET(); \
PIN_DELAY()
#define PIN_DELAY() PIN_DELAY_SLOW(DAP_Data.clock_delay)
#if (DAP_JTAG != 0)
// Generate JTAG Sequence
// info: sequence information
// tdi: pointer to TDI generated data
// tdo: pointer to TDO captured data
// return: none
void JTAG_Sequence (uint32_t info, const uint8_t *tdi, uint8_t *tdo) {
uint32_t i_val;
uint32_t o_val;
uint32_t bit;
uint32_t n, k;
n = info & JTAG_SEQUENCE_TCK;
if (n == 0U) {
n = 64U;
}
if (info & JTAG_SEQUENCE_TMS) {
PIN_TMS_SET();
} else {
PIN_TMS_CLR();
}
while (n) {
i_val = *tdi++;
o_val = 0U;
for (k = 8U; k && n; k--, n--) {
JTAG_CYCLE_TDIO(i_val, bit);
i_val >>= 1;
o_val >>= 1;
o_val |= bit << 7;
}
o_val >>= k;
if (info & JTAG_SEQUENCE_TDO) {
*tdo++ = (uint8_t)o_val;
}
}
}
// JTAG Set IR
// ir: IR value
// return: none
#define JTAG_IR_Function(speed) /**/ \
static void JTAG_IR_##speed (uint32_t ir) { \
uint32_t n; \
\
PIN_TMS_SET(); \
JTAG_CYCLE_TCK(); /* Select-DR-Scan */ \
JTAG_CYCLE_TCK(); /* Select-IR-Scan */ \
PIN_TMS_CLR(); \
JTAG_CYCLE_TCK(); /* Capture-IR */ \
JTAG_CYCLE_TCK(); /* Shift-IR */ \
\
PIN_TDI_OUT(1U); \
for (n = DAP_Data.jtag_dev.ir_before[DAP_Data.jtag_dev.index]; n; n--) { \
JTAG_CYCLE_TCK(); /* Bypass before data */ \
} \
for (n = DAP_Data.jtag_dev.ir_length[DAP_Data.jtag_dev.index] - 1U; n; n--) { \
JTAG_CYCLE_TDI(ir); /* Set IR bits (except last) */ \
ir >>= 1; \
} \
n = DAP_Data.jtag_dev.ir_after[DAP_Data.jtag_dev.index]; \
if (n) { \
JTAG_CYCLE_TDI(ir); /* Set last IR bit */ \
PIN_TDI_OUT(1U); \
for (--n; n; n--) { \
JTAG_CYCLE_TCK(); /* Bypass after data */ \
} \
PIN_TMS_SET(); \
JTAG_CYCLE_TCK(); /* Bypass & Exit1-IR */ \
} else { \
PIN_TMS_SET(); \
JTAG_CYCLE_TDI(ir); /* Set last IR bit & Exit1-IR */ \
} \
\
JTAG_CYCLE_TCK(); /* Update-IR */ \
PIN_TMS_CLR(); \
JTAG_CYCLE_TCK(); /* Idle */ \
PIN_TDI_OUT(1U); \
}
// JTAG Transfer I/O
// request: A[3:2] RnW APnDP
// data: DATA[31:0]
// return: ACK[2:0]
#define JTAG_TransferFunction(speed) /**/ \
static uint8_t JTAG_Transfer##speed (uint32_t request, uint32_t *data) { \
uint32_t ack; \
uint32_t bit; \
uint32_t val; \
uint32_t n; \
\
PIN_TMS_SET(); \
JTAG_CYCLE_TCK(); /* Select-DR-Scan */ \
PIN_TMS_CLR(); \
JTAG_CYCLE_TCK(); /* Capture-DR */ \
JTAG_CYCLE_TCK(); /* Shift-DR */ \
\
for (n = DAP_Data.jtag_dev.index; n; n--) { \
JTAG_CYCLE_TCK(); /* Bypass before data */ \
} \
\
JTAG_CYCLE_TDIO(request >> 1, bit); /* Set RnW, Get ACK.0 */ \
ack = bit << 1; \
JTAG_CYCLE_TDIO(request >> 2, bit); /* Set A2, Get ACK.1 */ \
ack |= bit << 0; \
JTAG_CYCLE_TDIO(request >> 3, bit); /* Set A3, Get ACK.2 */ \
ack |= bit << 2; \
\
if (ack != DAP_TRANSFER_OK) { \
/* Exit on error */ \
PIN_TMS_SET(); \
JTAG_CYCLE_TCK(); /* Exit1-DR */ \
goto exit; \
} \
\
if (request & DAP_TRANSFER_RnW) { \
/* Read Transfer */ \
val = 0U; \
for (n = 31U; n; n--) { \
JTAG_CYCLE_TDO(bit); /* Get D0..D30 */ \
val |= bit << 31; \
val >>= 1; \
} \
n = DAP_Data.jtag_dev.count - DAP_Data.jtag_dev.index - 1U; \
if (n) { \
JTAG_CYCLE_TDO(bit); /* Get D31 */ \
for (--n; n; n--) { \
JTAG_CYCLE_TCK(); /* Bypass after data */ \
} \
PIN_TMS_SET(); \
JTAG_CYCLE_TCK(); /* Bypass & Exit1-DR */ \
} else { \
PIN_TMS_SET(); \
JTAG_CYCLE_TDO(bit); /* Get D31 & Exit1-DR */ \
} \
val |= bit << 31; \
if (data) { *data = val; } \
} else { \
/* Write Transfer */ \
val = *data; \
for (n = 31U; n; n--) { \
JTAG_CYCLE_TDI(val); /* Set D0..D30 */ \
val >>= 1; \
} \
n = DAP_Data.jtag_dev.count - DAP_Data.jtag_dev.index - 1U; \
if (n) { \
JTAG_CYCLE_TDI(val); /* Set D31 */ \
for (--n; n; n--) { \
JTAG_CYCLE_TCK(); /* Bypass after data */ \
} \
PIN_TMS_SET(); \
JTAG_CYCLE_TCK(); /* Bypass & Exit1-DR */ \
} else { \
PIN_TMS_SET(); \
JTAG_CYCLE_TDI(val); /* Set D31 & Exit1-DR */ \
} \
} \
\
exit: \
JTAG_CYCLE_TCK(); /* Update-DR */ \
PIN_TMS_CLR(); \
JTAG_CYCLE_TCK(); /* Idle */ \
PIN_TDI_OUT(1U); \
\
/* Capture Timestamp */ \
if (request & DAP_TRANSFER_TIMESTAMP) { \
DAP_Data.timestamp = TIMESTAMP_GET(); \
} \
\
/* Idle cycles */ \
n = DAP_Data.transfer.idle_cycles; \
while (n--) { \
JTAG_CYCLE_TCK(); /* Idle */ \
} \
\
return ((uint8_t)ack); \
}
#undef PIN_DELAY
#define PIN_DELAY() PIN_DELAY_FAST()
JTAG_IR_Function(Fast)
JTAG_TransferFunction(Fast)
#undef PIN_DELAY
#define PIN_DELAY() PIN_DELAY_SLOW(DAP_Data.clock_delay)
JTAG_IR_Function(Slow)
JTAG_TransferFunction(Slow)
// JTAG Read IDCODE register
// return: value read
uint32_t JTAG_ReadIDCode (void) {
uint32_t bit;
uint32_t val;
uint32_t n;
PIN_TMS_SET();
JTAG_CYCLE_TCK(); /* Select-DR-Scan */
PIN_TMS_CLR();
JTAG_CYCLE_TCK(); /* Capture-DR */
JTAG_CYCLE_TCK(); /* Shift-DR */
for (n = DAP_Data.jtag_dev.index; n; n--) {
JTAG_CYCLE_TCK(); /* Bypass before data */
}
val = 0U;
for (n = 31U; n; n--) {
JTAG_CYCLE_TDO(bit); /* Get D0..D30 */
val |= bit << 31;
val >>= 1;
}
PIN_TMS_SET();
JTAG_CYCLE_TDO(bit); /* Get D31 & Exit1-DR */
val |= bit << 31;
JTAG_CYCLE_TCK(); /* Update-DR */
PIN_TMS_CLR();
JTAG_CYCLE_TCK(); /* Idle */
return (val);
}
// JTAG Write ABORT register
// data: value to write
// return: none
void JTAG_WriteAbort (uint32_t data) {
uint32_t n;
PIN_TMS_SET();
JTAG_CYCLE_TCK(); /* Select-DR-Scan */
PIN_TMS_CLR();
JTAG_CYCLE_TCK(); /* Capture-DR */
JTAG_CYCLE_TCK(); /* Shift-DR */
for (n = DAP_Data.jtag_dev.index; n; n--) {
JTAG_CYCLE_TCK(); /* Bypass before data */
}
PIN_TDI_OUT(0U);
JTAG_CYCLE_TCK(); /* Set RnW=0 (Write) */
JTAG_CYCLE_TCK(); /* Set A2=0 */
JTAG_CYCLE_TCK(); /* Set A3=0 */
for (n = 31U; n; n--) {
JTAG_CYCLE_TDI(data); /* Set D0..D30 */
data >>= 1;
}
n = DAP_Data.jtag_dev.count - DAP_Data.jtag_dev.index - 1U;
if (n) {
JTAG_CYCLE_TDI(data); /* Set D31 */
for (--n; n; n--) {
JTAG_CYCLE_TCK(); /* Bypass after data */
}
PIN_TMS_SET();
JTAG_CYCLE_TCK(); /* Bypass & Exit1-DR */
} else {
PIN_TMS_SET();
JTAG_CYCLE_TDI(data); /* Set D31 & Exit1-DR */
}
JTAG_CYCLE_TCK(); /* Update-DR */
PIN_TMS_CLR();
JTAG_CYCLE_TCK(); /* Idle */
PIN_TDI_OUT(1U);
}
// JTAG Set IR
// ir: IR value
// return: none
void JTAG_IR (uint32_t ir) {
if (DAP_Data.fast_clock) {
JTAG_IR_Fast(ir);
} else {
JTAG_IR_Slow(ir);
}
}
// JTAG Transfer I/O
// request: A[3:2] RnW APnDP
// data: DATA[31:0]
// return: ACK[2:0]
uint8_t JTAG_Transfer(uint32_t request, uint32_t *data) {
if (DAP_Data.fast_clock) {
return JTAG_TransferFast(request, data);
} else {
return JTAG_TransferSlow(request, data);
}
}
#endif /* (DAP_JTAG != 0) */
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Source/JTAG_DP.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 3,053 |
```c
/*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* your_sha256_hash------
*
* $Date: 1. December 2017
* $Revision: V2.0.0
*
* Project: CMSIS-DAP Source
* Title: DAP_vendor.c CMSIS-DAP Vendor Commands
*
*your_sha256_hash-----------*/
#include "DAP_config.h"
#include "DAP.h"
//**************************************************************************************************
/**
\defgroup DAP_Vendor_Adapt_gr Adapt Vendor Commands
\ingroup DAP_Vendor_gr
@{
The file DAP_vendor.c provides template source code for extension of a Debug Unit with
Vendor Commands. Copy this file to the project folder of the Debug Unit and add the
file to the MDK-ARM project under the file group Configuration.
*/
/** Process DAP Vendor Command and prepare Response Data
\param request pointer to request data
\param response pointer to response data
\return number of bytes in response (lower 16 bits)
number of bytes in request (upper 16 bits)
*/
uint32_t DAP_ProcessVendorCommand(const uint8_t *request, uint8_t *response) {
uint32_t num = (1U << 16) | 1U;
*response++ = *request; // copy Command ID
switch (*request++) { // first byte in request is Command ID
case ID_DAP_Vendor0:
#if 0 // example user command
num += 1U << 16; // increment request count
if (*request == 1U) { // when first command data byte is 1
*response++ = 'X'; // send 'X' as response
num++; // increment response count
}
#endif
break;
case ID_DAP_Vendor1: break;
case ID_DAP_Vendor2: break;
case ID_DAP_Vendor3: break;
case ID_DAP_Vendor4: break;
case ID_DAP_Vendor5: break;
case ID_DAP_Vendor6: break;
case ID_DAP_Vendor7: break;
case ID_DAP_Vendor8: break;
case ID_DAP_Vendor9: break;
case ID_DAP_Vendor10: break;
case ID_DAP_Vendor11: break;
case ID_DAP_Vendor12: break;
case ID_DAP_Vendor13: break;
case ID_DAP_Vendor14: break;
case ID_DAP_Vendor15: break;
case ID_DAP_Vendor16: break;
case ID_DAP_Vendor17: break;
case ID_DAP_Vendor18: break;
case ID_DAP_Vendor19: break;
case ID_DAP_Vendor20: break;
case ID_DAP_Vendor21: break;
case ID_DAP_Vendor22: break;
case ID_DAP_Vendor23: break;
case ID_DAP_Vendor24: break;
case ID_DAP_Vendor25: break;
case ID_DAP_Vendor26: break;
case ID_DAP_Vendor27: break;
case ID_DAP_Vendor28: break;
case ID_DAP_Vendor29: break;
case ID_DAP_Vendor30: break;
case ID_DAP_Vendor31: break;
}
return (num);
}
///@}
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Source/DAP_vendor.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 775 |
```c
/*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* your_sha256_hash------
*
* $Date: 1. March 2021
* $Revision: V1.0.0
*
* Project: CMSIS-DAP Source
* Title: UART.c CMSIS-DAP UART
*
*your_sha256_hash-----------*/
#include "DAP_config.h"
#include "DAP.h"
#if (DAP_UART != 0)
#ifdef DAP_FW_V1
#error "UART Communication Port not supported in DAP V1!"
#endif
#include "Driver_USART.h"
#include "cmsis_os2.h"
#include <string.h>
#define UART_RX_BLOCK_SIZE 32U /* Uart Rx Block Size (must be 2^n) */
// USART Driver
#define _USART_Driver_(n) Driver_USART##n
#define USART_Driver_(n) _USART_Driver_(n)
extern ARM_DRIVER_USART USART_Driver_(DAP_UART_DRIVER);
#define pUSART (&USART_Driver_(DAP_UART_DRIVER))
// UART Configuration
#if (DAP_UART_USB_COM_PORT != 0)
static uint8_t UartTransport = DAP_UART_TRANSPORT_USB_COM_PORT;
#else
static uint8_t UartTransport = DAP_UART_TRANSPORT_NONE;
#endif
// UART Flags
static uint8_t UartConfigured = 0U;
static uint8_t UartReceiveEnabled = 0U;
static uint8_t UartTransmitEnabled = 0U;
static uint8_t UartTransmitActive = 0U;
// UART TX Buffer
static uint8_t UartTxBuf[DAP_UART_TX_BUFFER_SIZE];
static volatile uint32_t UartTxIndexI = 0U;
static volatile uint32_t UartTxIndexO = 0U;
// UART RX Buffer
static uint8_t UartRxBuf[DAP_UART_RX_BUFFER_SIZE];
static volatile uint32_t UartRxIndexI = 0U;
static volatile uint32_t UartRxIndexO = 0U;
// Uart Errors
static volatile uint8_t UartErrorRxDataLost = 0U;
static volatile uint8_t UartErrorFraming = 0U;
static volatile uint8_t UartErrorParity = 0U;
// UART Transmit
static uint32_t UartTxNum = 0U;
// Function prototypes
static uint8_t UART_Init (void);
static void UART_Uninit (void);
static uint8_t UART_Get_Status (void);
static uint8_t UART_Receive_Enable (void);
static uint8_t UART_Transmit_Enable (void);
static void UART_Receive_Disable (void);
static void UART_Transmit_Disable (void);
static void UART_Receive_Flush (void);
static void UART_Transmit_Flush (void);
static void UART_Receive (void);
static void UART_Transmit (void);
// USART Driver Callback function
// event: event mask
static void USART_Callback (uint32_t event) {
if (event & ARM_USART_EVENT_SEND_COMPLETE) {
UartTxIndexO += UartTxNum;
UartTransmitActive = 0U;
UART_Transmit();
}
if (event & ARM_USART_EVENT_RECEIVE_COMPLETE) {
UartRxIndexI += UART_RX_BLOCK_SIZE;
UART_Receive();
}
if (event & ARM_USART_EVENT_RX_OVERFLOW) {
UartErrorRxDataLost = 1U;
}
if (event & ARM_USART_EVENT_RX_FRAMING_ERROR) {
UartErrorFraming = 1U;
}
if (event & ARM_USART_EVENT_RX_PARITY_ERROR) {
UartErrorParity = 1U;
}
}
// Init UART
// return: DAP_OK or DAP_ERROR
static uint8_t UART_Init (void) {
int32_t status;
uint8_t ret = DAP_ERROR;
UartConfigured = 0U;
UartReceiveEnabled = 0U;
UartTransmitEnabled = 0U;
UartTransmitActive = 0U;
UartErrorRxDataLost = 0U;
UartErrorFraming = 0U;
UartErrorParity = 0U;
UartTxIndexI = 0U;
UartTxIndexO = 0U;
UartRxIndexI = 0U;
UartRxIndexO = 0U;
UartTxNum = 0U;
status = pUSART->Initialize(USART_Callback);
if (status == ARM_DRIVER_OK) {
status = pUSART->PowerControl(ARM_POWER_FULL);
}
if (status == ARM_DRIVER_OK) {
ret = DAP_OK;
}
return (ret);
}
// Un-Init UART
static void UART_Uninit (void) {
UartConfigured = 0U;
pUSART->PowerControl(ARM_POWER_OFF);
pUSART->Uninitialize();
}
// Get UART Status
// return: status
static uint8_t UART_Get_Status (void) {
uint8_t status = 0U;
if (UartReceiveEnabled != 0U) {
status |= DAP_UART_STATUS_RX_ENABLED;
}
if (UartErrorRxDataLost != 0U) {
UartErrorRxDataLost = 0U;
status |= DAP_UART_STATUS_RX_DATA_LOST;
}
if (UartErrorFraming != 0U) {
UartErrorFraming = 0U;
status |= DAP_UART_STATUS_FRAMING_ERROR;
}
if (UartErrorParity != 0U) {
UartErrorParity = 0U;
status |= DAP_UART_STATUS_PARITY_ERROR;
}
if (UartTransmitEnabled != 0U) {
status |= DAP_UART_STATUS_TX_ENABLED;
}
return (status);
}
// Enable UART Receive
// return: DAP_OK or DAP_ERROR
static uint8_t UART_Receive_Enable (void) {
int32_t status;
uint8_t ret = DAP_ERROR;
if (UartReceiveEnabled == 0U) {
// Flush Buffers
UartRxIndexI = 0U;
UartRxIndexO = 0U;
UART_Receive();
status = pUSART->Control(ARM_USART_CONTROL_RX, 1U);
if (status == ARM_DRIVER_OK) {
UartReceiveEnabled = 1U;
ret = DAP_OK;
}
} else {
ret = DAP_OK;
}
return (ret);
}
// Enable UART Transmit
// return: DAP_OK or DAP_ERROR
static uint8_t UART_Transmit_Enable (void) {
int32_t status;
uint8_t ret = DAP_ERROR;
if (UartTransmitEnabled == 0U) {
// Flush Buffers
UartTransmitActive = 0U;
UartTxIndexI = 0U;
UartTxIndexO = 0U;
UartTxNum = 0U;
status = pUSART->Control(ARM_USART_CONTROL_TX, 1U);
if (status == ARM_DRIVER_OK) {
UartTransmitEnabled = 1U;
ret = DAP_OK;
}
} else {
ret = DAP_OK;
}
return (ret);
}
// Disable UART Receive
static void UART_Receive_Disable (void) {
if (UartReceiveEnabled != 0U) {
pUSART->Control(ARM_USART_CONTROL_RX, 0U);
pUSART->Control(ARM_USART_ABORT_RECEIVE, 0U);
UartReceiveEnabled = 0U;
}
}
// Disable UART Transmit
static void UART_Transmit_Disable (void) {
if (UartTransmitEnabled != 0U) {
pUSART->Control(ARM_USART_ABORT_SEND, 0U);
pUSART->Control(ARM_USART_CONTROL_TX, 0U);
UartTransmitActive = 0U;
UartTransmitEnabled = 0U;
}
}
// Flush UART Receive buffer
static void UART_Receive_Flush (void) {
pUSART->Control(ARM_USART_ABORT_RECEIVE, 0U);
UartRxIndexI = 0U;
UartRxIndexO = 0U;
if (UartReceiveEnabled != 0U) {
UART_Receive();
}
}
// Flush UART Transmit buffer
static void UART_Transmit_Flush (void) {
pUSART->Control(ARM_USART_ABORT_SEND, 0U);
UartTransmitActive = 0U;
UartTxIndexI = 0U;
UartTxIndexO = 0U;
UartTxNum = 0U;
}
// Receive data from target via UART
static void UART_Receive (void) {
uint32_t index;
index = UartRxIndexI & (DAP_UART_RX_BUFFER_SIZE - 1U);
pUSART->Receive(&UartRxBuf[index], UART_RX_BLOCK_SIZE);
}
// Transmit available data to target via UART
static void UART_Transmit (void) {
uint32_t count;
uint32_t index;
count = UartTxIndexI - UartTxIndexO;
index = UartTxIndexO & (DAP_UART_TX_BUFFER_SIZE - 1U);
if (count != 0U) {
if ((index + count) <= DAP_UART_TX_BUFFER_SIZE) {
UartTxNum = count;
} else {
UartTxNum = DAP_UART_TX_BUFFER_SIZE - index;
}
UartTransmitActive = 1U;
pUSART->Send(&UartTxBuf[index], UartTxNum);
}
}
// Process UART Transport command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
uint32_t UART_Transport (const uint8_t *request, uint8_t *response) {
uint8_t transport;
uint8_t ret = DAP_ERROR;
transport = *request;
switch (transport) {
case DAP_UART_TRANSPORT_NONE:
switch (UartTransport) {
case DAP_UART_TRANSPORT_NONE:
ret = DAP_OK;
break;
case DAP_UART_TRANSPORT_USB_COM_PORT:
#if (DAP_UART_USB_COM_PORT != 0)
USB_COM_PORT_Activate(0U);
UartTransport = DAP_UART_TRANSPORT_NONE;
ret = DAP_OK;
#endif
break;
case DAP_UART_TRANSPORT_DAP_COMMAND:
UART_Receive_Disable();
UART_Transmit_Disable();
UART_Uninit();
UartTransport = DAP_UART_TRANSPORT_NONE;
ret= DAP_OK;
break;
}
break;
case DAP_UART_TRANSPORT_USB_COM_PORT:
switch (UartTransport) {
case DAP_UART_TRANSPORT_NONE:
#if (DAP_UART_USB_COM_PORT != 0)
if (USB_COM_PORT_Activate(1U) == 0U) {
UartTransport = DAP_UART_TRANSPORT_USB_COM_PORT;
ret = DAP_OK;
}
#endif
break;
case DAP_UART_TRANSPORT_USB_COM_PORT:
ret = DAP_OK;
break;
case DAP_UART_TRANSPORT_DAP_COMMAND:
UART_Receive_Disable();
UART_Transmit_Disable();
UART_Uninit();
UartTransport = DAP_UART_TRANSPORT_NONE;
#if (DAP_UART_USB_COM_PORT != 0)
if (USB_COM_PORT_Activate(1U) == 0U) {
UartTransport = DAP_UART_TRANSPORT_USB_COM_PORT;
ret = DAP_OK;
}
#endif
break;
}
break;
case DAP_UART_TRANSPORT_DAP_COMMAND:
switch (UartTransport) {
case DAP_UART_TRANSPORT_NONE:
ret = UART_Init();
if (ret == DAP_OK) {
UartTransport = DAP_UART_TRANSPORT_DAP_COMMAND;
}
break;
case DAP_UART_TRANSPORT_USB_COM_PORT:
#if (DAP_UART_USB_COM_PORT != 0)
USB_COM_PORT_Activate(0U);
UartTransport = DAP_UART_TRANSPORT_NONE;
#endif
ret = UART_Init();
if (ret == DAP_OK) {
UartTransport = DAP_UART_TRANSPORT_DAP_COMMAND;
}
break;
case DAP_UART_TRANSPORT_DAP_COMMAND:
ret = DAP_OK;
break;
}
break;
default:
break;
}
*response = ret;
return ((1U << 16) | 1U);
}
// Process UART Configure command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
uint32_t UART_Configure (const uint8_t *request, uint8_t *response) {
uint8_t control, status;
uint32_t baudrate;
int32_t result;
if (UartTransport != DAP_UART_TRANSPORT_DAP_COMMAND) {
status = DAP_UART_CFG_ERROR_DATA_BITS |
DAP_UART_CFG_ERROR_PARITY |
DAP_UART_CFG_ERROR_STOP_BITS;
baudrate = 0U; // baudrate error
} else {
status = 0U;
control = *request;
baudrate = (uint32_t)(*(request+1) << 0) |
(uint32_t)(*(request+2) << 8) |
(uint32_t)(*(request+3) << 16) |
(uint32_t)(*(request+4) << 24);
result = pUSART->Control(control |
ARM_USART_MODE_ASYNCHRONOUS |
ARM_USART_FLOW_CONTROL_NONE,
baudrate);
if (result == ARM_DRIVER_OK) {
UartConfigured = 1U;
} else {
UartConfigured = 0U;
switch (result) {
case ARM_USART_ERROR_BAUDRATE:
status = 0U;
baudrate = 0U;
break;
case ARM_USART_ERROR_DATA_BITS:
status = DAP_UART_CFG_ERROR_DATA_BITS;
break;
case ARM_USART_ERROR_PARITY:
status = DAP_UART_CFG_ERROR_PARITY;
break;
case ARM_USART_ERROR_STOP_BITS:
status = DAP_UART_CFG_ERROR_STOP_BITS;
break;
default:
status = DAP_UART_CFG_ERROR_DATA_BITS |
DAP_UART_CFG_ERROR_PARITY |
DAP_UART_CFG_ERROR_STOP_BITS;
baudrate = 0U;
break;
}
}
}
*response++ = status;
*response++ = (uint8_t)(baudrate >> 0);
*response++ = (uint8_t)(baudrate >> 8);
*response++ = (uint8_t)(baudrate >> 16);
*response = (uint8_t)(baudrate >> 24);
return ((5U << 16) | 5U);
}
// Process UART Control command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
uint32_t UART_Control (const uint8_t *request, uint8_t *response) {
uint8_t control;
uint8_t result;
uint8_t ret = DAP_OK;
if (UartTransport != DAP_UART_TRANSPORT_DAP_COMMAND) {
ret = DAP_ERROR;
} else {
control = *request;
if ((control & DAP_UART_CONTROL_RX_DISABLE) != 0U) {
// Receive disable
UART_Receive_Disable();
} else if ((control & DAP_UART_CONTROL_RX_ENABLE) != 0U) {
// Receive enable
if (UartConfigured != 0U) {
result = UART_Receive_Enable();
if (result != DAP_OK) {
ret = DAP_ERROR;
}
} else {
ret = DAP_ERROR;
}
}
if ((control & DAP_UART_CONTROL_RX_BUF_FLUSH) != 0U) {
UART_Receive_Flush();
}
if ((control & DAP_UART_CONTROL_TX_DISABLE) != 0U) {
// Transmit disable
UART_Transmit_Disable();
} else if ((control & DAP_UART_CONTROL_TX_ENABLE) != 0U) {
// Transmit enable
if (UartConfigured != 0U) {
result = UART_Transmit_Enable();
if (result != DAP_OK) {
ret = DAP_ERROR;
}
} else {
ret = DAP_ERROR;
}
}
if ((control & DAP_UART_CONTROL_TX_BUF_FLUSH) != 0U) {
UART_Transmit_Flush();
}
}
*response = ret;
return ((1U << 16) | 1U);
}
// Process UART Status command and prepare response
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
uint32_t UART_Status (uint8_t *response) {
uint32_t rx_cnt, tx_cnt;
uint32_t cnt;
uint8_t status;
if ((UartTransport != DAP_UART_TRANSPORT_DAP_COMMAND) ||
(UartConfigured == 0U)) {
rx_cnt = 0U;
tx_cnt = 0U;
status = 0U;
} else {
rx_cnt = UartRxIndexI - UartRxIndexO;
rx_cnt += pUSART->GetRxCount();
if (rx_cnt > (DAP_UART_RX_BUFFER_SIZE - (UART_RX_BLOCK_SIZE*2))) {
// Overflow
UartErrorRxDataLost = 1U;
rx_cnt = (DAP_UART_RX_BUFFER_SIZE - (UART_RX_BLOCK_SIZE*2));
UartRxIndexO = UartRxIndexI - rx_cnt;
}
tx_cnt = UartTxIndexI - UartTxIndexO;
cnt = pUSART->GetTxCount();
if (UartTransmitActive != 0U) {
tx_cnt -= cnt;
}
status = UART_Get_Status();
}
*response++ = status;
*response++ = (uint8_t)(rx_cnt >> 0);
*response++ = (uint8_t)(rx_cnt >> 8);
*response++ = (uint8_t)(rx_cnt >> 16);
*response++ = (uint8_t)(rx_cnt >> 24);
*response++ = (uint8_t)(tx_cnt >> 0);
*response++ = (uint8_t)(tx_cnt >> 8);
*response++ = (uint8_t)(tx_cnt >> 16);
*response = (uint8_t)(tx_cnt >> 24);
return ((0U << 16) | 9U);
}
// Process UART Transfer command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
uint32_t UART_Transfer (const uint8_t *request, uint8_t *response) {
uint32_t rx_cnt, tx_cnt;
uint32_t rx_num, tx_num;
uint8_t *rx_data;
const
uint8_t *tx_data;
uint32_t num;
uint32_t index;
uint8_t status;
if (UartTransport != DAP_UART_TRANSPORT_DAP_COMMAND) {
status = 0U;
rx_cnt = 0U;
tx_cnt = 0U;
} else {
// RX Data
rx_cnt = ((uint32_t)(*(request+0) << 0) |
(uint32_t)(*(request+1) << 8));
if (rx_cnt > (DAP_PACKET_SIZE - 6U)) {
rx_cnt = (DAP_PACKET_SIZE - 6U);
}
rx_num = UartRxIndexI - UartRxIndexO;
rx_num += pUSART->GetRxCount();
if (rx_num > (DAP_UART_RX_BUFFER_SIZE - (UART_RX_BLOCK_SIZE*2))) {
// Overflow
UartErrorRxDataLost = 1U;
rx_num = (DAP_UART_RX_BUFFER_SIZE - (UART_RX_BLOCK_SIZE*2));
UartRxIndexO = UartRxIndexI - rx_num;
}
if (rx_cnt > rx_num) {
rx_cnt = rx_num;
}
rx_data = (response+5);
index = UartRxIndexO & (DAP_UART_RX_BUFFER_SIZE - 1U);
if ((index + rx_cnt) <= DAP_UART_RX_BUFFER_SIZE) {
memcpy( rx_data, &UartRxBuf[index], rx_cnt);
} else {
num = DAP_UART_RX_BUFFER_SIZE - index;
memcpy( rx_data, &UartRxBuf[index], num);
memcpy(&rx_data[num], &UartRxBuf[0], rx_cnt - num);
}
UartRxIndexO += rx_cnt;
// TX Data
tx_cnt = ((uint32_t)(*(request+2) << 0) |
(uint32_t)(*(request+3) << 8));
tx_data = (request+4);
if (tx_cnt > (DAP_PACKET_SIZE - 5U)) {
tx_cnt = (DAP_PACKET_SIZE - 5U);
}
tx_num = UartTxIndexI - UartTxIndexO;
num = pUSART->GetTxCount();
if (UartTransmitActive != 0U) {
tx_num -= num;
}
if (tx_cnt > (DAP_UART_TX_BUFFER_SIZE - tx_num)) {
tx_cnt = (DAP_UART_TX_BUFFER_SIZE - tx_num);
}
index = UartTxIndexI & (DAP_UART_TX_BUFFER_SIZE - 1U);
if ((index + tx_cnt) <= DAP_UART_TX_BUFFER_SIZE) {
memcpy(&UartTxBuf[index], tx_data, tx_cnt);
} else {
num = DAP_UART_TX_BUFFER_SIZE - index;
memcpy(&UartTxBuf[index], tx_data, num);
memcpy(&UartTxBuf[0], &tx_data[num], tx_cnt - num);
}
UartTxIndexI += tx_cnt;
if (UartTransmitActive == 0U) {
UART_Transmit();
}
status = UART_Get_Status();
}
*response++ = status;
*response++ = (uint8_t)(tx_cnt >> 0);
*response++ = (uint8_t)(tx_cnt >> 8);
*response++ = (uint8_t)(rx_cnt >> 0);
*response = (uint8_t)(rx_cnt >> 8);
return (((4U + tx_cnt) << 16) | (5U + rx_cnt));
}
#endif /* DAP_UART */
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Source/UART.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 5,238 |
```c
/*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* your_sha256_hash------
*
* $Date: 29. March 2021
* $Revision: V2.0.1
*
* Project: CMSIS-DAP Source
* Title: SWO.c CMSIS-DAP SWO I/O
*
*your_sha256_hash-----------*/
#include "DAP_config.h"
#include "DAP.h"
#if (SWO_UART != 0)
#include "Driver_USART.h"
#endif
#if (SWO_STREAM != 0)
#include "cmsis_os2.h"
#define osObjectsExternal
#include "osObjects.h"
#endif
#if (SWO_STREAM != 0)
#ifdef DAP_FW_V1
#error "SWO Streaming Trace not supported in DAP V1!"
#endif
#endif
#if (SWO_UART != 0)
// USART Driver
#define _USART_Driver_(n) Driver_USART##n
#define USART_Driver_(n) _USART_Driver_(n)
extern ARM_DRIVER_USART USART_Driver_(SWO_UART_DRIVER);
#define pUSART (&USART_Driver_(SWO_UART_DRIVER))
static uint8_t USART_Ready = 0U;
#endif /* (SWO_UART != 0) */
#if ((SWO_UART != 0) || (SWO_MANCHESTER != 0))
#define SWO_STREAM_TIMEOUT 50U /* Stream timeout in ms */
#define USB_BLOCK_SIZE 512U /* USB Block Size */
#define TRACE_BLOCK_SIZE 64U /* Trace Block Size (2^n: 32...512) */
// Trace State
static uint8_t TraceTransport = 0U; /* Trace Transport */
static uint8_t TraceMode = 0U; /* Trace Mode */
static uint8_t TraceStatus = 0U; /* Trace Status without Errors */
static uint8_t TraceError[2] = {0U, 0U}; /* Trace Error flags (banked) */
static uint8_t TraceError_n = 0U; /* Active Trace Error bank */
// Trace Buffer
static uint8_t TraceBuf[SWO_BUFFER_SIZE]; /* Trace Buffer (must be 2^n) */
static volatile uint32_t TraceIndexI = 0U; /* Incoming Trace Index */
static volatile uint32_t TraceIndexO = 0U; /* Outgoing Trace Index */
static volatile uint8_t TraceUpdate; /* Trace Update Flag */
static uint32_t TraceBlockSize; /* Current Trace Block Size */
#if (TIMESTAMP_CLOCK != 0U)
// Trace Timestamp
static volatile struct {
uint32_t index;
uint32_t tick;
} TraceTimestamp;
#endif
// Trace Helper functions
static void ClearTrace (void);
static void ResumeTrace (void);
static uint32_t GetTraceCount (void);
static uint8_t GetTraceStatus (void);
static void SetTraceError (uint8_t flag);
#if (SWO_STREAM != 0)
extern osThreadId_t SWO_ThreadId;
static volatile uint8_t TransferBusy = 0U; /* Transfer Busy Flag */
static uint32_t TransferSize; /* Current Transfer Size */
#endif
#if (SWO_UART != 0)
// USART Driver Callback function
// event: event mask
static void USART_Callback (uint32_t event) {
uint32_t index_i;
uint32_t index_o;
uint32_t count;
uint32_t num;
if (event & ARM_USART_EVENT_RECEIVE_COMPLETE) {
#if (TIMESTAMP_CLOCK != 0U)
TraceTimestamp.tick = TIMESTAMP_GET();
#endif
index_o = TraceIndexO;
index_i = TraceIndexI;
index_i += TraceBlockSize;
TraceIndexI = index_i;
#if (TIMESTAMP_CLOCK != 0U)
TraceTimestamp.index = index_i;
#endif
num = TRACE_BLOCK_SIZE - (index_i & (TRACE_BLOCK_SIZE - 1U));
count = index_i - index_o;
if (count <= (SWO_BUFFER_SIZE - num)) {
index_i &= SWO_BUFFER_SIZE - 1U;
TraceBlockSize = num;
pUSART->Receive(&TraceBuf[index_i], num);
} else {
TraceStatus = DAP_SWO_CAPTURE_ACTIVE | DAP_SWO_CAPTURE_PAUSED;
}
TraceUpdate = 1U;
#if (SWO_STREAM != 0)
if (TraceTransport == 2U) {
if (count >= (USB_BLOCK_SIZE - (index_o & (USB_BLOCK_SIZE - 1U)))) {
osThreadFlagsSet(SWO_ThreadId, 1U);
}
}
#endif
}
if (event & ARM_USART_EVENT_RX_OVERFLOW) {
SetTraceError(DAP_SWO_BUFFER_OVERRUN);
}
if (event & (ARM_USART_EVENT_RX_BREAK |
ARM_USART_EVENT_RX_FRAMING_ERROR |
ARM_USART_EVENT_RX_PARITY_ERROR)) {
SetTraceError(DAP_SWO_STREAM_ERROR);
}
}
// Enable or disable SWO Mode (UART)
// enable: enable flag
// return: 1 - Success, 0 - Error
__WEAK uint32_t SWO_Mode_UART (uint32_t enable) {
int32_t status;
USART_Ready = 0U;
if (enable != 0U) {
status = pUSART->Initialize(USART_Callback);
if (status != ARM_DRIVER_OK) {
return (0U);
}
status = pUSART->PowerControl(ARM_POWER_FULL);
if (status != ARM_DRIVER_OK) {
pUSART->Uninitialize();
return (0U);
}
} else {
pUSART->Control(ARM_USART_CONTROL_RX, 0U);
pUSART->Control(ARM_USART_ABORT_RECEIVE, 0U);
pUSART->PowerControl(ARM_POWER_OFF);
pUSART->Uninitialize();
}
return (1U);
}
// Configure SWO Baudrate (UART)
// baudrate: requested baudrate
// return: actual baudrate or 0 when not configured
__WEAK uint32_t SWO_Baudrate_UART (uint32_t baudrate) {
int32_t status;
uint32_t index;
uint32_t num;
if (baudrate > SWO_UART_MAX_BAUDRATE) {
baudrate = SWO_UART_MAX_BAUDRATE;
}
if (TraceStatus & DAP_SWO_CAPTURE_ACTIVE) {
pUSART->Control(ARM_USART_CONTROL_RX, 0U);
if (pUSART->GetStatus().rx_busy) {
TraceIndexI += pUSART->GetRxCount();
pUSART->Control(ARM_USART_ABORT_RECEIVE, 0U);
}
}
status = pUSART->Control(ARM_USART_MODE_ASYNCHRONOUS |
ARM_USART_DATA_BITS_8 |
ARM_USART_PARITY_NONE |
ARM_USART_STOP_BITS_1,
baudrate);
if (status == ARM_DRIVER_OK) {
USART_Ready = 1U;
} else {
USART_Ready = 0U;
return (0U);
}
if (TraceStatus & DAP_SWO_CAPTURE_ACTIVE) {
if ((TraceStatus & DAP_SWO_CAPTURE_PAUSED) == 0U) {
index = TraceIndexI & (SWO_BUFFER_SIZE - 1U);
num = TRACE_BLOCK_SIZE - (index & (TRACE_BLOCK_SIZE - 1U));
TraceBlockSize = num;
pUSART->Receive(&TraceBuf[index], num);
}
pUSART->Control(ARM_USART_CONTROL_RX, 1U);
}
return (baudrate);
}
// Control SWO Capture (UART)
// active: active flag
// return: 1 - Success, 0 - Error
__WEAK uint32_t SWO_Control_UART (uint32_t active) {
int32_t status;
if (active) {
if (!USART_Ready) {
return (0U);
}
TraceBlockSize = 1U;
status = pUSART->Receive(&TraceBuf[0], 1U);
if (status != ARM_DRIVER_OK) {
return (0U);
}
status = pUSART->Control(ARM_USART_CONTROL_RX, 1U);
if (status != ARM_DRIVER_OK) {
return (0U);
}
} else {
pUSART->Control(ARM_USART_CONTROL_RX, 0U);
if (pUSART->GetStatus().rx_busy) {
TraceIndexI += pUSART->GetRxCount();
pUSART->Control(ARM_USART_ABORT_RECEIVE, 0U);
}
}
return (1U);
}
// Start SWO Capture (UART)
// buf: pointer to buffer for capturing
// num: number of bytes to capture
__WEAK void SWO_Capture_UART (uint8_t *buf, uint32_t num) {
TraceBlockSize = num;
pUSART->Receive(buf, num);
}
// Get SWO Pending Trace Count (UART)
// return: number of pending trace data bytes
__WEAK uint32_t SWO_GetCount_UART (void) {
uint32_t count;
if (pUSART->GetStatus().rx_busy) {
count = pUSART->GetRxCount();
} else {
count = 0U;
}
return (count);
}
#endif /* (SWO_UART != 0) */
#if (SWO_MANCHESTER != 0)
// Enable or disable SWO Mode (Manchester)
// enable: enable flag
// return: 1 - Success, 0 - Error
__WEAK uint32_t SWO_Mode_Manchester (uint32_t enable) {
return (0U);
}
// Configure SWO Baudrate (Manchester)
// baudrate: requested baudrate
// return: actual baudrate or 0 when not configured
__WEAK uint32_t SWO_Baudrate_Manchester (uint32_t baudrate) {
return (0U);
}
// Control SWO Capture (Manchester)
// active: active flag
// return: 1 - Success, 0 - Error
__WEAK uint32_t SWO_Control_Manchester (uint32_t active) {
return (0U);
}
// Start SWO Capture (Manchester)
// buf: pointer to buffer for capturing
// num: number of bytes to capture
__WEAK void SWO_Capture_Manchester (uint8_t *buf, uint32_t num) {
}
// Get SWO Pending Trace Count (Manchester)
// return: number of pending trace data bytes
__WEAK uint32_t SWO_GetCount_Manchester (void) {
}
#endif /* (SWO_MANCHESTER != 0) */
// Clear Trace Errors and Data
static void ClearTrace (void) {
#if (SWO_STREAM != 0)
if (TraceTransport == 2U) {
if (TransferBusy != 0U) {
SWO_AbortTransfer();
TransferBusy = 0U;
}
}
#endif
TraceError[0] = 0U;
TraceError[1] = 0U;
TraceError_n = 0U;
TraceIndexI = 0U;
TraceIndexO = 0U;
#if (TIMESTAMP_CLOCK != 0U)
TraceTimestamp.index = 0U;
TraceTimestamp.tick = 0U;
#endif
}
// Resume Trace Capture
static void ResumeTrace (void) {
uint32_t index_i;
uint32_t index_o;
if (TraceStatus == (DAP_SWO_CAPTURE_ACTIVE | DAP_SWO_CAPTURE_PAUSED)) {
index_i = TraceIndexI;
index_o = TraceIndexO;
if ((index_i - index_o) < SWO_BUFFER_SIZE) {
index_i &= SWO_BUFFER_SIZE - 1U;
switch (TraceMode) {
#if (SWO_UART != 0)
case DAP_SWO_UART:
TraceStatus = DAP_SWO_CAPTURE_ACTIVE;
SWO_Capture_UART(&TraceBuf[index_i], 1U);
break;
#endif
#if (SWO_MANCHESTER != 0)
case DAP_SWO_MANCHESTER:
TraceStatus = DAP_SWO_CAPTURE_ACTIVE;
SWO_Capture_Manchester(&TraceBuf[index_i], 1U);
break;
#endif
default:
break;
}
}
}
}
// Get Trace Count
// return: number of available data bytes in trace buffer
static uint32_t GetTraceCount (void) {
uint32_t count;
if (TraceStatus == DAP_SWO_CAPTURE_ACTIVE) {
do {
TraceUpdate = 0U;
count = TraceIndexI - TraceIndexO;
switch (TraceMode) {
#if (SWO_UART != 0)
case DAP_SWO_UART:
count += SWO_GetCount_UART();
break;
#endif
#if (SWO_MANCHESTER != 0)
case DAP_SWO_MANCHESTER:
count += SWO_GetCount_Manchester();
break;
#endif
default:
break;
}
} while (TraceUpdate != 0U);
} else {
count = TraceIndexI - TraceIndexO;
}
return (count);
}
// Get Trace Status (clear Error flags)
// return: Trace Status (Active flag and Error flags)
static uint8_t GetTraceStatus (void) {
uint8_t status;
uint32_t n;
n = TraceError_n;
TraceError_n ^= 1U;
status = TraceStatus | TraceError[n];
TraceError[n] = 0U;
return (status);
}
// Set Trace Error flag(s)
// flag: error flag(s) to set
static void SetTraceError (uint8_t flag) {
TraceError[TraceError_n] |= flag;
}
// Process SWO Transport command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
uint32_t SWO_Transport (const uint8_t *request, uint8_t *response) {
uint8_t transport;
uint32_t result;
if ((TraceStatus & DAP_SWO_CAPTURE_ACTIVE) == 0U) {
transport = *request;
switch (transport) {
case 0U:
case 1U:
#if (SWO_STREAM != 0)
case 2U:
#endif
TraceTransport = transport;
result = 1U;
break;
default:
result = 0U;
break;
}
} else {
result = 0U;
}
if (result != 0U) {
*response = DAP_OK;
} else {
*response = DAP_ERROR;
}
return ((1U << 16) | 1U);
}
// Process SWO Mode command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
uint32_t SWO_Mode (const uint8_t *request, uint8_t *response) {
uint8_t mode;
uint32_t result;
mode = *request;
switch (TraceMode) {
#if (SWO_UART != 0)
case DAP_SWO_UART:
SWO_Mode_UART(0U);
break;
#endif
#if (SWO_MANCHESTER != 0)
case DAP_SWO_MANCHESTER:
SWO_Mode_Manchester(0U);
break;
#endif
default:
break;
}
switch (mode) {
case DAP_SWO_OFF:
result = 1U;
break;
#if (SWO_UART != 0)
case DAP_SWO_UART:
result = SWO_Mode_UART(1U);
break;
#endif
#if (SWO_MANCHESTER != 0)
case DAP_SWO_MANCHESTER:
result = SWO_Mode_Manchester(1U);
break;
#endif
default:
result = 0U;
break;
}
if (result != 0U) {
TraceMode = mode;
} else {
TraceMode = DAP_SWO_OFF;
}
TraceStatus = 0U;
if (result != 0U) {
*response = DAP_OK;
} else {
*response = DAP_ERROR;
}
return ((1U << 16) | 1U);
}
// Process SWO Baudrate command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
uint32_t SWO_Baudrate (const uint8_t *request, uint8_t *response) {
uint32_t baudrate;
baudrate = (uint32_t)(*(request+0) << 0) |
(uint32_t)(*(request+1) << 8) |
(uint32_t)(*(request+2) << 16) |
(uint32_t)(*(request+3) << 24);
switch (TraceMode) {
#if (SWO_UART != 0)
case DAP_SWO_UART:
baudrate = SWO_Baudrate_UART(baudrate);
break;
#endif
#if (SWO_MANCHESTER != 0)
case DAP_SWO_MANCHESTER:
baudrate = SWO_Baudrate_Manchester(baudrate);
break;
#endif
default:
baudrate = 0U;
break;
}
if (baudrate == 0U) {
TraceStatus = 0U;
}
*response++ = (uint8_t)(baudrate >> 0);
*response++ = (uint8_t)(baudrate >> 8);
*response++ = (uint8_t)(baudrate >> 16);
*response = (uint8_t)(baudrate >> 24);
return ((4U << 16) | 4U);
}
// Process SWO Control command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
uint32_t SWO_Control (const uint8_t *request, uint8_t *response) {
uint8_t active;
uint32_t result;
active = *request & DAP_SWO_CAPTURE_ACTIVE;
if (active != (TraceStatus & DAP_SWO_CAPTURE_ACTIVE)) {
if (active) {
ClearTrace();
}
switch (TraceMode) {
#if (SWO_UART != 0)
case DAP_SWO_UART:
result = SWO_Control_UART(active);
break;
#endif
#if (SWO_MANCHESTER != 0)
case DAP_SWO_MANCHESTER:
result = SWO_Control_Manchester(active);
break;
#endif
default:
result = 0U;
break;
}
if (result != 0U) {
TraceStatus = active;
#if (SWO_STREAM != 0)
if (TraceTransport == 2U) {
osThreadFlagsSet(SWO_ThreadId, 1U);
}
#endif
}
} else {
result = 1U;
}
if (result != 0U) {
*response = DAP_OK;
} else {
*response = DAP_ERROR;
}
return ((1U << 16) | 1U);
}
// Process SWO Status command and prepare response
// response: pointer to response data
// return: number of bytes in response
uint32_t SWO_Status (uint8_t *response) {
uint8_t status;
uint32_t count;
status = GetTraceStatus();
count = GetTraceCount();
*response++ = status;
*response++ = (uint8_t)(count >> 0);
*response++ = (uint8_t)(count >> 8);
*response++ = (uint8_t)(count >> 16);
*response = (uint8_t)(count >> 24);
return (5U);
}
// Process SWO Extended Status command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
uint32_t SWO_ExtendedStatus (const uint8_t *request, uint8_t *response) {
uint8_t cmd;
uint8_t status;
uint32_t count;
#if (TIMESTAMP_CLOCK != 0U)
uint32_t index;
uint32_t tick;
#endif
uint32_t num;
num = 0U;
cmd = *request;
if (cmd & 0x01U) {
status = GetTraceStatus();
*response++ = status;
num += 1U;
}
if (cmd & 0x02U) {
count = GetTraceCount();
*response++ = (uint8_t)(count >> 0);
*response++ = (uint8_t)(count >> 8);
*response++ = (uint8_t)(count >> 16);
*response++ = (uint8_t)(count >> 24);
num += 4U;
}
#if (TIMESTAMP_CLOCK != 0U)
if (cmd & 0x04U) {
do {
TraceUpdate = 0U;
index = TraceTimestamp.index;
tick = TraceTimestamp.tick;
} while (TraceUpdate != 0U);
*response++ = (uint8_t)(index >> 0);
*response++ = (uint8_t)(index >> 8);
*response++ = (uint8_t)(index >> 16);
*response++ = (uint8_t)(index >> 24);
*response++ = (uint8_t)(tick >> 0);
*response++ = (uint8_t)(tick >> 8);
*response++ = (uint8_t)(tick >> 16);
*response++ = (uint8_t)(tick >> 24);
num += 4U;
}
#endif
return ((1U << 16) | num);
}
// Process SWO Data command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
uint32_t SWO_Data (const uint8_t *request, uint8_t *response) {
uint8_t status;
uint32_t count;
uint32_t index;
uint32_t n, i;
status = GetTraceStatus();
count = GetTraceCount();
if (TraceTransport == 1U) {
n = (uint32_t)(*(request+0) << 0) |
(uint32_t)(*(request+1) << 8);
if (n > (DAP_PACKET_SIZE - 4U)) {
n = DAP_PACKET_SIZE - 4U;
}
if (count > n) {
count = n;
}
} else {
count = 0U;
}
*response++ = status;
*response++ = (uint8_t)(count >> 0);
*response++ = (uint8_t)(count >> 8);
if (TraceTransport == 1U) {
index = TraceIndexO;
for (i = index, n = count; n; n--) {
i &= SWO_BUFFER_SIZE - 1U;
*response++ = TraceBuf[i++];
}
TraceIndexO = index + count;
ResumeTrace();
}
return ((2U << 16) | (3U + count));
}
#if (SWO_STREAM != 0)
// SWO Data Transfer complete callback
void SWO_TransferComplete (void) {
TraceIndexO += TransferSize;
TransferBusy = 0U;
ResumeTrace();
osThreadFlagsSet(SWO_ThreadId, 1U);
}
// SWO Thread
__NO_RETURN void SWO_Thread (void *argument) {
uint32_t timeout;
uint32_t flags;
uint32_t count;
uint32_t index;
uint32_t i, n;
(void) argument;
timeout = osWaitForever;
for (;;) {
flags = osThreadFlagsWait(1U, osFlagsWaitAny, timeout);
if (TraceStatus & DAP_SWO_CAPTURE_ACTIVE) {
timeout = SWO_STREAM_TIMEOUT;
} else {
timeout = osWaitForever;
flags = osFlagsErrorTimeout;
}
if (TransferBusy == 0U) {
count = GetTraceCount();
if (count != 0U) {
index = TraceIndexO & (SWO_BUFFER_SIZE - 1U);
n = SWO_BUFFER_SIZE - index;
if (count > n) {
count = n;
}
if (flags != osFlagsErrorTimeout) {
i = index & (USB_BLOCK_SIZE - 1U);
if (i == 0U) {
count &= ~(USB_BLOCK_SIZE - 1U);
} else {
n = USB_BLOCK_SIZE - i;
if (count >= n) {
count = n;
} else {
count = 0U;
}
}
}
if (count != 0U) {
TransferSize = count;
TransferBusy = 1U;
SWO_QueueTransfer(&TraceBuf[index], count);
}
}
}
}
}
#endif /* (SWO_STREAM != 0) */
#endif /* ((SWO_UART != 0) || (SWO_MANCHESTER != 0)) */
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Source/SWO.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 5,817 |
```c
/*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* your_sha256_hash------
*
* $Date: 5. December 2022
* $Revision: V2.1.2
*
* Project: CMSIS-DAP Source
* Title: DAP.c CMSIS-DAP Commands
*
*your_sha256_hash-----------*/
#include <string.h>
#include "DAP_config.h"
#include "DAP.h"
#if (DAP_PACKET_SIZE < 64U)
#error "Minimum Packet Size is 64!"
#endif
#if (DAP_PACKET_SIZE > 32768U)
#error "Maximum Packet Size is 32768!"
#endif
#if (DAP_PACKET_COUNT < 1U)
#error "Minimum Packet Count is 1!"
#endif
#if (DAP_PACKET_COUNT > 255U)
#error "Maximum Packet Count is 255!"
#endif
// Clock Macros
#define MAX_SWJ_CLOCK(delay_cycles) \
((CPU_CLOCK/2U) / (IO_PORT_WRITE_CYCLES + delay_cycles))
DAP_Data_t DAP_Data; // DAP Data
volatile uint8_t DAP_TransferAbort; // Transfer Abort Flag
static const char DAP_FW_Ver [] = DAP_FW_VER;
// Common clock delay calculation routine
// clock: requested SWJ frequency in Hertz
static void Set_Clock_Delay(uint32_t clock) {
uint32_t delay;
if (clock >= MAX_SWJ_CLOCK(DELAY_FAST_CYCLES)) {
DAP_Data.fast_clock = 1U;
DAP_Data.clock_delay = 1U;
} else {
DAP_Data.fast_clock = 0U;
delay = ((CPU_CLOCK/2U) + (clock - 1U)) / clock;
if (delay > IO_PORT_WRITE_CYCLES) {
delay -= IO_PORT_WRITE_CYCLES;
delay = (delay + (DELAY_SLOW_CYCLES - 1U)) / DELAY_SLOW_CYCLES;
} else {
delay = 1U;
}
DAP_Data.clock_delay = delay;
}
}
// Get DAP Information
// id: info identifier
// info: pointer to info data
// return: number of bytes in info data
static uint8_t DAP_Info(uint8_t id, uint8_t *info) {
uint8_t length = 0U;
switch (id) {
case DAP_ID_VENDOR:
length = DAP_GetVendorString((char *)info);
break;
case DAP_ID_PRODUCT:
length = DAP_GetProductString((char *)info);
break;
case DAP_ID_SER_NUM:
length = DAP_GetSerNumString((char *)info);
break;
case DAP_ID_DAP_FW_VER:
length = (uint8_t)sizeof(DAP_FW_Ver);
memcpy(info, DAP_FW_Ver, length);
break;
case DAP_ID_DEVICE_VENDOR:
length = DAP_GetTargetDeviceVendorString((char *)info);
break;
case DAP_ID_DEVICE_NAME:
length = DAP_GetTargetDeviceNameString((char *)info);
break;
case DAP_ID_BOARD_VENDOR:
length = DAP_GetTargetBoardVendorString((char *)info);
break;
case DAP_ID_BOARD_NAME:
length = DAP_GetTargetBoardNameString((char *)info);
break;
case DAP_ID_PRODUCT_FW_VER:
length = DAP_GetProductFirmwareVersionString((char *)info);
break;
case DAP_ID_CAPABILITIES:
info[0] = ((DAP_SWD != 0) ? (1U << 0) : 0U) |
((DAP_JTAG != 0) ? (1U << 1) : 0U) |
((SWO_UART != 0) ? (1U << 2) : 0U) |
((SWO_MANCHESTER != 0) ? (1U << 3) : 0U) |
/* Atomic Commands */ (1U << 4) |
((TIMESTAMP_CLOCK != 0U) ? (1U << 5) : 0U) |
((SWO_STREAM != 0U) ? (1U << 6) : 0U) |
((DAP_UART != 0U) ? (1U << 7) : 0U);
info[1] = ((DAP_UART_USB_COM_PORT != 0) ? (1U << 0) : 0U);
length = 2U;
break;
case DAP_ID_TIMESTAMP_CLOCK:
#if (TIMESTAMP_CLOCK != 0U)
info[0] = (uint8_t)(TIMESTAMP_CLOCK >> 0);
info[1] = (uint8_t)(TIMESTAMP_CLOCK >> 8);
info[2] = (uint8_t)(TIMESTAMP_CLOCK >> 16);
info[3] = (uint8_t)(TIMESTAMP_CLOCK >> 24);
length = 4U;
#endif
break;
case DAP_ID_UART_RX_BUFFER_SIZE:
#if (DAP_UART != 0)
info[0] = (uint8_t)(DAP_UART_RX_BUFFER_SIZE >> 0);
info[1] = (uint8_t)(DAP_UART_RX_BUFFER_SIZE >> 8);
info[2] = (uint8_t)(DAP_UART_RX_BUFFER_SIZE >> 16);
info[3] = (uint8_t)(DAP_UART_RX_BUFFER_SIZE >> 24);
length = 4U;
#endif
break;
case DAP_ID_UART_TX_BUFFER_SIZE:
#if (DAP_UART != 0)
info[0] = (uint8_t)(DAP_UART_TX_BUFFER_SIZE >> 0);
info[1] = (uint8_t)(DAP_UART_TX_BUFFER_SIZE >> 8);
info[2] = (uint8_t)(DAP_UART_TX_BUFFER_SIZE >> 16);
info[3] = (uint8_t)(DAP_UART_TX_BUFFER_SIZE >> 24);
length = 4U;
#endif
break;
case DAP_ID_SWO_BUFFER_SIZE:
#if ((SWO_UART != 0) || (SWO_MANCHESTER != 0))
info[0] = (uint8_t)(SWO_BUFFER_SIZE >> 0);
info[1] = (uint8_t)(SWO_BUFFER_SIZE >> 8);
info[2] = (uint8_t)(SWO_BUFFER_SIZE >> 16);
info[3] = (uint8_t)(SWO_BUFFER_SIZE >> 24);
length = 4U;
#endif
break;
case DAP_ID_PACKET_SIZE:
info[0] = (uint8_t)(DAP_PACKET_SIZE >> 0);
info[1] = (uint8_t)(DAP_PACKET_SIZE >> 8);
length = 2U;
break;
case DAP_ID_PACKET_COUNT:
info[0] = DAP_PACKET_COUNT;
length = 1U;
break;
default:
break;
}
return (length);
}
// Delay for specified time
// delay: delay time in ms
void Delayms(uint32_t delay) {
delay *= ((CPU_CLOCK/1000U) + (DELAY_SLOW_CYCLES-1U)) / DELAY_SLOW_CYCLES;
PIN_DELAY_SLOW(delay);
}
// Process Delay command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
static uint32_t DAP_Delay(const uint8_t *request, uint8_t *response) {
uint32_t delay;
delay = (uint32_t)(*(request+0)) |
(uint32_t)(*(request+1) << 8);
delay *= ((CPU_CLOCK/1000000U) + (DELAY_SLOW_CYCLES-1U)) / DELAY_SLOW_CYCLES;
PIN_DELAY_SLOW(delay);
*response = DAP_OK;
return ((2U << 16) | 1U);
}
// Process Host Status command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
static uint32_t DAP_HostStatus(const uint8_t *request, uint8_t *response) {
switch (*request) {
case DAP_DEBUGGER_CONNECTED:
LED_CONNECTED_OUT((*(request+1) & 1U));
break;
case DAP_TARGET_RUNNING:
LED_RUNNING_OUT((*(request+1) & 1U));
break;
default:
*response = DAP_ERROR;
return ((2U << 16) | 1U);
}
*response = DAP_OK;
return ((2U << 16) | 1U);
}
// Process Connect command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
static uint32_t DAP_Connect(const uint8_t *request, uint8_t *response) {
uint32_t port;
if (*request == DAP_PORT_AUTODETECT) {
port = DAP_DEFAULT_PORT;
} else {
port = *request;
}
switch (port) {
#if (DAP_SWD != 0)
case DAP_PORT_SWD:
DAP_Data.debug_port = DAP_PORT_SWD;
PORT_SWD_SETUP();
break;
#endif
#if (DAP_JTAG != 0)
case DAP_PORT_JTAG:
DAP_Data.debug_port = DAP_PORT_JTAG;
PORT_JTAG_SETUP();
break;
#endif
default:
port = DAP_PORT_DISABLED;
break;
}
*response = (uint8_t)port;
return ((1U << 16) | 1U);
}
// Process Disconnect command and prepare response
// response: pointer to response data
// return: number of bytes in response
static uint32_t DAP_Disconnect(uint8_t *response) {
DAP_Data.debug_port = DAP_PORT_DISABLED;
PORT_OFF();
*response = DAP_OK;
return (1U);
}
// Process Reset Target command and prepare response
// response: pointer to response data
// return: number of bytes in response
static uint32_t DAP_ResetTarget(uint8_t *response) {
*(response+1) = RESET_TARGET();
*(response+0) = DAP_OK;
return (2U);
}
// Process SWJ Pins command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
static uint32_t DAP_SWJ_Pins(const uint8_t *request, uint8_t *response) {
#if ((DAP_SWD != 0) || (DAP_JTAG != 0))
uint32_t value;
uint32_t select;
uint32_t wait;
uint32_t timestamp;
value = (uint32_t) *(request+0);
select = (uint32_t) *(request+1);
wait = (uint32_t)(*(request+2) << 0) |
(uint32_t)(*(request+3) << 8) |
(uint32_t)(*(request+4) << 16) |
(uint32_t)(*(request+5) << 24);
if ((select & (1U << DAP_SWJ_SWCLK_TCK)) != 0U) {
if ((value & (1U << DAP_SWJ_SWCLK_TCK)) != 0U) {
PIN_SWCLK_TCK_SET();
} else {
PIN_SWCLK_TCK_CLR();
}
}
if ((select & (1U << DAP_SWJ_SWDIO_TMS)) != 0U) {
if ((value & (1U << DAP_SWJ_SWDIO_TMS)) != 0U) {
PIN_SWDIO_TMS_SET();
} else {
PIN_SWDIO_TMS_CLR();
}
}
if ((select & (1U << DAP_SWJ_TDI)) != 0U) {
PIN_TDI_OUT(value >> DAP_SWJ_TDI);
}
if ((select & (1U << DAP_SWJ_nTRST)) != 0U) {
PIN_nTRST_OUT(value >> DAP_SWJ_nTRST);
}
if ((select & (1U << DAP_SWJ_nRESET)) != 0U){
PIN_nRESET_OUT(value >> DAP_SWJ_nRESET);
}
if (wait != 0U) {
#if (TIMESTAMP_CLOCK != 0U)
if (wait > 3000000U) {
wait = 3000000U;
}
#if (TIMESTAMP_CLOCK >= 1000000U)
wait *= TIMESTAMP_CLOCK / 1000000U;
#else
wait /= 1000000U / TIMESTAMP_CLOCK;
#endif
#else
wait = 1U;
#endif
timestamp = TIMESTAMP_GET();
do {
if ((select & (1U << DAP_SWJ_SWCLK_TCK)) != 0U) {
if ((value >> DAP_SWJ_SWCLK_TCK) ^ PIN_SWCLK_TCK_IN()) {
continue;
}
}
if ((select & (1U << DAP_SWJ_SWDIO_TMS)) != 0U) {
if ((value >> DAP_SWJ_SWDIO_TMS) ^ PIN_SWDIO_TMS_IN()) {
continue;
}
}
if ((select & (1U << DAP_SWJ_TDI)) != 0U) {
if ((value >> DAP_SWJ_TDI) ^ PIN_TDI_IN()) {
continue;
}
}
if ((select & (1U << DAP_SWJ_nTRST)) != 0U) {
if ((value >> DAP_SWJ_nTRST) ^ PIN_nTRST_IN()) {
continue;
}
}
if ((select & (1U << DAP_SWJ_nRESET)) != 0U) {
if ((value >> DAP_SWJ_nRESET) ^ PIN_nRESET_IN()) {
continue;
}
}
break;
} while ((TIMESTAMP_GET() - timestamp) < wait);
}
value = (PIN_SWCLK_TCK_IN() << DAP_SWJ_SWCLK_TCK) |
(PIN_SWDIO_TMS_IN() << DAP_SWJ_SWDIO_TMS) |
(PIN_TDI_IN() << DAP_SWJ_TDI) |
(PIN_TDO_IN() << DAP_SWJ_TDO) |
(PIN_nTRST_IN() << DAP_SWJ_nTRST) |
(PIN_nRESET_IN() << DAP_SWJ_nRESET);
*response = (uint8_t)value;
#else
*response = 0U;
#endif
return ((6U << 16) | 1U);
}
// Process SWJ Clock command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
static uint32_t DAP_SWJ_Clock(const uint8_t *request, uint8_t *response) {
#if ((DAP_SWD != 0) || (DAP_JTAG != 0))
uint32_t clock;
uint32_t delay;
clock = (uint32_t)(*(request+0) << 0) |
(uint32_t)(*(request+1) << 8) |
(uint32_t)(*(request+2) << 16) |
(uint32_t)(*(request+3) << 24);
if (clock == 0U) {
*response = DAP_ERROR;
return ((4U << 16) | 1U);
}
Set_Clock_Delay(clock);
*response = DAP_OK;
#else
*response = DAP_ERROR;
#endif
return ((4U << 16) | 1U);
}
// Process SWJ Sequence command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
static uint32_t DAP_SWJ_Sequence(const uint8_t *request, uint8_t *response) {
uint32_t count;
count = *request++;
if (count == 0U) {
count = 256U;
}
#if ((DAP_SWD != 0) || (DAP_JTAG != 0))
SWJ_Sequence(count, request);
*response = DAP_OK;
#else
*response = DAP_ERROR;
#endif
count = (count + 7U) >> 3;
return (((count + 1U) << 16) | 1U);
}
// Process SWD Configure command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
static uint32_t DAP_SWD_Configure(const uint8_t *request, uint8_t *response) {
#if (DAP_SWD != 0)
uint8_t value;
value = *request;
DAP_Data.swd_conf.turnaround = (value & 0x03U) + 1U;
DAP_Data.swd_conf.data_phase = (value & 0x04U) ? 1U : 0U;
*response = DAP_OK;
#else
*response = DAP_ERROR;
#endif
return ((1U << 16) | 1U);
}
// Process SWD Sequence command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
static uint32_t DAP_SWD_Sequence(const uint8_t *request, uint8_t *response) {
uint32_t sequence_info;
uint32_t sequence_count;
uint32_t request_count;
uint32_t response_count;
uint32_t count;
#if (DAP_SWD != 0)
*response++ = DAP_OK;
#else
*response++ = DAP_ERROR;
#endif
request_count = 1U;
response_count = 1U;
sequence_count = *request++;
while (sequence_count--) {
sequence_info = *request++;
count = sequence_info & SWD_SEQUENCE_CLK;
if (count == 0U) {
count = 64U;
}
count = (count + 7U) / 8U;
#if (DAP_SWD != 0)
if ((sequence_info & SWD_SEQUENCE_DIN) != 0U) {
PIN_SWDIO_OUT_DISABLE();
} else {
PIN_SWDIO_OUT_ENABLE();
}
SWD_Sequence(sequence_info, request, response);
if (sequence_count == 0U) {
PIN_SWDIO_OUT_ENABLE();
}
#endif
if ((sequence_info & SWD_SEQUENCE_DIN) != 0U) {
request_count++;
#if (DAP_SWD != 0)
response += count;
response_count += count;
#endif
} else {
request += count;
request_count += count + 1U;
}
}
return ((request_count << 16) | response_count);
}
// Process JTAG Sequence command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
static uint32_t DAP_JTAG_Sequence(const uint8_t *request, uint8_t *response) {
uint32_t sequence_info;
uint32_t sequence_count;
uint32_t request_count;
uint32_t response_count;
uint32_t count;
#if (DAP_JTAG != 0)
*response++ = DAP_OK;
#else
*response++ = DAP_ERROR;
#endif
request_count = 1U;
response_count = 1U;
sequence_count = *request++;
while (sequence_count--) {
sequence_info = *request++;
count = sequence_info & JTAG_SEQUENCE_TCK;
if (count == 0U) {
count = 64U;
}
count = (count + 7U) / 8U;
#if (DAP_JTAG != 0)
JTAG_Sequence(sequence_info, request, response);
#endif
request += count;
request_count += count + 1U;
#if (DAP_JTAG != 0)
if ((sequence_info & JTAG_SEQUENCE_TDO) != 0U) {
response += count;
response_count += count;
}
#endif
}
return ((request_count << 16) | response_count);
}
// Process JTAG Configure command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
static uint32_t DAP_JTAG_Configure(const uint8_t *request, uint8_t *response) {
uint32_t count;
#if (DAP_JTAG != 0)
uint32_t length;
uint32_t bits;
uint32_t n;
count = *request++;
DAP_Data.jtag_dev.count = (uint8_t)count;
bits = 0U;
for (n = 0U; n < count; n++) {
length = *request++;
DAP_Data.jtag_dev.ir_length[n] = (uint8_t)length;
DAP_Data.jtag_dev.ir_before[n] = (uint16_t)bits;
bits += length;
}
for (n = 0U; n < count; n++) {
bits -= DAP_Data.jtag_dev.ir_length[n];
DAP_Data.jtag_dev.ir_after[n] = (uint16_t)bits;
}
*response = DAP_OK;
#else
count = *request;
*response = DAP_ERROR;
#endif
return (((count + 1U) << 16) | 1U);
}
// Process JTAG IDCODE command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
static uint32_t DAP_JTAG_IDCode(const uint8_t *request, uint8_t *response) {
#if (DAP_JTAG != 0)
uint32_t data;
if (DAP_Data.debug_port != DAP_PORT_JTAG) {
goto id_error;
}
// Device index (JTAP TAP)
DAP_Data.jtag_dev.index = *request;
if (DAP_Data.jtag_dev.index >= DAP_Data.jtag_dev.count) {
goto id_error;
}
// Select JTAG chain
JTAG_IR(JTAG_IDCODE);
// Read IDCODE register
data = JTAG_ReadIDCode();
// Store Data
*(response+0) = DAP_OK;
*(response+1) = (uint8_t)(data >> 0);
*(response+2) = (uint8_t)(data >> 8);
*(response+3) = (uint8_t)(data >> 16);
*(response+4) = (uint8_t)(data >> 24);
return ((1U << 16) | 5U);
id_error:
#endif
*response = DAP_ERROR;
return ((1U << 16) | 1U);
}
// Process Transfer Configure command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
static uint32_t DAP_TransferConfigure(const uint8_t *request, uint8_t *response) {
DAP_Data.transfer.idle_cycles = *(request+0);
DAP_Data.transfer.retry_count = (uint16_t) *(request+1) |
(uint16_t)(*(request+2) << 8);
DAP_Data.transfer.match_retry = (uint16_t) *(request+3) |
(uint16_t)(*(request+4) << 8);
*response = DAP_OK;
return ((5U << 16) | 1U);
}
// Process SWD Transfer command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
#if (DAP_SWD != 0)
static uint32_t DAP_SWD_Transfer(const uint8_t *request, uint8_t *response) {
const
uint8_t *request_head;
uint32_t request_count;
uint32_t request_value;
uint8_t *response_head;
uint32_t response_count;
uint32_t response_value;
uint32_t post_read;
uint32_t check_write;
uint32_t match_value;
uint32_t match_retry;
uint32_t retry;
uint32_t data;
#if (TIMESTAMP_CLOCK != 0U)
uint32_t timestamp;
#endif
request_head = request;
response_count = 0U;
response_value = 0U;
response_head = response;
response += 2;
DAP_TransferAbort = 0U;
post_read = 0U;
check_write = 0U;
request++; // Ignore DAP index
request_count = *request++;
while (request_count != 0) {
request_count--;
request_value = *request++;
if ((request_value & DAP_TRANSFER_RnW) != 0U) {
// Read register
if (post_read) {
// Read was posted before
retry = DAP_Data.transfer.retry_count;
if ((request_value & (DAP_TRANSFER_APnDP | DAP_TRANSFER_MATCH_VALUE)) == DAP_TRANSFER_APnDP) {
// Read previous AP data and post next AP read
do {
response_value = SWD_Transfer(request_value, &data);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
} else {
// Read previous AP data
do {
response_value = SWD_Transfer(DP_RDBUFF | DAP_TRANSFER_RnW, &data);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
post_read = 0U;
}
if (response_value != DAP_TRANSFER_OK) {
break;
}
// Store previous AP data
*response++ = (uint8_t) data;
*response++ = (uint8_t)(data >> 8);
*response++ = (uint8_t)(data >> 16);
*response++ = (uint8_t)(data >> 24);
#if (TIMESTAMP_CLOCK != 0U)
if (post_read) {
// Store Timestamp of next AP read
if ((request_value & DAP_TRANSFER_TIMESTAMP) != 0U) {
timestamp = DAP_Data.timestamp;
*response++ = (uint8_t) timestamp;
*response++ = (uint8_t)(timestamp >> 8);
*response++ = (uint8_t)(timestamp >> 16);
*response++ = (uint8_t)(timestamp >> 24);
}
}
#endif
}
if ((request_value & DAP_TRANSFER_MATCH_VALUE) != 0U) {
// Read with value match
match_value = (uint32_t)(*(request+0) << 0) |
(uint32_t)(*(request+1) << 8) |
(uint32_t)(*(request+2) << 16) |
(uint32_t)(*(request+3) << 24);
request += 4;
match_retry = DAP_Data.transfer.match_retry;
if ((request_value & DAP_TRANSFER_APnDP) != 0U) {
// Post AP read
retry = DAP_Data.transfer.retry_count;
do {
response_value = SWD_Transfer(request_value, NULL);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
if (response_value != DAP_TRANSFER_OK) {
break;
}
}
do {
// Read register until its value matches or retry counter expires
retry = DAP_Data.transfer.retry_count;
do {
response_value = SWD_Transfer(request_value, &data);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
if (response_value != DAP_TRANSFER_OK) {
break;
}
} while (((data & DAP_Data.transfer.match_mask) != match_value) && match_retry-- && !DAP_TransferAbort);
if ((data & DAP_Data.transfer.match_mask) != match_value) {
response_value |= DAP_TRANSFER_MISMATCH;
}
if (response_value != DAP_TRANSFER_OK) {
break;
}
} else {
// Normal read
retry = DAP_Data.transfer.retry_count;
if ((request_value & DAP_TRANSFER_APnDP) != 0U) {
// Read AP register
if (post_read == 0U) {
// Post AP read
do {
response_value = SWD_Transfer(request_value, NULL);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
if (response_value != DAP_TRANSFER_OK) {
break;
}
#if (TIMESTAMP_CLOCK != 0U)
// Store Timestamp
if ((request_value & DAP_TRANSFER_TIMESTAMP) != 0U) {
timestamp = DAP_Data.timestamp;
*response++ = (uint8_t) timestamp;
*response++ = (uint8_t)(timestamp >> 8);
*response++ = (uint8_t)(timestamp >> 16);
*response++ = (uint8_t)(timestamp >> 24);
}
#endif
post_read = 1U;
}
} else {
// Read DP register
do {
response_value = SWD_Transfer(request_value, &data);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
if (response_value != DAP_TRANSFER_OK) {
break;
}
#if (TIMESTAMP_CLOCK != 0U)
// Store Timestamp
if ((request_value & DAP_TRANSFER_TIMESTAMP) != 0U) {
timestamp = DAP_Data.timestamp;
*response++ = (uint8_t) timestamp;
*response++ = (uint8_t)(timestamp >> 8);
*response++ = (uint8_t)(timestamp >> 16);
*response++ = (uint8_t)(timestamp >> 24);
}
#endif
// Store data
*response++ = (uint8_t) data;
*response++ = (uint8_t)(data >> 8);
*response++ = (uint8_t)(data >> 16);
*response++ = (uint8_t)(data >> 24);
}
}
check_write = 0U;
} else {
// Write register
if (post_read) {
// Read previous data
retry = DAP_Data.transfer.retry_count;
do {
response_value = SWD_Transfer(DP_RDBUFF | DAP_TRANSFER_RnW, &data);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
if (response_value != DAP_TRANSFER_OK) {
break;
}
// Store previous data
*response++ = (uint8_t) data;
*response++ = (uint8_t)(data >> 8);
*response++ = (uint8_t)(data >> 16);
*response++ = (uint8_t)(data >> 24);
post_read = 0U;
}
// Load data
data = (uint32_t)(*(request+0) << 0) |
(uint32_t)(*(request+1) << 8) |
(uint32_t)(*(request+2) << 16) |
(uint32_t)(*(request+3) << 24);
request += 4;
if ((request_value & DAP_TRANSFER_MATCH_MASK) != 0U) {
// Write match mask
DAP_Data.transfer.match_mask = data;
response_value = DAP_TRANSFER_OK;
} else {
// Write DP/AP register
retry = DAP_Data.transfer.retry_count;
do {
response_value = SWD_Transfer(request_value, &data);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
if (response_value != DAP_TRANSFER_OK) {
break;
}
#if (TIMESTAMP_CLOCK != 0U)
// Store Timestamp
if ((request_value & DAP_TRANSFER_TIMESTAMP) != 0U) {
timestamp = DAP_Data.timestamp;
*response++ = (uint8_t) timestamp;
*response++ = (uint8_t)(timestamp >> 8);
*response++ = (uint8_t)(timestamp >> 16);
*response++ = (uint8_t)(timestamp >> 24);
}
#endif
check_write = 1U;
}
}
response_count++;
if (DAP_TransferAbort) {
break;
}
}
while (request_count != 0) {
// Process canceled requests
request_count--;
request_value = *request++;
if ((request_value & DAP_TRANSFER_RnW) != 0U) {
// Read register
if ((request_value & DAP_TRANSFER_MATCH_VALUE) != 0U) {
// Read with value match
request += 4;
}
} else {
// Write register
request += 4;
}
}
if (response_value == DAP_TRANSFER_OK) {
if (post_read) {
// Read previous data
retry = DAP_Data.transfer.retry_count;
do {
response_value = SWD_Transfer(DP_RDBUFF | DAP_TRANSFER_RnW, &data);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
if (response_value != DAP_TRANSFER_OK) {
goto end;
}
// Store previous data
*response++ = (uint8_t) data;
*response++ = (uint8_t)(data >> 8);
*response++ = (uint8_t)(data >> 16);
*response++ = (uint8_t)(data >> 24);
} else if (check_write) {
// Check last write
retry = DAP_Data.transfer.retry_count;
do {
response_value = SWD_Transfer(DP_RDBUFF | DAP_TRANSFER_RnW, NULL);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
}
}
end:
*(response_head+0) = (uint8_t)response_count;
*(response_head+1) = (uint8_t)response_value;
return (((uint32_t)(request - request_head) << 16) | (uint32_t)(response - response_head));
}
#endif
// Process JTAG Transfer command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
#if (DAP_JTAG != 0)
static uint32_t DAP_JTAG_Transfer(const uint8_t *request, uint8_t *response) {
const
uint8_t *request_head;
uint32_t request_count;
uint32_t request_value;
uint32_t request_ir;
uint8_t *response_head;
uint32_t response_count;
uint32_t response_value;
uint32_t post_read;
uint32_t match_value;
uint32_t match_retry;
uint32_t retry;
uint32_t data;
uint32_t ir;
#if (TIMESTAMP_CLOCK != 0U)
uint32_t timestamp;
#endif
request_head = request;
response_count = 0U;
response_value = 0U;
response_head = response;
response += 2;
DAP_TransferAbort = 0U;
ir = 0U;
post_read = 0U;
// Device index (JTAP TAP)
DAP_Data.jtag_dev.index = *request++;
if (DAP_Data.jtag_dev.index >= DAP_Data.jtag_dev.count) {
goto end;
}
request_count = *request++;
while (request_count != 0) {
request_count--;
request_value = *request++;
request_ir = (request_value & DAP_TRANSFER_APnDP) ? JTAG_APACC : JTAG_DPACC;
if ((request_value & DAP_TRANSFER_RnW) != 0U) {
// Read register
if (post_read) {
// Read was posted before
retry = DAP_Data.transfer.retry_count;
if ((ir == request_ir) && ((request_value & DAP_TRANSFER_MATCH_VALUE) == 0U)) {
// Read previous data and post next read
do {
response_value = JTAG_Transfer(request_value, &data);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
} else {
// Select JTAG chain
if (ir != JTAG_DPACC) {
ir = JTAG_DPACC;
JTAG_IR(ir);
}
// Read previous data
do {
response_value = JTAG_Transfer(DP_RDBUFF | DAP_TRANSFER_RnW, &data);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
post_read = 0U;
}
if (response_value != DAP_TRANSFER_OK) {
break;
}
// Store previous data
*response++ = (uint8_t) data;
*response++ = (uint8_t)(data >> 8);
*response++ = (uint8_t)(data >> 16);
*response++ = (uint8_t)(data >> 24);
#if (TIMESTAMP_CLOCK != 0U)
if (post_read) {
// Store Timestamp of next AP read
if ((request_value & DAP_TRANSFER_TIMESTAMP) != 0U) {
timestamp = DAP_Data.timestamp;
*response++ = (uint8_t) timestamp;
*response++ = (uint8_t)(timestamp >> 8);
*response++ = (uint8_t)(timestamp >> 16);
*response++ = (uint8_t)(timestamp >> 24);
}
}
#endif
}
if ((request_value & DAP_TRANSFER_MATCH_VALUE) != 0U) {
// Read with value match
match_value = (uint32_t)(*(request+0) << 0) |
(uint32_t)(*(request+1) << 8) |
(uint32_t)(*(request+2) << 16) |
(uint32_t)(*(request+3) << 24);
request += 4;
match_retry = DAP_Data.transfer.match_retry;
// Select JTAG chain
if (ir != request_ir) {
ir = request_ir;
JTAG_IR(ir);
}
// Post DP/AP read
retry = DAP_Data.transfer.retry_count;
do {
response_value = JTAG_Transfer(request_value, NULL);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
if (response_value != DAP_TRANSFER_OK) {
break;
}
do {
// Read register until its value matches or retry counter expires
retry = DAP_Data.transfer.retry_count;
do {
response_value = JTAG_Transfer(request_value, &data);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
if (response_value != DAP_TRANSFER_OK) {
break;
}
} while (((data & DAP_Data.transfer.match_mask) != match_value) && match_retry-- && !DAP_TransferAbort);
if ((data & DAP_Data.transfer.match_mask) != match_value) {
response_value |= DAP_TRANSFER_MISMATCH;
}
if (response_value != DAP_TRANSFER_OK) {
break;
}
} else {
// Normal read
if (post_read == 0U) {
// Select JTAG chain
if (ir != request_ir) {
ir = request_ir;
JTAG_IR(ir);
}
// Post DP/AP read
retry = DAP_Data.transfer.retry_count;
do {
response_value = JTAG_Transfer(request_value, NULL);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
if (response_value != DAP_TRANSFER_OK) {
break;
}
#if (TIMESTAMP_CLOCK != 0U)
// Store Timestamp
if ((request_value & DAP_TRANSFER_TIMESTAMP) != 0U) {
timestamp = DAP_Data.timestamp;
*response++ = (uint8_t) timestamp;
*response++ = (uint8_t)(timestamp >> 8);
*response++ = (uint8_t)(timestamp >> 16);
*response++ = (uint8_t)(timestamp >> 24);
}
#endif
post_read = 1U;
}
}
} else {
// Write register
if (post_read) {
// Select JTAG chain
if (ir != JTAG_DPACC) {
ir = JTAG_DPACC;
JTAG_IR(ir);
}
// Read previous data
retry = DAP_Data.transfer.retry_count;
do {
response_value = JTAG_Transfer(DP_RDBUFF | DAP_TRANSFER_RnW, &data);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
if (response_value != DAP_TRANSFER_OK) {
break;
}
// Store previous data
*response++ = (uint8_t) data;
*response++ = (uint8_t)(data >> 8);
*response++ = (uint8_t)(data >> 16);
*response++ = (uint8_t)(data >> 24);
post_read = 0U;
}
// Load data
data = (uint32_t)(*(request+0) << 0) |
(uint32_t)(*(request+1) << 8) |
(uint32_t)(*(request+2) << 16) |
(uint32_t)(*(request+3) << 24);
request += 4;
if ((request_value & DAP_TRANSFER_MATCH_MASK) != 0U) {
// Write match mask
DAP_Data.transfer.match_mask = data;
response_value = DAP_TRANSFER_OK;
} else {
// Select JTAG chain
if (ir != request_ir) {
ir = request_ir;
JTAG_IR(ir);
}
// Write DP/AP register
retry = DAP_Data.transfer.retry_count;
do {
response_value = JTAG_Transfer(request_value, &data);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
if (response_value != DAP_TRANSFER_OK) {
break;
}
#if (TIMESTAMP_CLOCK != 0U)
// Store Timestamp
if ((request_value & DAP_TRANSFER_TIMESTAMP) != 0U) {
timestamp = DAP_Data.timestamp;
*response++ = (uint8_t) timestamp;
*response++ = (uint8_t)(timestamp >> 8);
*response++ = (uint8_t)(timestamp >> 16);
*response++ = (uint8_t)(timestamp >> 24);
}
#endif
}
}
response_count++;
if (DAP_TransferAbort) {
break;
}
}
while (request_count != 0) {
// Process canceled requests
request_count--;
request_value = *request++;
if ((request_value & DAP_TRANSFER_RnW) != 0U) {
// Read register
if ((request_value & DAP_TRANSFER_MATCH_VALUE) != 0U) {
// Read with value match
request += 4;
}
} else {
// Write register
request += 4;
}
}
if (response_value == DAP_TRANSFER_OK) {
// Select JTAG chain
if (ir != JTAG_DPACC) {
ir = JTAG_DPACC;
JTAG_IR(ir);
}
if (post_read) {
// Read previous data
retry = DAP_Data.transfer.retry_count;
do {
response_value = JTAG_Transfer(DP_RDBUFF | DAP_TRANSFER_RnW, &data);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
if (response_value != DAP_TRANSFER_OK) {
goto end;
}
// Store previous data
*response++ = (uint8_t) data;
*response++ = (uint8_t)(data >> 8);
*response++ = (uint8_t)(data >> 16);
*response++ = (uint8_t)(data >> 24);
} else {
// Check last write
retry = DAP_Data.transfer.retry_count;
do {
response_value = JTAG_Transfer(DP_RDBUFF | DAP_TRANSFER_RnW, NULL);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
}
}
end:
*(response_head+0) = (uint8_t)response_count;
*(response_head+1) = (uint8_t)response_value;
return (((uint32_t)(request - request_head) << 16) | (uint32_t)(response - response_head));
}
#endif
// Process Dummy Transfer command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
static uint32_t DAP_Dummy_Transfer(const uint8_t *request, uint8_t *response) {
const
uint8_t *request_head;
uint32_t request_count;
uint32_t request_value;
request_head = request;
request++; // Ignore DAP index
request_count = *request++;
for (; request_count != 0U; request_count--) {
// Process dummy requests
request_value = *request++;
if ((request_value & DAP_TRANSFER_RnW) != 0U) {
// Read register
if ((request_value & DAP_TRANSFER_MATCH_VALUE) != 0U) {
// Read with value match
request += 4;
}
} else {
// Write register
request += 4;
}
}
*(response+0) = 0U; // Response count
*(response+1) = 0U; // Response value
return (((uint32_t)(request - request_head) << 16) | 2U);
}
// Process Transfer command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
static uint32_t DAP_Transfer(const uint8_t *request, uint8_t *response) {
uint32_t num;
switch (DAP_Data.debug_port) {
#if (DAP_SWD != 0)
case DAP_PORT_SWD:
num = DAP_SWD_Transfer(request, response);
break;
#endif
#if (DAP_JTAG != 0)
case DAP_PORT_JTAG:
num = DAP_JTAG_Transfer(request, response);
break;
#endif
default:
num = DAP_Dummy_Transfer(request, response);
break;
}
return (num);
}
// Process SWD Transfer Block command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response
#if (DAP_SWD != 0)
static uint32_t DAP_SWD_TransferBlock(const uint8_t *request, uint8_t *response) {
uint32_t request_count;
uint32_t request_value;
uint32_t response_count;
uint32_t response_value;
uint8_t *response_head;
uint32_t retry;
uint32_t data;
response_count = 0U;
response_value = 0U;
response_head = response;
response += 3;
DAP_TransferAbort = 0U;
request++; // Ignore DAP index
request_count = (uint32_t)(*(request+0) << 0) |
(uint32_t)(*(request+1) << 8);
request += 2;
if (request_count == 0U) {
goto end;
}
request_value = *request++;
if ((request_value & DAP_TRANSFER_RnW) != 0U) {
// Read register block
if ((request_value & DAP_TRANSFER_APnDP) != 0U) {
// Post AP read
retry = DAP_Data.transfer.retry_count;
do {
response_value = SWD_Transfer(request_value, NULL);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
if (response_value != DAP_TRANSFER_OK) {
goto end;
}
}
while (request_count--) {
// Read DP/AP register
if ((request_count == 0U) && ((request_value & DAP_TRANSFER_APnDP) != 0U)) {
// Last AP read
request_value = DP_RDBUFF | DAP_TRANSFER_RnW;
}
retry = DAP_Data.transfer.retry_count;
do {
response_value = SWD_Transfer(request_value, &data);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
if (response_value != DAP_TRANSFER_OK) {
goto end;
}
// Store data
*response++ = (uint8_t) data;
*response++ = (uint8_t)(data >> 8);
*response++ = (uint8_t)(data >> 16);
*response++ = (uint8_t)(data >> 24);
response_count++;
}
} else {
// Write register block
while (request_count--) {
// Load data
data = (uint32_t)(*(request+0) << 0) |
(uint32_t)(*(request+1) << 8) |
(uint32_t)(*(request+2) << 16) |
(uint32_t)(*(request+3) << 24);
request += 4;
// Write DP/AP register
retry = DAP_Data.transfer.retry_count;
do {
response_value = SWD_Transfer(request_value, &data);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
if (response_value != DAP_TRANSFER_OK) {
goto end;
}
response_count++;
}
// Check last write
retry = DAP_Data.transfer.retry_count;
do {
response_value = SWD_Transfer(DP_RDBUFF | DAP_TRANSFER_RnW, NULL);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
}
end:
*(response_head+0) = (uint8_t)(response_count >> 0);
*(response_head+1) = (uint8_t)(response_count >> 8);
*(response_head+2) = (uint8_t) response_value;
return ((uint32_t)(response - response_head));
}
#endif
// Process JTAG Transfer Block command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response
#if (DAP_JTAG != 0)
static uint32_t DAP_JTAG_TransferBlock(const uint8_t *request, uint8_t *response) {
uint32_t request_count;
uint32_t request_value;
uint32_t response_count;
uint32_t response_value;
uint8_t *response_head;
uint32_t retry;
uint32_t data;
uint32_t ir;
response_count = 0U;
response_value = 0U;
response_head = response;
response += 3;
DAP_TransferAbort = 0U;
// Device index (JTAP TAP)
DAP_Data.jtag_dev.index = *request++;
if (DAP_Data.jtag_dev.index >= DAP_Data.jtag_dev.count) {
goto end;
}
request_count = (uint32_t)(*(request+0) << 0) |
(uint32_t)(*(request+1) << 8);
request += 2;
if (request_count == 0U) {
goto end;
}
request_value = *request++;
// Select JTAG chain
ir = (request_value & DAP_TRANSFER_APnDP) ? JTAG_APACC : JTAG_DPACC;
JTAG_IR(ir);
if ((request_value & DAP_TRANSFER_RnW) != 0U) {
// Post read
retry = DAP_Data.transfer.retry_count;
do {
response_value = JTAG_Transfer(request_value, NULL);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
if (response_value != DAP_TRANSFER_OK) {
goto end;
}
// Read register block
while (request_count--) {
// Read DP/AP register
if (request_count == 0U) {
// Last read
if (ir != JTAG_DPACC) {
JTAG_IR(JTAG_DPACC);
}
request_value = DP_RDBUFF | DAP_TRANSFER_RnW;
}
retry = DAP_Data.transfer.retry_count;
do {
response_value = JTAG_Transfer(request_value, &data);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
if (response_value != DAP_TRANSFER_OK) {
goto end;
}
// Store data
*response++ = (uint8_t) data;
*response++ = (uint8_t)(data >> 8);
*response++ = (uint8_t)(data >> 16);
*response++ = (uint8_t)(data >> 24);
response_count++;
}
} else {
// Write register block
while (request_count--) {
// Load data
data = (uint32_t)(*(request+0) << 0) |
(uint32_t)(*(request+1) << 8) |
(uint32_t)(*(request+2) << 16) |
(uint32_t)(*(request+3) << 24);
request += 4;
// Write DP/AP register
retry = DAP_Data.transfer.retry_count;
do {
response_value = JTAG_Transfer(request_value, &data);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
if (response_value != DAP_TRANSFER_OK) {
goto end;
}
response_count++;
}
// Check last write
if (ir != JTAG_DPACC) {
JTAG_IR(JTAG_DPACC);
}
retry = DAP_Data.transfer.retry_count;
do {
response_value = JTAG_Transfer(DP_RDBUFF | DAP_TRANSFER_RnW, NULL);
} while ((response_value == DAP_TRANSFER_WAIT) && retry-- && !DAP_TransferAbort);
}
end:
*(response_head+0) = (uint8_t)(response_count >> 0);
*(response_head+1) = (uint8_t)(response_count >> 8);
*(response_head+2) = (uint8_t) response_value;
return ((uint32_t)(response - response_head));
}
#endif
// Process Transfer Block command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
static uint32_t DAP_TransferBlock(const uint8_t *request, uint8_t *response) {
uint32_t num;
switch (DAP_Data.debug_port) {
#if (DAP_SWD != 0)
case DAP_PORT_SWD:
num = DAP_SWD_TransferBlock (request, response);
break;
#endif
#if (DAP_JTAG != 0)
case DAP_PORT_JTAG:
num = DAP_JTAG_TransferBlock(request, response);
break;
#endif
default:
*(response+0) = 0U; // Response count [7:0]
*(response+1) = 0U; // Response count[15:8]
*(response+2) = 0U; // Response value
num = 3U;
break;
}
if ((*(request+3) & DAP_TRANSFER_RnW) != 0U) {
// Read register block
num |= 4U << 16;
} else {
// Write register block
num |= (4U + (((uint32_t)(*(request+1)) | (uint32_t)(*(request+2) << 8)) * 4)) << 16;
}
return (num);
}
// Process SWD Write ABORT command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response
#if (DAP_SWD != 0)
static uint32_t DAP_SWD_WriteAbort(const uint8_t *request, uint8_t *response) {
uint32_t data;
// Load data (Ignore DAP index)
data = (uint32_t)(*(request+1) << 0) |
(uint32_t)(*(request+2) << 8) |
(uint32_t)(*(request+3) << 16) |
(uint32_t)(*(request+4) << 24);
// Write Abort register
SWD_Transfer(DP_ABORT, &data);
*response = DAP_OK;
return (1U);
}
#endif
// Process JTAG Write ABORT command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response
#if (DAP_JTAG != 0)
static uint32_t DAP_JTAG_WriteAbort(const uint8_t *request, uint8_t *response) {
uint32_t data;
// Device index (JTAP TAP)
DAP_Data.jtag_dev.index = *request;
if (DAP_Data.jtag_dev.index >= DAP_Data.jtag_dev.count) {
*response = DAP_ERROR;
return (1U);
}
// Select JTAG chain
JTAG_IR(JTAG_ABORT);
// Load data
data = (uint32_t)(*(request+1) << 0) |
(uint32_t)(*(request+2) << 8) |
(uint32_t)(*(request+3) << 16) |
(uint32_t)(*(request+4) << 24);
// Write Abort register
JTAG_WriteAbort(data);
*response = DAP_OK;
return (1U);
}
#endif
// Process Write ABORT command and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
static uint32_t DAP_WriteAbort(const uint8_t *request, uint8_t *response) {
uint32_t num;
switch (DAP_Data.debug_port) {
#if (DAP_SWD != 0)
case DAP_PORT_SWD:
num = DAP_SWD_WriteAbort (request, response);
break;
#endif
#if (DAP_JTAG != 0)
case DAP_PORT_JTAG:
num = DAP_JTAG_WriteAbort(request, response);
break;
#endif
default:
*response = DAP_ERROR;
num = 1U;
break;
}
return ((5U << 16) | num);
}
// Process DAP Vendor command request and prepare response
// Default function (can be overridden)
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
__WEAK uint32_t DAP_ProcessVendorCommand(const uint8_t *request, uint8_t *response) {
(void)request;
*response = ID_DAP_Invalid;
return ((1U << 16) | 1U);
}
// Process DAP command request and prepare response
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
uint32_t DAP_ProcessCommand(const uint8_t *request, uint8_t *response) {
uint32_t num;
if ((*request >= ID_DAP_Vendor0) && (*request <= ID_DAP_Vendor31)) {
return DAP_ProcessVendorCommand(request, response);
}
*response++ = *request;
switch (*request++) {
case ID_DAP_Info:
num = DAP_Info(*request, response+1);
*response = (uint8_t)num;
return ((2U << 16) + 2U + num);
case ID_DAP_HostStatus:
num = DAP_HostStatus(request, response);
break;
case ID_DAP_Connect:
num = DAP_Connect(request, response);
break;
case ID_DAP_Disconnect:
num = DAP_Disconnect(response);
break;
case ID_DAP_Delay:
num = DAP_Delay(request, response);
break;
case ID_DAP_ResetTarget:
num = DAP_ResetTarget(response);
break;
case ID_DAP_SWJ_Pins:
num = DAP_SWJ_Pins(request, response);
break;
case ID_DAP_SWJ_Clock:
num = DAP_SWJ_Clock(request, response);
break;
case ID_DAP_SWJ_Sequence:
num = DAP_SWJ_Sequence(request, response);
break;
case ID_DAP_SWD_Configure:
num = DAP_SWD_Configure(request, response);
break;
case ID_DAP_SWD_Sequence:
num = DAP_SWD_Sequence(request, response);
break;
case ID_DAP_JTAG_Sequence:
num = DAP_JTAG_Sequence(request, response);
break;
case ID_DAP_JTAG_Configure:
num = DAP_JTAG_Configure(request, response);
break;
case ID_DAP_JTAG_IDCODE:
num = DAP_JTAG_IDCode(request, response);
break;
case ID_DAP_TransferConfigure:
num = DAP_TransferConfigure(request, response);
break;
case ID_DAP_Transfer:
num = DAP_Transfer(request, response);
break;
case ID_DAP_TransferBlock:
num = DAP_TransferBlock(request, response);
break;
case ID_DAP_WriteABORT:
num = DAP_WriteAbort(request, response);
break;
#if ((SWO_UART != 0) || (SWO_MANCHESTER != 0))
case ID_DAP_SWO_Transport:
num = SWO_Transport(request, response);
break;
case ID_DAP_SWO_Mode:
num = SWO_Mode(request, response);
break;
case ID_DAP_SWO_Baudrate:
num = SWO_Baudrate(request, response);
break;
case ID_DAP_SWO_Control:
num = SWO_Control(request, response);
break;
case ID_DAP_SWO_Status:
num = SWO_Status(response);
break;
case ID_DAP_SWO_ExtendedStatus:
num = SWO_ExtendedStatus(request, response);
break;
case ID_DAP_SWO_Data:
num = SWO_Data(request, response);
break;
#endif
#if (DAP_UART != 0)
case ID_DAP_UART_Transport:
num = UART_Transport(request, response);
break;
case ID_DAP_UART_Configure:
num = UART_Configure(request, response);
break;
case ID_DAP_UART_Control:
num = UART_Control(request, response);
break;
case ID_DAP_UART_Status:
num = UART_Status(response);
break;
case ID_DAP_UART_Transfer:
num = UART_Transfer(request, response);
break;
#endif
default:
*(response-1) = ID_DAP_Invalid;
return ((1U << 16) | 1U);
}
return ((1U << 16) + 1U + num);
}
// Execute DAP command (process request and prepare response)
// request: pointer to request data
// response: pointer to response data
// return: number of bytes in response (lower 16 bits)
// number of bytes in request (upper 16 bits)
uint32_t DAP_ExecuteCommand(const uint8_t *request, uint8_t *response) {
uint32_t cnt, num, n;
if (*request == ID_DAP_ExecuteCommands) {
*response++ = *request++;
cnt = *request++;
*response++ = (uint8_t)cnt;
num = (2U << 16) | 2U;
while (cnt--) {
n = DAP_ProcessCommand(request, response);
num += n;
request += (uint16_t)(n >> 16);
response += (uint16_t) n;
}
return (num);
}
return DAP_ProcessCommand(request, response);
}
// Setup DAP
void DAP_Setup(void) {
// Default settings
DAP_Data.debug_port = 0U;
DAP_Data.transfer.idle_cycles = 0U;
DAP_Data.transfer.retry_count = 100U;
DAP_Data.transfer.match_retry = 0U;
DAP_Data.transfer.match_mask = 0x00000000U;
#if (DAP_SWD != 0)
DAP_Data.swd_conf.turnaround = 1U;
DAP_Data.swd_conf.data_phase = 0U;
#endif
#if (DAP_JTAG != 0)
DAP_Data.jtag_dev.count = 0U;
#endif
// Sets DAP_Data.fast_clock and DAP_Data.clock_delay.
Set_Clock_Delay(DAP_DEFAULT_SWJ_CLOCK);
DAP_SETUP(); // Device specific setup
}
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Source/DAP.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 15,320 |
```c
/*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* your_sha256_hash------
*
* $Date: 1. December 2017
* $Revision: V2.0.0
*
* Project: CMSIS-DAP Source
* Title: SW_DP.c CMSIS-DAP SW DP I/O
*
*your_sha256_hash-----------*/
#include "DAP_config.h"
#include "DAP.h"
// SW Macros
#define PIN_SWCLK_SET PIN_SWCLK_TCK_SET
#define PIN_SWCLK_CLR PIN_SWCLK_TCK_CLR
#define SW_CLOCK_CYCLE() \
PIN_SWCLK_CLR(); \
PIN_DELAY(); \
PIN_SWCLK_SET(); \
PIN_DELAY()
#define SW_WRITE_BIT(bit) \
PIN_SWDIO_OUT(bit); \
PIN_SWCLK_CLR(); \
PIN_DELAY(); \
PIN_SWCLK_SET(); \
PIN_DELAY()
#define SW_READ_BIT(bit) \
PIN_SWCLK_CLR(); \
PIN_DELAY(); \
bit = PIN_SWDIO_IN(); \
PIN_SWCLK_SET(); \
PIN_DELAY()
#define PIN_DELAY() PIN_DELAY_SLOW(DAP_Data.clock_delay)
// Generate SWJ Sequence
// count: sequence bit count
// data: pointer to sequence bit data
// return: none
#if ((DAP_SWD != 0) || (DAP_JTAG != 0))
void SWJ_Sequence (uint32_t count, const uint8_t *data) {
uint32_t val;
uint32_t n;
val = 0U;
n = 0U;
while (count--) {
if (n == 0U) {
val = *data++;
n = 8U;
}
if (val & 1U) {
PIN_SWDIO_TMS_SET();
} else {
PIN_SWDIO_TMS_CLR();
}
SW_CLOCK_CYCLE();
val >>= 1;
n--;
}
}
#endif
// Generate SWD Sequence
// info: sequence information
// swdo: pointer to SWDIO generated data
// swdi: pointer to SWDIO captured data
// return: none
#if (DAP_SWD != 0)
void SWD_Sequence (uint32_t info, const uint8_t *swdo, uint8_t *swdi) {
uint32_t val;
uint32_t bit;
uint32_t n, k;
n = info & SWD_SEQUENCE_CLK;
if (n == 0U) {
n = 64U;
}
if (info & SWD_SEQUENCE_DIN) {
while (n) {
val = 0U;
for (k = 8U; k && n; k--, n--) {
SW_READ_BIT(bit);
val >>= 1;
val |= bit << 7;
}
val >>= k;
*swdi++ = (uint8_t)val;
}
} else {
while (n) {
val = *swdo++;
for (k = 8U; k && n; k--, n--) {
SW_WRITE_BIT(val);
val >>= 1;
}
}
}
}
#endif
#if (DAP_SWD != 0)
// SWD Transfer I/O
// request: A[3:2] RnW APnDP
// data: DATA[31:0]
// return: ACK[2:0]
#define SWD_TransferFunction(speed) /**/ \
static uint8_t SWD_Transfer##speed (uint32_t request, uint32_t *data) { \
uint32_t ack; \
uint32_t bit; \
uint32_t val; \
uint32_t parity; \
\
uint32_t n; \
\
/* Packet Request */ \
parity = 0U; \
SW_WRITE_BIT(1U); /* Start Bit */ \
bit = request >> 0; \
SW_WRITE_BIT(bit); /* APnDP Bit */ \
parity += bit; \
bit = request >> 1; \
SW_WRITE_BIT(bit); /* RnW Bit */ \
parity += bit; \
bit = request >> 2; \
SW_WRITE_BIT(bit); /* A2 Bit */ \
parity += bit; \
bit = request >> 3; \
SW_WRITE_BIT(bit); /* A3 Bit */ \
parity += bit; \
SW_WRITE_BIT(parity); /* Parity Bit */ \
SW_WRITE_BIT(0U); /* Stop Bit */ \
SW_WRITE_BIT(1U); /* Park Bit */ \
\
/* Turnaround */ \
PIN_SWDIO_OUT_DISABLE(); \
for (n = DAP_Data.swd_conf.turnaround; n; n--) { \
SW_CLOCK_CYCLE(); \
} \
\
/* Acknowledge response */ \
SW_READ_BIT(bit); \
ack = bit << 0; \
SW_READ_BIT(bit); \
ack |= bit << 1; \
SW_READ_BIT(bit); \
ack |= bit << 2; \
\
if (ack == DAP_TRANSFER_OK) { /* OK response */ \
/* Data transfer */ \
if (request & DAP_TRANSFER_RnW) { \
/* Read data */ \
val = 0U; \
parity = 0U; \
for (n = 32U; n; n--) { \
SW_READ_BIT(bit); /* Read RDATA[0:31] */ \
parity += bit; \
val >>= 1; \
val |= bit << 31; \
} \
SW_READ_BIT(bit); /* Read Parity */ \
if ((parity ^ bit) & 1U) { \
ack = DAP_TRANSFER_ERROR; \
} \
if (data) { *data = val; } \
/* Turnaround */ \
for (n = DAP_Data.swd_conf.turnaround; n; n--) { \
SW_CLOCK_CYCLE(); \
} \
PIN_SWDIO_OUT_ENABLE(); \
} else { \
/* Turnaround */ \
for (n = DAP_Data.swd_conf.turnaround; n; n--) { \
SW_CLOCK_CYCLE(); \
} \
PIN_SWDIO_OUT_ENABLE(); \
/* Write data */ \
val = *data; \
parity = 0U; \
for (n = 32U; n; n--) { \
SW_WRITE_BIT(val); /* Write WDATA[0:31] */ \
parity += val; \
val >>= 1; \
} \
SW_WRITE_BIT(parity); /* Write Parity Bit */ \
} \
/* Capture Timestamp */ \
if (request & DAP_TRANSFER_TIMESTAMP) { \
DAP_Data.timestamp = TIMESTAMP_GET(); \
} \
/* Idle cycles */ \
n = DAP_Data.transfer.idle_cycles; \
if (n) { \
PIN_SWDIO_OUT(0U); \
for (; n; n--) { \
SW_CLOCK_CYCLE(); \
} \
} \
PIN_SWDIO_OUT(1U); \
return ((uint8_t)ack); \
} \
\
if ((ack == DAP_TRANSFER_WAIT) || (ack == DAP_TRANSFER_FAULT)) { \
/* WAIT or FAULT response */ \
if (DAP_Data.swd_conf.data_phase && ((request & DAP_TRANSFER_RnW) != 0U)) { \
for (n = 32U+1U; n; n--) { \
SW_CLOCK_CYCLE(); /* Dummy Read RDATA[0:31] + Parity */ \
} \
} \
/* Turnaround */ \
for (n = DAP_Data.swd_conf.turnaround; n; n--) { \
SW_CLOCK_CYCLE(); \
} \
PIN_SWDIO_OUT_ENABLE(); \
if (DAP_Data.swd_conf.data_phase && ((request & DAP_TRANSFER_RnW) == 0U)) { \
PIN_SWDIO_OUT(0U); \
for (n = 32U+1U; n; n--) { \
SW_CLOCK_CYCLE(); /* Dummy Write WDATA[0:31] + Parity */ \
} \
} \
PIN_SWDIO_OUT(1U); \
return ((uint8_t)ack); \
} \
\
/* Protocol error */ \
for (n = DAP_Data.swd_conf.turnaround + 32U + 1U; n; n--) { \
SW_CLOCK_CYCLE(); /* Back off data phase */ \
} \
PIN_SWDIO_OUT_ENABLE(); \
PIN_SWDIO_OUT(1U); \
return ((uint8_t)ack); \
}
#undef PIN_DELAY
#define PIN_DELAY() PIN_DELAY_FAST()
SWD_TransferFunction(Fast)
#undef PIN_DELAY
#define PIN_DELAY() PIN_DELAY_SLOW(DAP_Data.clock_delay)
SWD_TransferFunction(Slow)
// SWD Transfer I/O
// request: A[3:2] RnW APnDP
// data: DATA[31:0]
// return: ACK[2:0]
uint8_t SWD_Transfer(uint32_t request, uint32_t *data) {
if (DAP_Data.fast_clock) {
return SWD_TransferFast(request, data);
} else {
return SWD_TransferSlow(request, data);
}
}
#endif /* (DAP_SWD != 0) */
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Source/SW_DP.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 2,254 |
```objective-c
/*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* your_sha256_hash------
*
* $Date: 15. September 2021
* $Revision: V1.0.0
*
* Project: CMSIS-DAP Examples MCU-LINK
* Title: ser_num.h CMSIS-DAP Serial Number module for MCU-LINK
*
*your_sha256_hash-----------*/
#ifndef __SER_NUM_H__
#define __SER_NUM_H__
char *GetSerialNum (void);
#endif /* __SER_NUM_H__ */
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Examples/MCU-LINK/ser_num.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 146 |
```c
/*your_sha256_hash--------------
* MDK Middleware - Component ::USB:Device:CDC
*your_sha256_hash--------------
* Name: USBD_User_CDC_ACM_UART_0.c
* Purpose: USB Device Communication Device Class (CDC)
* Abstract Control Model (ACM) USB <-> UART Bridge User module
* Rev.: V1.0.8
*your_sha256_hash------------*/
/**
* \addtogroup usbd_cdcFunctions
*
* USBD_User_CDC_ACM_UART_0.c implements the application specific
* functionality of the CDC ACM class and is used to demonstrate a USB <-> UART
* bridge. All data received on USB is transmitted on UART and all data
* received on UART is transmitted on USB.
*
* Details of operation:
* UART -> USB:
* Initial reception on UART is started after the USB Host sets line coding
* with SetLineCoding command. Having received a full UART buffer, any
* new reception is restarted on the same buffer. Any data received on
* the UART is sent over USB using the CDC0_ACM_UART_to_USB_Thread thread.
* USB -> UART:
* While the UART transmit is not busy, data transmission on the UART is
* started in the USBD_CDC0_ACM_DataReceived callback as soon as data is
* received on the USB. Further data received on USB is transmitted on
* UART in the UART callback routine until there is no more data available.
* In this case, the next UART transmit is restarted from the
* USBD_CDC0_ACM_DataReceived callback as soon as new data is received
* on the USB.
*
* The following constants in this module affect the module functionality:
*
* - UART_PORT: specifies UART Port
* default value: 0 (=UART0)
* - UART_BUFFER_SIZE: specifies UART data Buffer Size
* default value: 512
*
* Notes:
* If the USB is slower than the UART, data can get lost. This may happen
* when USB is pausing during data reception because of the USB Host being
* too loaded with other tasks and not polling the Bulk IN Endpoint often
* enough (up to 2 seconds of gap in polling Bulk IN Endpoint may occur).
* This problem can be solved by using a large enough UART buffer to
* compensate up to a few seconds of received UART data or by using UART
* flow control.
* If the device that receives the UART data (usually a PC) is too loaded
* with other tasks it can also loose UART data. This problem can only be
* solved by using UART flow control.
*
* This file has to be adapted in case of UART flow control usage.
*/
//! [code_USBD_User_CDC_ACM]
#include <stdio.h>
#include <string.h>
#include "rl_usb.h"
#include "Driver_USART.h"
#include "DAP_config.h"
#include "DAP.h"
// UART Configuration ----------------------------------------------------------
#define UART_BUFFER_SIZE (512) // UART Buffer Size
//your_sha256_hash--------------
#define _UART_Driver_(n) Driver_USART##n
#define UART_Driver_(n) _UART_Driver_(n)
extern ARM_DRIVER_USART UART_Driver_(DAP_UART_DRIVER);
#define ptrUART (&UART_Driver_(DAP_UART_DRIVER))
// Local Variables
static uint8_t uart_rx_buf[UART_BUFFER_SIZE];
static uint8_t uart_tx_buf[UART_BUFFER_SIZE];
static volatile int32_t uart_rx_cnt = 0;
static volatile int32_t usb_tx_cnt = 0;
static void *cdc_acm_bridge_tid = 0U;
static CDC_LINE_CODING cdc_acm_line_coding = { 0U, 0U, 0U, 0U };
static uint8_t cdc_acm_active = 1U;
static osMutexId_t cdc_acm_mutex_id = NULL;
// Acquire mutex
__STATIC_INLINE void CDC_ACM_Lock (void) {
if (cdc_acm_mutex_id == NULL) {
cdc_acm_mutex_id = osMutexNew(NULL);
}
osMutexAcquire(cdc_acm_mutex_id, osWaitForever);
}
// Release mutex
__STATIC_INLINE void CDC_ACM_Unlock (void) {
osMutexRelease(cdc_acm_mutex_id);
}
// Change communication settings.
// \param[in] line_coding pointer to CDC_LINE_CODING structure.
// \return true set line coding request processed.
// \return false set line coding request not supported or not processed.
static bool CDC_ACM_SetLineCoding (const CDC_LINE_CODING *line_coding) {
uint32_t data_bits = 0U, parity = 0U, stop_bits = 0U;
int32_t status;
(void)ptrUART->Control (ARM_USART_ABORT_SEND, 0U);
(void)ptrUART->Control (ARM_USART_ABORT_RECEIVE, 0U);
(void)ptrUART->Control (ARM_USART_CONTROL_TX, 0U);
(void)ptrUART->Control (ARM_USART_CONTROL_RX, 0U);
switch (line_coding->bCharFormat) {
case 0: // 1 Stop bit
stop_bits = ARM_USART_STOP_BITS_1;
break;
case 1: // 1.5 Stop bits
stop_bits = ARM_USART_STOP_BITS_1_5;
break;
case 2: // 2 Stop bits
stop_bits = ARM_USART_STOP_BITS_2;
break;
default:
return false;
}
switch (line_coding->bParityType) {
case 0: // None
parity = ARM_USART_PARITY_NONE;
break;
case 1: // Odd
parity = ARM_USART_PARITY_ODD;
break;
case 2: // Even
parity = ARM_USART_PARITY_EVEN;
break;
default:
return false;
}
switch (line_coding->bDataBits) {
case 5:
data_bits = ARM_USART_DATA_BITS_5;
break;
case 6:
data_bits = ARM_USART_DATA_BITS_6;
break;
case 7:
data_bits = ARM_USART_DATA_BITS_7;
break;
case 8:
data_bits = ARM_USART_DATA_BITS_8;
break;
default:
return false;
}
status = ptrUART->Control(ARM_USART_MODE_ASYNCHRONOUS |
data_bits |
parity |
stop_bits ,
line_coding->dwDTERate );
if (status != ARM_DRIVER_OK) {
return false;
}
// Store requested settings to local variable
memcpy(&cdc_acm_line_coding, line_coding, sizeof(cdc_acm_line_coding));
uart_rx_cnt = 0;
usb_tx_cnt = 0;
(void)ptrUART->Control (ARM_USART_CONTROL_TX, 1U);
(void)ptrUART->Control (ARM_USART_CONTROL_RX, 1U);
(void)ptrUART->Receive (uart_rx_buf, UART_BUFFER_SIZE);
return true;
}
// Activate or Deactivate USBD COM PORT
// \param[in] cmd 0=deactivate, 1=activate
// \return 0=Ok, 0xFF=Error
uint8_t USB_COM_PORT_Activate (uint32_t cmd) {
switch (cmd) {
case 0U:
cdc_acm_active = 0U;
USBD_CDC0_ACM_Uninitialize();
break;
case 1U:
USBD_CDC0_ACM_Initialize();
CDC_ACM_Lock();
CDC_ACM_SetLineCoding(&cdc_acm_line_coding);
cdc_acm_active = 1U;
CDC_ACM_Unlock();
break;
}
return 0U;
}
// Called when UART has transmitted or received requested number of bytes.
// \param[in] event UART event
// - ARM_USART_EVENT_SEND_COMPLETE: all requested data was sent
// - ARM_USART_EVENT_RECEIVE_COMPLETE: all requested data was received
static void UART_Callback (uint32_t event) {
int32_t cnt;
if (cdc_acm_active == 0U) {
return;
}
if (event & ARM_USART_EVENT_SEND_COMPLETE) {
// USB -> UART
cnt = USBD_CDC_ACM_ReadData(0U, uart_tx_buf, UART_BUFFER_SIZE);
if (cnt > 0) {
(void)ptrUART->Send(uart_tx_buf, (uint32_t)(cnt));
}
}
if (event & ARM_USART_EVENT_RECEIVE_COMPLETE) {
// UART data received, restart new reception
uart_rx_cnt += UART_BUFFER_SIZE;
(void)ptrUART->Receive(uart_rx_buf, UART_BUFFER_SIZE);
}
}
// Thread: Sends data received on UART to USB
// \param[in] arg not used.
__NO_RETURN static void CDC0_ACM_UART_to_USB_Thread (void *arg) {
int32_t cnt, cnt_to_wrap;
(void)(arg);
for (;;) {
// UART - > USB
if (ptrUART->GetStatus().rx_busy != 0U) {
cnt = uart_rx_cnt;
cnt += (int32_t)ptrUART->GetRxCount();
cnt -= usb_tx_cnt;
if (cnt >= (UART_BUFFER_SIZE - 32)) {
// Dump old data in UART receive buffer if USB is not consuming fast enough
cnt = (UART_BUFFER_SIZE - 32);
usb_tx_cnt = uart_rx_cnt - (UART_BUFFER_SIZE - 32);
}
if (cnt > 0) {
cnt_to_wrap = (int32_t)(UART_BUFFER_SIZE - ((uint32_t)usb_tx_cnt & (UART_BUFFER_SIZE - 1)));
if (cnt > cnt_to_wrap) {
cnt = cnt_to_wrap;
}
cnt = USBD_CDC_ACM_WriteData(0U, (uart_rx_buf + ((uint32_t)usb_tx_cnt & (UART_BUFFER_SIZE - 1))), cnt);
if (cnt > 0) {
usb_tx_cnt += cnt;
}
}
}
(void)osDelay(10U);
}
}
static osRtxThread_t cdc0_acm_uart_to_usb_thread_cb_mem __SECTION(.bss.os.thread.cb);
static uint64_t cdc0_acm_uart_to_usb_thread_stack_mem[512U / 8U] __SECTION(.bss.os.thread.cdc.stack);
static const osThreadAttr_t cdc0_acm_uart_to_usb_thread_attr = {
"CDC0_ACM_UART_to_USB_Thread",
0U,
&cdc0_acm_uart_to_usb_thread_cb_mem,
sizeof(osRtxThread_t),
&cdc0_acm_uart_to_usb_thread_stack_mem[0],
sizeof(cdc0_acm_uart_to_usb_thread_stack_mem),
osPriorityNormal,
0U,
0U
};
// CDC ACM Callbacks -----------------------------------------------------------
// Called when new data was received from the USB Host.
// \param[in] len number of bytes available to read.
void USBD_CDC0_ACM_DataReceived (uint32_t len) {
int32_t cnt;
(void)(len);
if (cdc_acm_active == 0U) {
return;
}
if (ptrUART->GetStatus().tx_busy == 0U) {
// Start USB -> UART
cnt = USBD_CDC_ACM_ReadData(0U, uart_tx_buf, UART_BUFFER_SIZE);
if (cnt > 0) {
(void)ptrUART->Send(uart_tx_buf, (uint32_t)(cnt));
}
}
}
// Called during USBD_Initialize to initialize the USB CDC class instance (ACM).
void USBD_CDC0_ACM_Initialize (void) {
(void)ptrUART->Initialize (UART_Callback);
(void)ptrUART->PowerControl (ARM_POWER_FULL);
cdc_acm_bridge_tid = osThreadNew (CDC0_ACM_UART_to_USB_Thread, NULL, &cdc0_acm_uart_to_usb_thread_attr);
}
// Called during USBD_Uninitialize to de-initialize the USB CDC class instance (ACM).
void USBD_CDC0_ACM_Uninitialize (void) {
if (osThreadTerminate (cdc_acm_bridge_tid) == osOK) {
cdc_acm_bridge_tid = NULL;
}
(void)ptrUART->Control (ARM_USART_ABORT_RECEIVE, 0U);
(void)ptrUART->PowerControl (ARM_POWER_OFF);
(void)ptrUART->Uninitialize ();
}
// Called upon USB Bus Reset Event.
void USBD_CDC0_ACM_Reset (void) {
if (cdc_acm_active == 0U ) {
return;
}
(void)ptrUART->Control (ARM_USART_ABORT_SEND, 0U);
(void)ptrUART->Control (ARM_USART_ABORT_RECEIVE, 0U);
}
// Called upon USB Host request to change communication settings.
// \param[in] line_coding pointer to CDC_LINE_CODING structure.
// \return true set line coding request processed.
// \return false set line coding request not supported or not processed.
bool USBD_CDC0_ACM_SetLineCoding (const CDC_LINE_CODING *line_coding) {
bool ret = false;
CDC_ACM_Lock();
if (cdc_acm_active == 0U) {
// Store requested settings to local variable
memcpy(&cdc_acm_line_coding, line_coding, sizeof(cdc_acm_line_coding));
ret = true;
} else {
ret = CDC_ACM_SetLineCoding(line_coding);
}
CDC_ACM_Unlock();
return ret;
}
// Called upon USB Host request to retrieve communication settings.
// \param[out] line_coding pointer to CDC_LINE_CODING structure.
// \return true get line coding request processed.
// \return false get line coding request not supported or not processed.
bool USBD_CDC0_ACM_GetLineCoding (CDC_LINE_CODING *line_coding) {
// Load settings from ones stored on USBD_CDC0_ACM_SetLineCoding callback
*line_coding = cdc_acm_line_coding;
return true;
}
// Called upon USB Host request to set control line states.
// \param [in] state control line settings bitmap.
// - bit 0: DTR state
// - bit 1: RTS state
// \return true set control line state request processed.
// \return false set control line state request not supported or not processed.
bool USBD_CDC0_ACM_SetControlLineState (uint16_t state) {
// Add code for set control line state
(void)(state);
return true;
}
//! [code_USBD_User_CDC_ACM]
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Examples/MCU-LINK/USBD_User_CDC_ACM_UART_0.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 3,365 |
```c
/*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* your_sha256_hash------
*
* $Date: 15. September 2021
* $Revision: V1.0.0
*
* Project: CMSIS-DAP Examples MCU-LINK
* Title: ser_num.c CMSIS-DAP Serial Number module for MCU-LINK
*
*your_sha256_hash-----------*/
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "ser_num.h"
#include "fsl_iap_ffr.h"
// Serial Number
#define SER_NUM_PREFIX "00A1"
static char SerialNum[32];
/**
\brief Calculate 32-bit CRC (polynom: 0x04C11DB7, init value: 0xFFFFFFFF)
\param[in] data pointer to data
\param[in] len data length (in bytes)
\return CRC32 value
*/
static uint32_t crc32 (const uint8_t *data, uint32_t len) {
uint32_t crc32;
uint32_t n;
crc32 = 0xFFFFFFFFU;
while (len != 0U) {
crc32 ^= ((uint32_t)*data++) << 24U;
for (n = 8U; n; n--) {
if (crc32 & 0x80000000U) {
crc32 <<= 1U;
crc32 ^= 0x04C11DB7U;
} else {
crc32 <<= 1U;
}
}
len--;
}
return (crc32);
}
/**
\brief Get serial number string. First characters are fixed. Last eight
characters are Unique (calculated from devices's unique ID)
\return Serial number string or NULL (callculation of unique ID failed)
*/
char *GetSerialNum (void) {
flash_config_t flash_config;
uint8_t uuid_buf[16];
uint32_t uid;
char *str;
str = NULL;
if (FFR_Init(&flash_config) == kStatus_Success) {
if (FFR_GetUUID(&flash_config, uuid_buf) == kStatus_Success) {
uid = crc32(uuid_buf, 16U);
snprintf(SerialNum, sizeof(SerialNum), "%s%08X", SER_NUM_PREFIX, uid);
str = SerialNum;
}
}
return (str);
}
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Examples/MCU-LINK/ser_num.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 562 |
```objective-c
/*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* your_sha256_hash------
*
* $Date: 15. September 2021
* $Revision: V2.1.0
*
* Project: CMSIS-DAP Examples MCU-LINK
* Title: DAP_config.h CMSIS-DAP Configuration File for MCU-LINK
*
*your_sha256_hash-----------*/
#ifndef __DAP_CONFIG_H__
#define __DAP_CONFIG_H__
//**************************************************************************************************
/**
\defgroup DAP_Config_Debug_gr CMSIS-DAP Debug Unit Information
\ingroup DAP_ConfigIO_gr
@{
Provides definitions about the hardware and configuration of the Debug Unit.
This information includes:
- Definition of Cortex-M processor parameters used in CMSIS-DAP Debug Unit.
- Debug Unit Identification strings (Vendor, Product, Serial Number).
- Debug Unit communication packet size.
- Debug Access Port supported modes and settings (JTAG/SWD and SWO).
- Optional information about a connected Target Device (for Evaluation Boards).
*/
#ifdef _RTE_
#include "RTE_Components.h"
#include CMSIS_device_header
#else
#include "device.h" // Debug Unit Cortex-M Processor Header File
#endif
#include "pin_mux.h"
#include "fsl_gpio.h"
#include "ser_num.h"
/// Processor Clock of the Cortex-M MCU used in the Debug Unit.
/// This value is used to calculate the SWD/JTAG clock speed.
#define CPU_CLOCK 150000000U ///< Specifies the CPU Clock in Hz.
/// Number of processor cycles for I/O Port write operations.
/// This value is used to calculate the SWD/JTAG clock speed that is generated with I/O
/// Port write operations in the Debug Unit by a Cortex-M MCU. Most Cortex-M processors
/// require 2 processor cycles for a I/O Port Write operation. If the Debug Unit uses
/// a Cortex-M0+ processor with high-speed peripheral I/O only 1 processor cycle might be
/// required.
#define IO_PORT_WRITE_CYCLES 2U ///< I/O Cycles: 2=default, 1=Cortex-M0+ fast I/0.
/// Indicate that Serial Wire Debug (SWD) communication mode is available at the Debug Access Port.
/// This information is returned by the command \ref DAP_Info as part of <b>Capabilities</b>.
#define DAP_SWD 1 ///< SWD Mode: 1 = available, 0 = not available.
/// Indicate that JTAG communication mode is available at the Debug Port.
/// This information is returned by the command \ref DAP_Info as part of <b>Capabilities</b>.
#define DAP_JTAG 1 ///< JTAG Mode: 1 = available, 0 = not available.
/// Configure maximum number of JTAG devices on the scan chain connected to the Debug Access Port.
/// This setting impacts the RAM requirements of the Debug Unit. Valid range is 1 .. 255.
#define DAP_JTAG_DEV_CNT 8U ///< Maximum number of JTAG devices on scan chain.
/// Default communication mode on the Debug Access Port.
/// Used for the command \ref DAP_Connect when Port Default mode is selected.
#define DAP_DEFAULT_PORT 1U ///< Default JTAG/SWJ Port Mode: 1 = SWD, 2 = JTAG.
/// Default communication speed on the Debug Access Port for SWD and JTAG mode.
/// Used to initialize the default SWD/JTAG clock frequency.
/// The command \ref DAP_SWJ_Clock can be used to overwrite this default setting.
#define DAP_DEFAULT_SWJ_CLOCK 1000000U ///< Default SWD/JTAG clock frequency in Hz.
/// Maximum Package Size for Command and Response data.
/// This configuration settings is used to optimize the communication performance with the
/// debugger and depends on the USB peripheral. Typical vales are 64 for Full-speed USB HID or WinUSB,
/// 1024 for High-speed USB HID and 512 for High-speed USB WinUSB.
#define DAP_PACKET_SIZE 512U ///< Specifies Packet Size in bytes.
/// Maximum Package Buffers for Command and Response data.
/// This configuration settings is used to optimize the communication performance with the
/// debugger and depends on the USB peripheral. For devices with limited RAM or USB buffer the
/// setting can be reduced (valid range is 1 .. 255).
#define DAP_PACKET_COUNT 8U ///< Specifies number of packets buffered.
/// Indicate that UART Serial Wire Output (SWO) trace is available.
/// This information is returned by the command \ref DAP_Info as part of <b>Capabilities</b>.
#define SWO_UART 1 ///< SWO UART: 1 = available, 0 = not available.
/// USART Driver instance number for the UART SWO.
#define SWO_UART_DRIVER 3 ///< USART Driver instance number (Driver_USART#).
/// Maximum SWO UART Baudrate.
#define SWO_UART_MAX_BAUDRATE 9000000U ///< SWO UART Maximum Baudrate in Hz.
/// Indicate that Manchester Serial Wire Output (SWO) trace is available.
/// This information is returned by the command \ref DAP_Info as part of <b>Capabilities</b>.
#define SWO_MANCHESTER 0 ///< SWO Manchester: 1 = available, 0 = not available.
/// SWO Trace Buffer Size.
#define SWO_BUFFER_SIZE 8192U ///< SWO Trace Buffer Size in bytes (must be 2^n).
/// SWO Streaming Trace.
#define SWO_STREAM 1 ///< SWO Streaming Trace: 1 = available, 0 = not available.
/// Clock frequency of the Test Domain Timer. Timer value is returned with \ref TIMESTAMP_GET.
#define TIMESTAMP_CLOCK 150000000U ///< Timestamp clock in Hz (0 = timestamps not supported).
/// Indicate that UART Communication Port is available.
/// This information is returned by the command \ref DAP_Info as part of <b>Capabilities</b>.
#define DAP_UART 1 ///< DAP UART: 1 = available, 0 = not available.
/// USART Driver instance number for the UART Communication Port.
#define DAP_UART_DRIVER 0 ///< USART Driver instance number (Driver_USART#).
/// UART Receive Buffer Size.
#define DAP_UART_RX_BUFFER_SIZE 1024U ///< Uart Receive Buffer Size in bytes (must be 2^n).
/// UART Transmit Buffer Size.
#define DAP_UART_TX_BUFFER_SIZE 1024U ///< Uart Transmit Buffer Size in bytes (must be 2^n).
/// Indicate that UART Communication via USB COM Port is available.
/// This information is returned by the command \ref DAP_Info as part of <b>Capabilities</b>.
#define DAP_UART_USB_COM_PORT 1 ///< USB COM Port: 1 = available, 0 = not available.
/// Debug Unit is connected to fixed Target Device.
/// The Debug Unit may be part of an evaluation board and always connected to a fixed
/// known device. In this case a Device Vendor, Device Name, Board Vendor and Board Name strings
/// are stored and may be used by the debugger or IDE to configure device parameters.
#define TARGET_FIXED 0 ///< Target: 1 = known, 0 = unknown;
#define TARGET_DEVICE_VENDOR "NXP" ///< String indicating the Silicon Vendor
#define TARGET_DEVICE_NAME "Cortex-M" ///< String indicating the Target Device
#define TARGET_BOARD_VENDOR "NXP" ///< String indicating the Board Vendor
#define TARGET_BOARD_NAME "NXP board" ///< String indicating the Board Name
#if TARGET_FIXED != 0
#include <string.h>
static const char TargetDeviceVendor [] = TARGET_DEVICE_VENDOR;
static const char TargetDeviceName [] = TARGET_DEVICE_NAME;
static const char TargetBoardVendor [] = TARGET_BOARD_VENDOR;
static const char TargetBoardName [] = TARGET_BOARD_NAME;
#endif
/** Get Vendor Name string.
\param str Pointer to buffer to store the string (max 60 characters).
\return String length (including terminating NULL character) or 0 (no string).
*/
__STATIC_INLINE uint8_t DAP_GetVendorString (char *str) {
(void)str;
return (0U);
}
/** Get Product Name string.
\param str Pointer to buffer to store the string (max 60 characters).
\return String length (including terminating NULL character) or 0 (no string).
*/
__STATIC_INLINE uint8_t DAP_GetProductString (char *str) {
(void)str;
return (0U);
}
/** Get Serial Number string.
\param str Pointer to buffer to store the string (max 60 characters).
\return String length (including terminating NULL character) or 0 (no string).
*/
__STATIC_INLINE uint8_t DAP_GetSerNumString (char *str) {
uint8_t len = 0U;
char *ser_num;
ser_num = GetSerialNum();
if (ser_num != NULL) {
strcpy(str, ser_num);
len = (uint8_t)(strlen(ser_num) + 1U);
}
return (len);
}
/** Get Target Device Vendor string.
\param str Pointer to buffer to store the string (max 60 characters).
\return String length (including terminating NULL character) or 0 (no string).
*/
__STATIC_INLINE uint8_t DAP_GetTargetDeviceVendorString (char *str) {
#if TARGET_FIXED != 0
uint8_t len;
strcpy(str, TargetDeviceVendor);
len = (uint8_t)(strlen(TargetDeviceVendor) + 1U);
return (len);
#else
(void)str;
return (0U);
#endif
}
/** Get Target Device Name string.
\param str Pointer to buffer to store the string (max 60 characters).
\return String length (including terminating NULL character) or 0 (no string).
*/
__STATIC_INLINE uint8_t DAP_GetTargetDeviceNameString (char *str) {
#if TARGET_FIXED != 0
uint8_t len;
strcpy(str, TargetDeviceName);
len = (uint8_t)(strlen(TargetDeviceName) + 1U);
return (len);
#else
(void)str;
return (0U);
#endif
}
/** Get Target Board Vendor string.
\param str Pointer to buffer to store the string (max 60 characters).
\return String length (including terminating NULL character) or 0 (no string).
*/
__STATIC_INLINE uint8_t DAP_GetTargetBoardVendorString (char *str) {
#if TARGET_FIXED != 0
uint8_t len;
strcpy(str, TargetBoardVendor);
len = (uint8_t)(strlen(TargetBoardVendor) + 1U);
return (len);
#else
(void)str;
return (0U);
#endif
}
/** Get Target Board Name string.
\param str Pointer to buffer to store the string (max 60 characters).
\return String length (including terminating NULL character) or 0 (no string).
*/
__STATIC_INLINE uint8_t DAP_GetTargetBoardNameString (char *str) {
#if TARGET_FIXED != 0
uint8_t len;
strcpy(str, TargetBoardName);
len = (uint8_t)(strlen(TargetBoardName) + 1U);
return (len);
#else
(void)str;
return (0U);
#endif
}
/** Get Product Firmware Version string.
\param str Pointer to buffer to store the string (max 60 characters).
\return String length (including terminating NULL character) or 0 (no string).
*/
__STATIC_INLINE uint8_t DAP_GetProductFirmwareVersionString (char *str) {
(void)str;
return (0U);
}
///@}
// Debug Port I/O Pins
//SWO/TDO
#define PIN_SWO_TDO_PORT (0U)
#define PIN_SWO_TDO_PIN (3U)
//**************************************************************************************************
/**
\defgroup DAP_Config_PortIO_gr CMSIS-DAP Hardware I/O Pin Access
\ingroup DAP_ConfigIO_gr
@{
Standard I/O Pins of the CMSIS-DAP Hardware Debug Port support standard JTAG mode
and Serial Wire Debug (SWD) mode. In SWD mode only 2 pins are required to implement the debug
interface of a device. The following I/O Pins are provided:
JTAG I/O Pin | SWD I/O Pin | CMSIS-DAP Hardware pin mode
---------------------------- | -------------------- | ---------------------------------------------
TCK: Test Clock | SWCLK: Clock | Output Push/Pull
TMS: Test Mode Select | SWDIO: Data I/O | Output Push/Pull; Input (for receiving data)
TDI: Test Data Input | | Output Push/Pull
TDO: Test Data Output | | Input
nTRST: Test Reset (optional) | | Output Open Drain with pull-up resistor
nRESET: Device Reset | nRESET: Device Reset | Output Open Drain with pull-up resistor
DAP Hardware I/O Pin Access Functions
-------------------------------------
The various I/O Pins are accessed by functions that implement the Read, Write, Set, or Clear to
these I/O Pins.
For the SWDIO I/O Pin there are additional functions that are called in SWD I/O mode only.
This functions are provided to achieve faster I/O that is possible with some advanced GPIO
peripherals that can independently write/read a single I/O pin without affecting any other pins
of the same I/O port. The following SWDIO I/O Pin functions are provided:
- \ref PIN_SWDIO_OUT_ENABLE to enable the output mode from the DAP hardware.
- \ref PIN_SWDIO_OUT_DISABLE to enable the input mode to the DAP hardware.
- \ref PIN_SWDIO_IN to read from the SWDIO I/O pin with utmost possible speed.
- \ref PIN_SWDIO_OUT to write to the SWDIO I/O pin with utmost possible speed.
*/
// Configure DAP I/O pins ------------------------------
/** Setup JTAG I/O pins: TCK, TMS, TDI, TDO, nTRST, and nRESET.
Configures the DAP Hardware I/O pins for JTAG mode:
- TCK, TMS, TDI, nTRST, nRESET to output mode and set to high level.
- TDO to input mode.
*/
__STATIC_INLINE void PORT_JTAG_SETUP (void) {
// TCK
DBGIF_TCK_SWCLK_GPIO->SET[DBGIF_TCK_SWCLK_PORT] = (1U << DBGIF_TCK_SWCLK_PIN);
DBGIF_TCK_SWCLK_GPIO->DIRSET[DBGIF_TCK_SWCLK_PORT] = (1U << DBGIF_TCK_SWCLK_PIN);
// TDI
DBGIF_TDI_GPIO->SET[DBGIF_TDI_PORT] = (1U << DBGIF_TDI_PIN);
DBGIF_TDI_GPIO->DIRSET[DBGIF_TDI_PORT] = (1U << DBGIF_TDI_PIN);
// TMS
DBGIF_TMS_SWDIO_GPIO->SET[DBGIF_TMS_SWDIO_PORT] = (1U << DBGIF_TMS_SWDIO_PIN);
DBGIF_TMS_SWDIO_GPIO->DIRSET[DBGIF_TMS_SWDIO_PORT] = (1U << DBGIF_TMS_SWDIO_PIN);
DBGIF_TMS_SWDIO_TXEN_GPIO->SET[DBGIF_TMS_SWDIO_TXEN_PORT] = (1U << DBGIF_TMS_SWDIO_TXEN_PIN);
// nRESET
DBGIF_RESET_GPIO->SET[DBGIF_RESET_PORT] = (1U << DBGIF_RESET_PIN);
DBGIF_RESET_GPIO->DIRSET[DBGIF_RESET_PORT] = (1U << DBGIF_RESET_PIN);
DBGIF_RESET_TXEN_GPIO->SET[DBGIF_RESET_TXEN_PORT] = (1U << DBGIF_RESET_TXEN_PIN);
// TDO
GPIO->DIRCLR[PIN_SWO_TDO_PORT] = (1U << PIN_SWO_TDO_PIN);
}
/** Setup SWD I/O pins: SWCLK, SWDIO, and nRESET.
Configures the DAP Hardware I/O pins for Serial Wire Debug (SWD) mode:
- SWCLK, SWDIO, nRESET to output mode and set to default high level.
- TDI, nTRST to HighZ mode (pins are unused in SWD mode).
*/
__STATIC_INLINE void PORT_SWD_SETUP (void) {
// SWCLK
DBGIF_TCK_SWCLK_GPIO->SET[DBGIF_TCK_SWCLK_PORT] = (1U << DBGIF_TCK_SWCLK_PIN);
DBGIF_TCK_SWCLK_GPIO->DIRSET[DBGIF_TCK_SWCLK_PORT] = (1U << DBGIF_TCK_SWCLK_PIN);
// SWDIO
DBGIF_TMS_SWDIO_GPIO->SET[DBGIF_TMS_SWDIO_PORT] = (1U << DBGIF_TMS_SWDIO_PIN);
DBGIF_TMS_SWDIO_GPIO->DIRSET[DBGIF_TMS_SWDIO_PORT] = (1U << DBGIF_TMS_SWDIO_PIN);
DBGIF_TMS_SWDIO_TXEN_GPIO->SET[DBGIF_TMS_SWDIO_TXEN_PORT] = (1U << DBGIF_TMS_SWDIO_TXEN_PIN);
// nRESET
DBGIF_RESET_GPIO->SET[DBGIF_RESET_PORT] = (1U << DBGIF_RESET_PIN);
DBGIF_RESET_GPIO->DIRSET[DBGIF_RESET_PORT] = (1U << DBGIF_RESET_PIN);
DBGIF_RESET_TXEN_GPIO->SET[DBGIF_RESET_TXEN_PORT] = (1U << DBGIF_RESET_TXEN_PIN);
// TDI
DBGIF_TDI_GPIO->DIRCLR[DBGIF_TDI_PORT] = (1U << DBGIF_TDI_PIN);
}
/** Disable JTAG/SWD I/O Pins.
Disables the DAP Hardware I/O pins which configures:
- TCK/SWCLK, TMS/SWDIO, TDI, TDO, nTRST, nRESET to High-Z mode.
*/
__STATIC_INLINE void PORT_OFF (void) {
// TCK/SWCLK
DBGIF_TCK_SWCLK_GPIO->DIRCLR[DBGIF_TCK_SWCLK_PORT] = (1U << DBGIF_TCK_SWCLK_PIN);
// TMS/SWDIO
DBGIF_TMS_SWDIO_TXEN_GPIO->CLR[DBGIF_TMS_SWDIO_TXEN_PORT] = (1U << DBGIF_TMS_SWDIO_TXEN_PIN);
DBGIF_TMS_SWDIO_GPIO->DIRCLR[DBGIF_TMS_SWDIO_PORT] = (1U << DBGIF_TMS_SWDIO_PIN);
// nRESET
DBGIF_RESET_TXEN_GPIO->CLR[DBGIF_RESET_TXEN_PORT] = (1U << DBGIF_RESET_TXEN_PIN);
DBGIF_RESET_GPIO->DIRCLR[DBGIF_RESET_PORT] = (1U << DBGIF_RESET_PIN);
// TDI
DBGIF_TDI_GPIO->DIRCLR[DBGIF_TDI_PORT] = (1U << DBGIF_TDI_PIN);
// TDO
GPIO->DIRCLR[PIN_SWO_TDO_PORT] = (1U << PIN_SWO_TDO_PIN);
}
// SWCLK/TCK I/O pin -------------------------------------
/** SWCLK/TCK I/O pin: Get Input.
\return Current status of the SWCLK/TCK DAP hardware I/O pin.
*/
__STATIC_FORCEINLINE uint32_t PIN_SWCLK_TCK_IN (void) {
return ((DBGIF_TCK_SWCLK_GPIO->PIN[DBGIF_TCK_SWCLK_PORT] >> DBGIF_TCK_SWCLK_PIN) & 1U);
}
/** SWCLK/TCK I/O pin: Set Output to High.
Set the SWCLK/TCK DAP hardware I/O pin to high level.
*/
__STATIC_FORCEINLINE void PIN_SWCLK_TCK_SET (void) {
DBGIF_TCK_SWCLK_GPIO->SET[DBGIF_TCK_SWCLK_PORT] = (1U << DBGIF_TCK_SWCLK_PIN);
}
/** SWCLK/TCK I/O pin: Set Output to Low.
Set the SWCLK/TCK DAP hardware I/O pin to low level.
*/
__STATIC_FORCEINLINE void PIN_SWCLK_TCK_CLR (void) {
DBGIF_TCK_SWCLK_GPIO->CLR[DBGIF_TCK_SWCLK_PORT] = (1U << DBGIF_TCK_SWCLK_PIN);
}
// SWDIO/TMS Pin I/O --------------------------------------
/** SWDIO/TMS I/O pin: Get Input.
\return Current status of the SWDIO/TMS DAP hardware I/O pin.
*/
__STATIC_FORCEINLINE uint32_t PIN_SWDIO_TMS_IN (void) {
return ((DBGIF_TMS_SWDIO_GPIO->PIN[DBGIF_TMS_SWDIO_PORT] >> DBGIF_TMS_SWDIO_PIN) & 1U);
}
/** SWDIO/TMS I/O pin: Set Output to High.
Set the SWDIO/TMS DAP hardware I/O pin to high level.
*/
__STATIC_FORCEINLINE void PIN_SWDIO_TMS_SET (void) {
DBGIF_TMS_SWDIO_GPIO->SET[DBGIF_TMS_SWDIO_PORT] = (1U << DBGIF_TMS_SWDIO_PIN);
}
/** SWDIO/TMS I/O pin: Set Output to Low.
Set the SWDIO/TMS DAP hardware I/O pin to low level.
*/
__STATIC_FORCEINLINE void PIN_SWDIO_TMS_CLR (void) {
DBGIF_TMS_SWDIO_GPIO->CLR[DBGIF_TMS_SWDIO_PORT] = (1U << DBGIF_TMS_SWDIO_PIN);
}
/** SWDIO I/O pin: Get Input (used in SWD mode only).
\return Current status of the SWDIO DAP hardware I/O pin.
*/
__STATIC_FORCEINLINE uint32_t PIN_SWDIO_IN (void) {
return (DBGIF_TMS_SWDIO_GPIO->B[DBGIF_TMS_SWDIO_PORT][DBGIF_TMS_SWDIO_PIN]);
}
/** SWDIO I/O pin: Set Output (used in SWD mode only).
\param bit Output value for the SWDIO DAP hardware I/O pin.
*/
__STATIC_FORCEINLINE void PIN_SWDIO_OUT (uint32_t bit) {
DBGIF_TMS_SWDIO_GPIO->B[DBGIF_TMS_SWDIO_PORT][DBGIF_TMS_SWDIO_PIN] = bit;
}
/** SWDIO I/O pin: Switch to Output mode (used in SWD mode only).
Configure the SWDIO DAP hardware I/O pin to output mode. This function is
called prior \ref PIN_SWDIO_OUT function calls.
*/
__STATIC_FORCEINLINE void PIN_SWDIO_OUT_ENABLE (void) {
DBGIF_TMS_SWDIO_GPIO->DIRSET[DBGIF_TMS_SWDIO_PORT] = (1U << DBGIF_TMS_SWDIO_PIN);
DBGIF_TMS_SWDIO_TXEN_GPIO->SET[DBGIF_TMS_SWDIO_TXEN_PORT] = (1U << DBGIF_TMS_SWDIO_TXEN_PIN);
}
/** SWDIO I/O pin: Switch to Input mode (used in SWD mode only).
Configure the SWDIO DAP hardware I/O pin to input mode. This function is
called prior \ref PIN_SWDIO_IN function calls.
*/
__STATIC_FORCEINLINE void PIN_SWDIO_OUT_DISABLE (void) {
DBGIF_TMS_SWDIO_TXEN_GPIO->CLR[DBGIF_TMS_SWDIO_TXEN_PORT] = (1U << DBGIF_TMS_SWDIO_TXEN_PIN);
DBGIF_TMS_SWDIO_GPIO->DIRCLR[DBGIF_TMS_SWDIO_PORT] = (1U << DBGIF_TMS_SWDIO_PIN);
}
// TDI Pin I/O ---------------------------------------------
/** TDI I/O pin: Get Input.
\return Current status of the TDI DAP hardware I/O pin.
*/
__STATIC_FORCEINLINE uint32_t PIN_TDI_IN (void) {
return (DBGIF_TDI_GPIO->B[DBGIF_TDI_PORT][DBGIF_TDI_PIN]);
}
/** TDI I/O pin: Set Output.
\param bit Output value for the TDI DAP hardware I/O pin.
*/
__STATIC_FORCEINLINE void PIN_TDI_OUT (uint32_t bit) {
DBGIF_TDI_GPIO->B[DBGIF_TDI_PORT][DBGIF_TDI_PIN] = bit;
}
// TDO Pin I/O ---------------------------------------------
/** TDO I/O pin: Get Input.
\return Current status of the TDO DAP hardware I/O pin.
*/
__STATIC_FORCEINLINE uint32_t PIN_TDO_IN (void) {
return (GPIO->B[PIN_SWO_TDO_PORT][PIN_SWO_TDO_PIN]);
}
// nTRST Pin I/O -------------------------------------------
/** nTRST I/O pin: Get Input.
\return Current status of the nTRST DAP hardware I/O pin.
*/
__STATIC_FORCEINLINE uint32_t PIN_nTRST_IN (void) {
return (0U); // Not available
}
/** nTRST I/O pin: Set Output.
\param bit JTAG TRST Test Reset pin status:
- 0: issue a JTAG TRST Test Reset.
- 1: release JTAG TRST Test Reset.
*/
__STATIC_FORCEINLINE void PIN_nTRST_OUT (uint32_t bit) {
(void) bit;
// Not available
}
// nRESET Pin I/O------------------------------------------
/** nRESET I/O pin: Get Input.
\return Current status of the nRESET DAP hardware I/O pin.
*/
__STATIC_FORCEINLINE uint32_t PIN_nRESET_IN (void) {
return ((DBGIF_RESET_GPIO->PIN[DBGIF_RESET_PORT] >> DBGIF_RESET_PIN) & 1U);
}
/** nRESET I/O pin: Set Output.
\param bit target device hardware reset pin status:
- 0: issue a device hardware reset.
- 1: release device hardware reset.
*/
__STATIC_FORCEINLINE void PIN_nRESET_OUT (uint32_t bit) {
if (bit) {
DBGIF_RESET_GPIO->SET[DBGIF_RESET_PORT] = (1U << DBGIF_RESET_PIN);
DBGIF_RESET_TXEN_GPIO->CLR[DBGIF_RESET_TXEN_PORT] = (1U << DBGIF_RESET_TXEN_PIN);
DBGIF_RESET_GPIO->DIRCLR[DBGIF_RESET_PORT] = (1U << DBGIF_RESET_PIN);
} else {
DBGIF_RESET_GPIO->CLR[DBGIF_RESET_PORT] = (1U << DBGIF_RESET_PIN);
DBGIF_RESET_GPIO->DIRSET[DBGIF_RESET_PORT] = (1U << DBGIF_RESET_PIN);
DBGIF_RESET_TXEN_GPIO->SET[DBGIF_RESET_TXEN_PORT] = (1U << DBGIF_RESET_TXEN_PIN);
}
}
///@}
//**************************************************************************************************
/**
\defgroup DAP_Config_LEDs_gr CMSIS-DAP Hardware Status LEDs
\ingroup DAP_ConfigIO_gr
@{
CMSIS-DAP Hardware may provide LEDs that indicate the status of the CMSIS-DAP Debug Unit.
It is recommended to provide the following LEDs for status indication:
- Connect LED: is active when the DAP hardware is connected to a debugger.
- Running LED: is active when the debugger has put the target device into running state.
*/
/** Debug Unit: Set status of Connected LED.
\param bit status of the Connect LED.
- 1: Connect LED ON: debugger is connected to CMSIS-DAP Debug Unit.
- 0: Connect LED OFF: debugger is not connected to CMSIS-DAP Debug Unit.
*/
__STATIC_INLINE void LED_CONNECTED_OUT (uint32_t bit) {
if (bit) {
LED1_GPIO->CLR[LED1_PORT] = (1U << LED1_PIN);
} else {
LED1_GPIO->SET[LED1_PORT] = (1U << LED1_PIN);
}
}
/** Debug Unit: Set status Target Running LED.
\param bit status of the Target Running LED.
- 1: Target Running LED ON: program execution in target started.
- 0: Target Running LED OFF: program execution in target stopped.
*/
__STATIC_INLINE void LED_RUNNING_OUT (uint32_t bit) {
(void) bit;
// Not available
}
///@}
//**************************************************************************************************
/**
\defgroup DAP_Config_Timestamp_gr CMSIS-DAP Timestamp
\ingroup DAP_ConfigIO_gr
@{
Access function for Test Domain Timer.
The value of the Test Domain Timer in the Debug Unit is returned by the function \ref TIMESTAMP_GET. By
default, the DWT timer is used. The frequency of this timer is configured with \ref TIMESTAMP_CLOCK.
*/
/** Get timestamp of Test Domain Timer.
\return Current timestamp value.
*/
__STATIC_INLINE uint32_t TIMESTAMP_GET (void) {
return (DWT->CYCCNT);
}
///@}
//**************************************************************************************************
/**
\defgroup DAP_Config_Initialization_gr CMSIS-DAP Initialization
\ingroup DAP_ConfigIO_gr
@{
CMSIS-DAP Hardware I/O and LED Pins are initialized with the function \ref DAP_SETUP.
*/
/** Setup of the Debug Unit I/O pins and LEDs (called when Debug Unit is initialized).
This function performs the initialization of the CMSIS-DAP Hardware I/O Pins and the
Status LEDs. In detail the operation of Hardware I/O and LED pins are enabled and set:
- I/O clock system enabled.
- all I/O pins: input buffer enabled, output pins are set to HighZ mode.
- for nTRST, nRESET a weak pull-up (if available) is enabled.
- LED output pins are enabled and LEDs are turned off.
*/
__STATIC_INLINE void DAP_SETUP (void) {
BOARD_InitBootPins();
}
/** Reset Target Device with custom specific I/O pin or command sequence.
This function allows the optional implementation of a device specific reset sequence.
It is called when the command \ref DAP_ResetTarget and is for example required
when a device needs a time-critical unlock sequence that enables the debug port.
\return 0 = no device specific reset sequence is implemented.\n
1 = a device specific reset sequence is implemented.
*/
__STATIC_INLINE uint8_t RESET_TARGET (void) {
return (0U); // change to '1' when a device reset sequence is implemented
}
///@}
#endif /* __DAP_CONFIG_H__ */
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Examples/MCU-LINK/DAP_config.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 6,585 |
```c
/*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* your_sha256_hash------
*
* $Date: 15. September 2021
* $Revision: V2.0.0
*
* Project: CMSIS-DAP Examples MCU-LINK
* Title: main.c CMSIS-DAP Main module for MCU-LINK
*
*your_sha256_hash-----------*/
#include "cmsis_os2.h"
#include "osObjects.h"
#include "rl_usb.h"
#include "DAP_config.h"
#include "DAP.h"
#include "clock_config.h"
#include "pin_mux.h"
#include "fsl_dma.h"
// Callbacks for USART0 Driver
uint32_t USART0_GetFreq (void) { return CLOCK_GetFlexCommClkFreq(0); }
void USART0_InitPins (void) { /* Done in BOARD_InitBootPins function */ }
void USART0_DeinitPins (void) { /* Not implemented */ }
// Callbacks for USART3 Driver
uint32_t USART3_GetFreq (void) { return CLOCK_GetFlexCommClkFreq(3); }
void USART3_InitPins (void) { /* Done in BOARD_InitBootPins function */ }
void USART3_DeinitPins (void) { /* Not implemented */ }
// Application Main program
__NO_RETURN void app_main (void *argument) {
(void)argument;
BOARD_InitBootPins();
BOARD_InitBootClocks();
DMA_Init(DMA0);
DAP_Setup(); // DAP Setup
USBD_Initialize(0U); // USB Device Initialization
char *ser_num;
ser_num = GetSerialNum();
if (ser_num != NULL) {
USBD_SetSerialNumber(0U, ser_num); // Update Serial Number
}
USBD_Connect(0U); // USB Device Connect
while (!USBD_Configured(0U)); // Wait for USB Device to configure
LED_CONNECTED_OUT(1U); // Turn on Debugger Connected LED
LED_RUNNING_OUT(1U); // Turn on Target Running LED
Delayms(500U); // Wait for 500ms
LED_RUNNING_OUT(0U); // Turn off Target Running LED
LED_CONNECTED_OUT(0U); // Turn off Debugger Connected LED
// Create DAP Thread
DAP_ThreadId = osThreadNew(DAP_Thread, NULL, &DAP_ThreadAttr);
// Create SWO Thread
SWO_ThreadId = osThreadNew(SWO_Thread, NULL, &SWO_ThreadAttr);
osDelay(osWaitForever);
for (;;) {}
}
int main (void) {
SystemCoreClockUpdate();
osKernelInitialize(); // Initialize CMSIS-RTOS
osThreadNew(app_main, NULL, NULL); // Create application main thread
if (osKernelGetState() == osKernelReady) {
osKernelStart(); // Start thread execution
}
for (;;) {}
}
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Examples/MCU-LINK/main.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 686 |
```objective-c
/*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* your_sha256_hash------
*
* $Date: 15. September 2021
* $Revision: V2.0.0
*
* Project: CMSIS-DAP Examples MCU-LINK
* Title: osObjects.h CMSIS-DAP RTOS2 Objects for MCU-LINK
*
*your_sha256_hash-----------*/
#ifndef __osObjects_h__
#define __osObjects_h__
#include "cmsis_os2.h"
#ifdef osObjectsExternal
extern osThreadId_t DAP_ThreadId;
extern osThreadId_t SWO_ThreadId;
#else
static const osThreadAttr_t DAP_ThreadAttr = {
.priority = osPriorityNormal
};
static const osThreadAttr_t SWO_ThreadAttr = {
.priority = osPriorityAboveNormal
};
extern osThreadId_t DAP_ThreadId;
osThreadId_t DAP_ThreadId;
extern osThreadId_t SWO_ThreadId;
osThreadId_t SWO_ThreadId;
#endif
extern void DAP_Thread (void *argument);
extern void SWO_Thread (void *argument);
extern void app_main (void *argument);
#endif /* __osObjects_h__ */
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Examples/MCU-LINK/osObjects.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 283 |
```c
/* your_sha256_hash-------------
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from
* the use of this software. Permission is granted to anyone to use this
* software for any purpose, including commercial applications, and to alter
* it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software in
* a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
*
* $Date: 28. June 2021
* $Revision: V1.0
*
* Driver: Driver_USBD1
* Project: USB1 High-Speed Device Driver for NXP LPC55xxx
* your_sha256_hash----------
* Use the following configuration settings in the middleware component
* to connect to this driver.
*
* Configuration Setting Value
* --------------------- -----
* Connect to hardware via Driver_USBD# = 1
* your_sha256_hash----------
* Defines used for driver configuration (at compile time):
*
* USBD1_MAX_ENDPOINT_NUM: defines maximum number of IN/OUT Endpoint pairs
* that driver will support with Control Endpoint 0
* not included, this value impacts driver memory
* requirements
* - default value: 5
* - maximum value: 5
*
* USBD1_OUT_EP0_BUF_SZ: defines Out Endpoint0 buffer size (in Bytes)
* USBD1_IN_EP0_BUF_SZ: defines In Endpoint0 buffer size (in Bytes)
* USBD1_OUT_EP1_BUF_SZ: defines Out Endpoint1 buffer size (in Bytes)
* USBD1_IN_EP1_BUF_SZ: defines In Endpoint1 buffer size (in Bytes)
* USBD1_OUT_EP2_BUF_SZ: defines Out Endpoint2 buffer size (in Bytes)
* USBD1_IN_EP2_BUF_SZ: defines In Endpoint2 buffer size (in Bytes)
* USBD1_OUT_EP3_BUF_SZ: defines Out Endpoint3 buffer size (in Bytes)
* USBD1_IN_EP3_BUF_SZ: defines In Endpoint3 buffer size (in Bytes)
* USBD1_OUT_EP4_BUF_SZ: defines Out Endpoint4 buffer size (in Bytes)
* USBD1_IN_EP4_BUF_SZ: defines In Endpoint4 buffer size (in Bytes)
* USBD1_OUT_EP5_BUF_SZ: defines Out Endpoint5 buffer size (in Bytes)
* USBD1_IN_EP5_BUF_SZ: defines In Endpoint5 buffer size (in Bytes)
* your_sha256_hash---------- */
/* History:
* Version 1.0
* Initial release
*/
#include <stdint.h>
#include <string.h>
#include "Driver_USBD.h"
#include "RTE_Device.h"
#include "RTE_Components.h"
#include "fsl_common.h"
#include "fsl_power.h"
#include "fsl_clock.h"
#include "fsl_reset.h"
#include "USB_LPC55xxx.h"
// Endpoint buffer must be 64Byte aligned
#define ALIGN_64(n) (n == 0U ? (0U) : (64U * (((n - 1U) / 64U) + 1U)))
#ifndef USBD1_MAX_ENDPOINT_NUM
#define USBD1_MAX_ENDPOINT_NUM (5U)
#endif
#if (USBD1_MAX_ENDPOINT_NUM > 5)
#error Too many Endpoints, maximum IN/OUT Endpoint pairs that this driver supports is 5 !!!
#endif
// Endpoint Bufer size definitions
#ifndef USBD1_OUT_EP0_BUF_SZ
#define USBD1_OUT_EP0_BUF_SZ (64U)
#endif
#ifndef USBD1_IN_EP0_BUF_SZ
#define USBD1_IN_EP0_BUF_SZ (64U)
#endif
#define USBD1_OUT_EP0_BUF_SZ_64 (ALIGN_64(USBD1_OUT_EP0_BUF_SZ))
#define USBD1_IN_EP0_BUF_SZ_64 (ALIGN_64(USBD1_IN_EP0_BUF_SZ))
#if (USBD1_MAX_ENDPOINT_NUM > 0)
#ifndef USBD1_OUT_EP1_BUF_SZ
#define USBD1_OUT_EP1_BUF_SZ (1024U)
#endif
#ifndef USBD1_IN_EP1_BUF_SZ
#define USBD1_IN_EP1_BUF_SZ (1024U)
#endif
#else
#define USBD1_OUT_EP1_BUF_SZ (0U)
#define USBD1_IN_EP1_BUF_SZ (0U)
#endif
#define USBD1_OUT_EP1_BUF_SZ_64 (ALIGN_64(USBD1_OUT_EP1_BUF_SZ))
#define USBD1_IN_EP1_BUF_SZ_64 (ALIGN_64(USBD1_IN_EP1_BUF_SZ))
#if (USBD1_MAX_ENDPOINT_NUM > 1)
#ifndef USBD1_OUT_EP2_BUF_SZ
#define USBD1_OUT_EP2_BUF_SZ (1024U)
#endif
#ifndef USBD1_IN_EP2_BUF_SZ
#define USBD1_IN_EP2_BUF_SZ (1024U)
#endif
#else
#define USBD1_OUT_EP2_BUF_SZ (0U)
#define USBD1_IN_EP2_BUF_SZ (0U)
#endif
#define USBD1_OUT_EP2_BUF_SZ_64 (ALIGN_64(USBD1_OUT_EP2_BUF_SZ))
#define USBD1_IN_EP2_BUF_SZ_64 (ALIGN_64(USBD1_IN_EP2_BUF_SZ))
#if (USBD1_MAX_ENDPOINT_NUM > 2)
#ifndef USBD1_OUT_EP3_BUF_SZ
#define USBD1_OUT_EP3_BUF_SZ (1024U)
#endif
#ifndef USBD1_IN_EP3_BUF_SZ
#define USBD1_IN_EP3_BUF_SZ (1024U)
#endif
#else
#define USBD1_OUT_EP3_BUF_SZ (0U)
#define USBD1_IN_EP3_BUF_SZ (0U)
#endif
#define USBD1_OUT_EP3_BUF_SZ_64 (ALIGN_64(USBD1_OUT_EP3_BUF_SZ))
#define USBD1_IN_EP3_BUF_SZ_64 (ALIGN_64(USBD1_IN_EP3_BUF_SZ))
#if (USBD1_MAX_ENDPOINT_NUM > 3)
#ifndef USBD1_OUT_EP4_BUF_SZ
#define USBD1_OUT_EP4_BUF_SZ (1024U)
#endif
#ifndef USBD1_IN_EP4_BUF_SZ
#define USBD1_IN_EP4_BUF_SZ (1024U)
#endif
#else
#define USBD1_OUT_EP4_BUF_SZ (0U)
#define USBD1_IN_EP4_BUF_SZ (0U)
#endif
#define USBD1_OUT_EP4_BUF_SZ_64 (ALIGN_64(USBD1_OUT_EP4_BUF_SZ))
#define USBD1_IN_EP4_BUF_SZ_64 (ALIGN_64(USBD1_IN_EP4_BUF_SZ))
#if (USBD1_MAX_ENDPOINT_NUM > 4)
#ifndef USBD1_OUT_EP5_BUF_SZ
#define USBD1_OUT_EP5_BUF_SZ (1024U)
#endif
#ifndef USBD1_IN_EP5_BUF_SZ
#define USBD1_IN_EP5_BUF_SZ (1024U)
#endif
#else
#define USBD1_OUT_EP5_BUF_SZ (0U)
#define USBD1_IN_EP5_BUF_SZ (0U)
#endif
#define USBD1_OUT_EP5_BUF_SZ_64 (ALIGN_64(USBD1_OUT_EP5_BUF_SZ))
#define USBD1_IN_EP5_BUF_SZ_64 (ALIGN_64(USBD1_IN_EP5_BUF_SZ))
#define USBD1_OUT_EP0_BUF_OFFSET (0U)
#define USBD1_IN_EP0_BUF_OFFSET (USBD1_OUT_EP0_BUF_SZ_64)
#define USBD1_OUT_EP1_BUF_OFFSET (USBD1_IN_EP0_BUF_OFFSET + USBD1_IN_EP0_BUF_SZ_64)
#define USBD1_IN_EP1_BUF_OFFSET (USBD1_OUT_EP1_BUF_OFFSET + USBD1_OUT_EP1_BUF_SZ_64)
#define USBD1_OUT_EP2_BUF_OFFSET (USBD1_IN_EP1_BUF_OFFSET + USBD1_IN_EP1_BUF_SZ_64)
#define USBD1_IN_EP2_BUF_OFFSET (USBD1_OUT_EP2_BUF_OFFSET + USBD1_OUT_EP2_BUF_SZ_64)
#define USBD1_OUT_EP3_BUF_OFFSET (USBD1_IN_EP2_BUF_OFFSET + USBD1_IN_EP2_BUF_SZ_64)
#define USBD1_IN_EP3_BUF_OFFSET (USBD1_OUT_EP3_BUF_OFFSET + USBD1_OUT_EP3_BUF_SZ_64)
#define USBD1_OUT_EP4_BUF_OFFSET (USBD1_IN_EP3_BUF_OFFSET + USBD1_IN_EP3_BUF_SZ_64)
#define USBD1_IN_EP4_BUF_OFFSET (USBD1_OUT_EP4_BUF_OFFSET + USBD1_OUT_EP4_BUF_SZ_64)
#define USBD1_OUT_EP5_BUF_OFFSET (USBD1_IN_EP4_BUF_OFFSET + USBD1_IN_EP4_BUF_SZ_64)
#define USBD1_IN_EP5_BUF_OFFSET (USBD1_OUT_EP5_BUF_OFFSET + USBD1_OUT_EP5_BUF_SZ_64)
#define USBD_EP_BUFFER_SZ (USBD1_OUT_EP0_BUF_SZ_64 + USBD1_IN_EP0_BUF_SZ_64 + \
USBD1_OUT_EP1_BUF_SZ_64 + USBD1_IN_EP1_BUF_SZ_64 + \
USBD1_OUT_EP2_BUF_SZ_64 + USBD1_IN_EP2_BUF_SZ_64 + \
USBD1_OUT_EP3_BUF_SZ_64 + USBD1_IN_EP3_BUF_SZ_64 + \
USBD1_OUT_EP4_BUF_SZ_64 + USBD1_IN_EP4_BUF_SZ_64 + \
USBD1_OUT_EP5_BUF_SZ_64 + USBD1_IN_EP5_BUF_SZ_64 )
#if (USBD_EP_BUFFER_SZ > 0x3C00U)
#error "Endpoint buffers do not fit into RAMx!"
#endif
#define EP_NUM(ep_addr) (ep_addr & ARM_USB_ENDPOINT_NUMBER_MASK)
#define EP_IDX(ep_addr) ((ep_addr & 0x80U) ? ((EP_NUM(ep_addr)) * 2U + 1U) : (ep_addr * 2U))
#define CMD_IDX(ep_addr) ((ep_addr & 0x80U) ? ((EP_NUM(ep_addr)) * 4U + 2U) : (ep_addr * 4U))
// Resource allocation
static uint8_t ep_buf[USBD_EP_BUFFER_SZ] __attribute__((section(".bss.ARM.__at_0x40100000")));
static EP_CMD ep_cmd[(USBD1_MAX_ENDPOINT_NUM + 1) * 4] __attribute__((section(".bss.ARM.__at_0x40103C00")));
static EP_TRANSFER ep_transfer[(USBD1_MAX_ENDPOINT_NUM + 1) * 2];
// Global variables
static ARM_USBD_STATE usbd_state;
static uint8_t usbd_flags;
static uint8_t setup_packet[8]; // Setup packet data
static volatile uint8_t setup_received; // Setup packet received
static ARM_USBD_SignalDeviceEvent_t SignalDeviceEvent;
static ARM_USBD_SignalEndpointEvent_t SignalEndpointEvent;
static const EP endpoint[] = {
// Endpoint 0
{ &(ep_cmd[0]), &(ep_buf[USBD1_OUT_EP0_BUF_OFFSET]), &(ep_transfer[0]), USBD1_OUT_EP0_BUF_OFFSET, },
{ &(ep_cmd[2]), &(ep_buf[USBD1_IN_EP0_BUF_OFFSET]), &(ep_transfer[1]), USBD1_IN_EP0_BUF_OFFSET, },
#if (USBD1_MAX_ENDPOINT_NUM > 0U)
// Endpoint 1
{ &(ep_cmd[4]), &(ep_buf[USBD1_OUT_EP1_BUF_OFFSET]), &(ep_transfer[2]), USBD1_OUT_EP1_BUF_OFFSET, },
{ &(ep_cmd[6]), &(ep_buf[USBD1_IN_EP1_BUF_OFFSET]), &(ep_transfer[3]), USBD1_IN_EP1_BUF_OFFSET, },
#endif
#if (USBD1_MAX_ENDPOINT_NUM > 1U)
// Endpoint 2
{ &(ep_cmd[8]), &(ep_buf[USBD1_OUT_EP2_BUF_OFFSET]), &(ep_transfer[4]), USBD1_OUT_EP2_BUF_OFFSET, },
{ &(ep_cmd[10]), &(ep_buf[USBD1_IN_EP2_BUF_OFFSET]), &(ep_transfer[5]), USBD1_IN_EP2_BUF_OFFSET, },
#endif
#if (USBD1_MAX_ENDPOINT_NUM > 2U)
// Endpoint 3
{ &(ep_cmd[12]), &(ep_buf[USBD1_OUT_EP3_BUF_OFFSET]), &(ep_transfer[6]), USBD1_OUT_EP3_BUF_OFFSET, },
{ &(ep_cmd[14]), &(ep_buf[USBD1_IN_EP3_BUF_OFFSET]), &(ep_transfer[7]), USBD1_IN_EP3_BUF_OFFSET, },
#endif
#if (USBD1_MAX_ENDPOINT_NUM > 3U)
// Endpoint 4
{ &(ep_cmd[16]), &(ep_buf[USBD1_OUT_EP4_BUF_OFFSET]), &(ep_transfer[8]), USBD1_OUT_EP4_BUF_OFFSET, },
{ &(ep_cmd[18]), &(ep_buf[USBD1_IN_EP4_BUF_OFFSET]), &(ep_transfer[9]), USBD1_IN_EP4_BUF_OFFSET, },
#endif
#if (USBD1_MAX_ENDPOINT_NUM > 4U)
// Endpoint 5
{ &(ep_cmd[16]), &(ep_buf[USBD1_OUT_EP5_BUF_OFFSET]), &(ep_transfer[8]), USBD1_OUT_EP5_BUF_OFFSET, },
{ &(ep_cmd[18]), &(ep_buf[USBD1_IN_EP5_BUF_OFFSET]), &(ep_transfer[9]), USBD1_IN_EP5_BUF_OFFSET, },
#endif
};
// USBD Driver *****************************************************************
#define ARM_USBD_DRV_VERSION ARM_DRIVER_VERSION_MAJOR_MINOR(1,0)
// Driver Version
static const ARM_DRIVER_VERSION usbd_driver_version = { ARM_USBD_API_VERSION, ARM_USBD_DRV_VERSION };
// Driver Capabilities
static const ARM_USBD_CAPABILITIES usbd_driver_capabilities = {
#if (USBD_VBUS_DETECT == 1)
1U, // VBUS Detection
1U, // Event VBUS On
1U, // Event VBUS Off
#else
0U, // VBUS Detection
0U, // Event VBUS On
0U // Event VBUS Off
#endif
};
/**
\fn void USBD_Reset (void)
\brief Reset USB Endpoint settings and variables.
*/
static void USBD_Reset (void) {
// Clear USB Endpoint command/status list
memset((void *)ep_cmd, 0, sizeof(ep_cmd));
memset((void *)&usbd_state, 0, sizeof(usbd_state));
}
// USBD Driver functions
/**
\fn ARM_DRIVER_VERSION USBD_GetVersion (void)
\brief Get driver version.
\return \ref ARM_DRIVER_VERSION
*/
static ARM_DRIVER_VERSION USBD_GetVersion (void) { return usbd_driver_version; }
/**
\fn ARM_USBD_CAPABILITIES USBD_GetCapabilities (void)
\brief Get driver capabilities.
\return \ref ARM_USBD_CAPABILITIES
*/
static ARM_USBD_CAPABILITIES USBD_GetCapabilities (void) { return usbd_driver_capabilities; }
/**
\fn int32_t USBD_Initialize (ARM_USBD_SignalDeviceEvent_t cb_device_event,
ARM_USBD_SignalEndpointEvent_t cb_endpoint_event)
\brief Initialize USB Device Interface.
\param[in] cb_device_event Pointer to \ref ARM_USBD_SignalDeviceEvent
\param[in] cb_endpoint_event Pointer to \ref ARM_USBD_SignalEndpointEvent
\return \ref execution_status
*/
static int32_t USBD_Initialize (ARM_USBD_SignalDeviceEvent_t cb_device_event,
ARM_USBD_SignalEndpointEvent_t cb_endpoint_event) {
if ((usbd_flags & USBD_DRIVER_FLAG_INITIALIZED) != 0U) { return ARM_DRIVER_OK; }
SignalDeviceEvent = cb_device_event;
SignalEndpointEvent = cb_endpoint_event;
usbd_flags = USBD_DRIVER_FLAG_INITIALIZED;
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_Uninitialize (void)
\brief De-initialize USB Device Interface.
\return \ref execution_status
*/
static int32_t USBD_Uninitialize (void) {
usbd_flags &= ~USBD_DRIVER_FLAG_INITIALIZED;
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_PowerControl (ARM_POWER_STATE state)
\brief Control USB Device Interface Power.
\param[in] state Power state
\return \ref execution_status
*/
static int32_t USBD_PowerControl (ARM_POWER_STATE state) {
switch (state) {
case ARM_POWER_OFF:
NVIC_DisableIRQ (USB1_IRQn); // Disable interrupt
NVIC_ClearPendingIRQ (USB1_IRQn); // Clear pending interrupt
usbd_flags &= ~USBD_DRIVER_FLAG_POWERED; // Clear powered flag
RESET_PeripheralReset(kUSB1D_RST_SHIFT_RSTn); // Reset USB1 Device controller
RESET_PeripheralReset(kUSB1_RST_SHIFT_RSTn); // Reset USB1 PHY
RESET_PeripheralReset(kUSB1RAM_RST_SHIFT_RSTn); // Reset USB1 RAM controller
// Disable USB IP clock
SYSCON->AHBCLKCTRLSET[2] &= ~SYSCON_AHBCLKCTRL2_USB1_RAM(1);
SYSCON->AHBCLKCTRLSET[2] &= ~SYSCON_AHBCLKCTRL2_USB1_DEV(1);
SYSCON->AHBCLKCTRLSET[2] &= ~SYSCON_AHBCLKCTRL2_USB1_PHY(1);
// Clear USB Endpoint command/status list
memset((void *)ep_cmd, 0, sizeof(ep_cmd));
// Clear Endpoint transfer structure
memset((void *)ep_transfer, 0, sizeof(ep_transfer));
break;
case ARM_POWER_FULL:
if ((usbd_flags & USBD_DRIVER_FLAG_INITIALIZED) == 0U) { return ARM_DRIVER_ERROR; }
if ((usbd_flags & USBD_DRIVER_FLAG_POWERED) != 0U) { return ARM_DRIVER_OK; }
// Enable USB IP clock
CLOCK_EnableUsbhs0PhyPllClock(kCLOCK_UsbPhySrcExt, 16000000U);
CLOCK_EnableUsbhs0DeviceClock(kCLOCK_UsbSrcUnused, 0U);
// Enable device operation (through USB1 Host PORTMODE register)
CLOCK_EnableClock(kCLOCK_Usbh1);
USBHSH->PORTMODE = USBHSH_PORTMODE_SW_PDCOM_MASK;
USBHSH->PORTMODE |= USBHSH_PORTMODE_DEV_ENABLE_MASK;
CLOCK_DisableClock(kCLOCK_Usbh1);
// Setup PHY
USBPHY->PWD = 0U;
USBPHY->CTRL_SET = USBPHY_CTRL_SET_ENAUTOCLR_CLKGATE_MASK;
USBPHY->CTRL_SET = USBPHY_CTRL_SET_ENAUTOCLR_PHY_PWD_MASK;
// Clear USB RAM
memset((void *)FSL_FEATURE_USBHSD_USB_RAM_BASE_ADDRESS, 0, FSL_FEATURE_USBHSD_USB_RAM);
// Reset variables and endpoint settings
USBD_Reset ();
// Set Endpoint list start address
USBHSD->EPLISTSTART = (uint32_t)ep_cmd;
// Set USB Data buffer start address
USBHSD->DATABUFSTART = (uint32_t)ep_buf;
// Enable device status interrupt
USBHSD->INTEN = USB_INTSTAT_DEV_INT_MASK;
usbd_flags |= USBD_DRIVER_FLAG_POWERED;
// Enable USB interrupt
NVIC_EnableIRQ (USB1_IRQn);
break;
default:
return ARM_DRIVER_ERROR_UNSUPPORTED;
}
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_DeviceConnect (void)
\brief Connect USB Device.
\return \ref execution_status
*/
static int32_t USBD_DeviceConnect (void) {
if ((usbd_flags & USBD_DRIVER_FLAG_POWERED) == 0U) { return ARM_DRIVER_ERROR; }
// Attach Device
USBHSD->DEVCMDSTAT |= USB_DEVCMDSTAT_DCON_MASK;
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_DeviceDisconnect (void)
\brief Disconnect USB Device.
\return \ref execution_status
*/
static int32_t USBD_DeviceDisconnect (void) {
if ((usbd_flags & USBD_DRIVER_FLAG_POWERED) == 0U) { return ARM_DRIVER_ERROR; }
// Detach Device
USBHSD->DEVCMDSTAT &= ~USB_DEVCMDSTAT_DCON_MASK;
return ARM_DRIVER_OK;
}
/**
\fn ARM_USBD_STATE USBD_DeviceGetState (void)
\brief Get current USB Device State.
\return Device State \ref ARM_USBD_STATE
*/
static ARM_USBD_STATE USBD_DeviceGetState (void) {
ARM_USBD_STATE dev_state = { 0U, 0U, 0U };
if ((usbd_flags & USBD_DRIVER_FLAG_POWERED) == 0U) { return dev_state; }
return usbd_state;
}
/**
\fn int32_t USBD_DeviceRemoteWakeup (void)
\brief Trigger USB Remote Wakeup.
\return \ref execution_status
*/
static int32_t USBD_DeviceRemoteWakeup (void) {
if ((usbd_flags & USBD_DRIVER_FLAG_POWERED) == 0U) { return ARM_DRIVER_ERROR; }
// Force remote wakeup
USBHSD->DEVCMDSTAT &= ~USB_DEVCMDSTAT_DSUS_MASK;
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_DeviceSetAddress (uint8_t dev_addr)
\brief Set USB Device Address.
\param[in] dev_addr Device Address
\return \ref execution_status
*/
static int32_t USBD_DeviceSetAddress (uint8_t dev_addr) {
if ((usbd_flags & USBD_DRIVER_FLAG_POWERED) == 0U) { return ARM_DRIVER_ERROR; }
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_ReadSetupPacket (uint8_t *setup)
\brief Read setup packet received over Control Endpoint.
\param[out] setup Pointer to buffer for setup packet
\return \ref execution_status
*/
static int32_t USBD_ReadSetupPacket (uint8_t *setup) {
if ((usbd_flags & USBD_DRIVER_FLAG_POWERED) == 0U) { return ARM_DRIVER_ERROR; }
if (setup_received == 0U) { return ARM_DRIVER_ERROR; }
setup_received = 0U;
memcpy(setup, setup_packet, 8);
if (setup_received != 0U) { // If new setup packet was received while this was being read
return ARM_DRIVER_ERROR;
}
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_EndpointConfigure (uint8_t ep_addr,
uint8_t ep_type,
uint16_t ep_max_packet_size)
\brief Configure USB Endpoint.
\param[in] ep_addr Endpoint Address
- ep_addr.0..3: Address
- ep_addr.7: Direction
\param[in] ep_type Endpoint Type (ARM_USB_ENDPOINT_xxx)
\param[in] ep_max_packet_size Endpoint Maximum Packet Size
\return \ref execution_status
*/
static int32_t USBD_EndpointConfigure (uint8_t ep_addr,
uint8_t ep_type,
uint16_t ep_max_packet_size) {
uint8_t ep_num, ep_idx;
EP const * ep;
volatile uint32_t DBG1 = 0;
volatile uint32_t DBG2 = 0;
volatile uint32_t DBG3 = 0;
volatile uint32_t DBG4 = 0;
volatile uint32_t DBG5 = ep_addr;
volatile uint32_t DBG6 = ep_type;
volatile uint32_t DBG7 = ep_max_packet_size;
ep_num = EP_NUM(ep_addr);
ep_idx = EP_IDX(ep_addr);
ep = &endpoint[ep_idx];
if (ep_num > USBD1_MAX_ENDPOINT_NUM) {
DBG1++;
return ARM_DRIVER_ERROR;
}
if ((usbd_flags & USBD_DRIVER_FLAG_POWERED) == 0U) {
DBG2++;
return ARM_DRIVER_ERROR;
}
if (ep->cmd->active == 1U) {
// Endpoint is "owned" by hardware
DBG3++;
return ARM_DRIVER_ERROR_BUSY;
}
if (ep_max_packet_size > ((ep+1)->buf_offset - ep->buf_offset)) {
// Configured Endpoint buffer size is too small
DBG4++;
return ARM_DRIVER_ERROR;
}
// Clear Endpoint command/status
memset((void *)ep->cmd, 0, sizeof(EP_CMD) * 2U);
// Clear Endpoint transfer structure
memset((void *)ep->transfer, 0, sizeof(EP_TRANSFER));
ep_transfer[ep_idx].max_packet_sz = ep_max_packet_size & ARM_USB_ENDPOINT_MAX_PACKET_SIZE_MASK;
ep->cmd->buff_addr_offset = ep->buf_offset >> 6;
if (ep_num != 0U) {
ep->cmd->ep_disabled = 1U;
// Reset data toggle
ep->cmd->ep_type_periodic = 0U;
ep->cmd->toggle_value = 0U;
ep->cmd->toggle_reset = 1U;
switch (ep_type) {
case ARM_USB_ENDPOINT_CONTROL:
break;
case ARM_USB_ENDPOINT_ISOCHRONOUS:
ep->cmd->toggle_value = 0U;
ep->cmd->ep_type_periodic = 1U;
break;
case ARM_USB_ENDPOINT_BULK:
ep->cmd->toggle_value = 0U;
ep->cmd->ep_type_periodic = 0U;
break;
case ARM_USB_ENDPOINT_INTERRUPT:
ep->cmd->toggle_value = 1U;
ep->cmd->ep_type_periodic = 1U;
break;
default: // Unknown endpoint type
return ARM_DRIVER_ERROR;
}
ep->cmd->ep_disabled = 0U;
/* Double-buffering not configured/used */
ep->cmd[1].buff_addr_offset = ep->buf_offset >> 6;
ep->cmd[1].ep_disabled = 1U;
}
// Clear Endpoint Interrupt
USBHSD->INTSTAT = USB_INT_EP(ep_idx);
// Enable endpoint interrupt
USBHSD->INTEN |= USB_INT_EP(ep_idx);
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_EndpointUnconfigure (uint8_t ep_addr)
\brief Unconfigure USB Endpoint.
\param[in] ep_addr Endpoint Address
- ep_addr.0..3: Address
- ep_addr.7: Direction
\return \ref execution_status
*/
static int32_t USBD_EndpointUnconfigure (uint8_t ep_addr) {
uint8_t ep_num, ep_idx;
EP const * ep;
ep_num = EP_NUM(ep_addr);
ep_idx = EP_IDX(ep_addr);
ep = &endpoint[ep_idx];
if (ep_num > USBD1_MAX_ENDPOINT_NUM) { return ARM_DRIVER_ERROR; }
if ((usbd_flags & USBD_DRIVER_FLAG_POWERED) == 0U) { return ARM_DRIVER_ERROR; }
if (ep->cmd->active == 1U) {
// Endpoint is "owned" by hardware
return ARM_DRIVER_ERROR_BUSY;
}
// Disable endpoint interrupt
USBHSD->INTEN &= ~USB_INT_EP(ep_idx);
if (ep->cmd->active) {
USBHSD->EPSKIP |= (1U << ep_idx);
while (USBHSD->EPSKIP & (1U << ep_idx));
}
// Clear Endpoint command/status
memset((void *)ep->cmd, 0, sizeof(EP_CMD) * 2U);
ep->cmd->ep_disabled = 1U;
// Clear Endpoint Interrupt
USBHSD->INTSTAT = USB_INT_EP(ep_idx);
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_EndpointStall (uint8_t ep_addr, bool stall)
\brief Set/Clear Stall for USB Endpoint.
\param[in] ep_addr Endpoint Address
- ep_addr.0..3: Address
- ep_addr.7: Direction
\param[in] stall Operation
- \b false Clear
- \b true Set
\return \ref execution_status
*/
static int32_t USBD_EndpointStall (uint8_t ep_addr, bool stall) {
uint8_t ep_num;
EP const * ep;
ep_num = EP_NUM(ep_addr);
ep = &endpoint[EP_IDX(ep_addr)];
if (ep_num > USBD1_MAX_ENDPOINT_NUM) { return ARM_DRIVER_ERROR; }
if ((usbd_flags & USBD_DRIVER_FLAG_POWERED) == 0U) { return ARM_DRIVER_ERROR; }
if (ep->cmd->active == 1U) {
// Endpoint is "owned" by hardware
return ARM_DRIVER_ERROR_BUSY;
}
if (stall != 0U) {
// Set Endpoint stall
ep->cmd->stall = 1U;
} else {
ep->cmd->toggle_value = 0U;
ep->cmd->toggle_reset = 1U;
// Clear Stall
ep->cmd->stall = 0U;
}
return ARM_DRIVER_OK;
}
/**
\fn int32_t USBD_EndpointTransfer (uint8_t ep_addr, uint8_t *data, uint32_t num)
\brief Read data from or Write data to USB Endpoint.
\param[in] ep_addr Endpoint Address
- ep_addr.0..3: Address
- ep_addr.7: Direction
\param[out] data Pointer to buffer for data to read or with data to write
\param[in] num Number of data bytes to transfer
\return \ref execution_status
*/
static int32_t USBD_EndpointTransfer (uint8_t ep_addr, uint8_t *data, uint32_t num) {
uint8_t ep_num, ep_idx;
EP const * ep;
ep_num = EP_NUM(ep_addr);
ep_idx = EP_IDX(ep_addr);
ep = &endpoint[ep_idx];
if (ep_num > USBD1_MAX_ENDPOINT_NUM) { return ARM_DRIVER_ERROR; }
if ((usbd_flags & USBD_DRIVER_FLAG_POWERED) == 0U) { return ARM_DRIVER_ERROR; }
if (ep->cmd->active == 1U) {
// Endpoint is "owned" by hardware
return ARM_DRIVER_ERROR_BUSY;
}
ep->transfer->num = num;
ep->transfer->buf = data;
ep->transfer->num_transferred_total = 0U;
if (num > ep->transfer->max_packet_sz) { num = ep->transfer->max_packet_sz; }
if (ep_addr & ARM_USB_ENDPOINT_DIRECTION_MASK) {
// Copy data into IN Endpoint buffer
memcpy (ep->buf, ep->transfer->buf, num);
}
ep->cmd->buff_addr_offset = ep->buf_offset >> 6;
ep->transfer->num_transferring = num;
// Set number of bytes to send/receive
ep->cmd->NBytes = num;
// Activate endpoint
ep->cmd->active |= 1U;
return ARM_DRIVER_OK;
}
/**
\fn uint32_t USBD_EndpointTransferGetResult (uint8_t ep_addr)
\brief Get result of USB Endpoint transfer.
\param[in] ep_addr Endpoint Address
- ep_addr.0..3: Address
- ep_addr.7: Direction
\return number of successfully transferred data bytes
*/
static uint32_t USBD_EndpointTransferGetResult (uint8_t ep_addr) {
if (EP_NUM(ep_addr) > USBD1_MAX_ENDPOINT_NUM) { return 0U; }
return (ep_transfer[EP_IDX(ep_addr)].num_transferred_total);
}
/**
\fn int32_t USBD_EndpointTransferAbort (uint8_t ep_addr)
\brief Abort current USB Endpoint transfer.
\param[in] ep_addr Endpoint Address
- ep_addr.0..3: Address
- ep_addr.7: Direction
\return \ref execution_status
*/
static int32_t USBD_EndpointTransferAbort (uint8_t ep_addr) {
uint8_t ep_num, ep_idx;
EP const * ep;
ep_num = EP_NUM(ep_addr);
ep_idx = EP_IDX(ep_addr);
ep = &endpoint[ep_idx];
if (ep_num > USBD1_MAX_ENDPOINT_NUM) { return ARM_DRIVER_ERROR; }
if ((usbd_flags & USBD_DRIVER_FLAG_POWERED) == 0U) { return ARM_DRIVER_ERROR; }
// Disable endpoint interrupt
USBHSD->INTEN &= ~USB_INT_EP(ep_idx);
if (ep->cmd->active == 1U) {
USBHSD->EPSKIP |= (1U << EP_IDX(ep_addr));
while (USBHSD->EPSKIP & (1U << EP_IDX(ep_addr)));
ep->cmd->active = 0U;
}
// Clear transfer info
ep->transfer->num = 0U;
ep->transfer->num_transferred_total = 0U;
ep->transfer->num_transferring = 0U;
// Clear Endpoint Interrupt
USBHSD->INTSTAT = USB_INT_EP(ep_idx);
// Enable endpoint interrupt
USBHSD->INTEN |= USB_INT_EP(ep_idx);
return ARM_DRIVER_OK;
}
/**
\fn uint16_t USBD_GetFrameNumber (void)
\brief Get current USB Frame Number.
\return Frame Number
*/
static uint16_t USBD_GetFrameNumber (void) {
if ((usbd_flags & USBD_DRIVER_FLAG_POWERED) == 0U) { return 0; }
return ((USBHSD->INFO & USB_INFO_FRAME_NR_MASK) >> USB_INFO_FRAME_NR_SHIFT);
}
/**
\fn void USB1_IRQHandler (void)
\brief USB1 Device Interrupt Routine (IRQ).
*/
void USB1_IRQHandler (void) {
uint32_t num, ep_idx, intstat, cmdstat, dev_evt = 0U;
uint16_t val;
EP const * ep;
intstat = USBHSD->INTSTAT & USBHSD->INTEN;
cmdstat = USBHSD->DEVCMDSTAT;
// Clear interrupt flags
USBHSD->INTSTAT = intstat;
// Device Status interrupt
if (intstat & USB_INTSTAT_DEV_INT_MASK) {
// Reset
if (cmdstat & USB_DEVCMDSTAT_DRES_C_MASK) {
USBD_Reset ();
usbd_state.active = 1U;
usbd_state.speed = ARM_USB_SPEED_FULL;
USBHSD->DEVCMDSTAT |= USB_DEVCMDSTAT_DRES_C_MASK | USB_DEVCMDSTAT_DEV_EN_MASK;
SignalDeviceEvent(ARM_USBD_EVENT_RESET);
if (((USBHSD->DEVCMDSTAT & USBHSD_DEVCMDSTAT_Speed_MASK) >> USBHSD_DEVCMDSTAT_Speed_SHIFT) == 2U) {
SignalDeviceEvent(ARM_USBD_EVENT_HIGH_SPEED);
}
}
// Suspend
if (cmdstat & USB_DEVCMDSTAT_DSUS_MASK) {
usbd_state.active = 0U;
USBHSD->DEVCMDSTAT |= USB_DEVCMDSTAT_DSUS_MASK;
SignalDeviceEvent(ARM_USBD_EVENT_SUSPEND);
}
#if (USBD_VBUS_DETECT == 1)
// Disconnect
if (cmdstat & USB_DEVCMDSTAT_DCON_C) {
usbd_state.active = 0U;
usbd_state.vbus = 0U;
LPC_USB->DEVCMDSTAT |= USB_DEVCMDSTAT_DCON_C;
SignalDeviceEvent(ARM_USBD_EVENT_VBUS_OFF);
}
// VBUS De-bounced
if (cmdstat & USB_DEVCMDSTAT_VBUS_DEBOUNCED) {
usbd_state.vbus = 1U;
SignalDeviceEvent(ARM_USBD_EVENT_VBUS_ON);
}
#endif
}
// Endpoint interrupt
if (intstat & USB_INT_EP_MSK) {
for (ep_idx = 0; ep_idx <= USBD1_MAX_ENDPOINT_NUM * 2U; ep_idx += 2U) {
if (intstat & (USB_INT_EP(ep_idx))) {
// Clear Interrupt status
USBHSD->INTSTAT = (1 << ep_idx);
// Setup Packet
if ((ep_idx == 0U) && ((cmdstat & USB_DEVCMDSTAT_SETUP_MASK) != 0U)) {
ep_cmd[0].stall = 0U;
ep_cmd[1].stall = 0U;
ep_cmd[2].stall = 0U;
ep_cmd[3].stall = 0U;
USBHSD->DEVCMDSTAT |= USB_DEVCMDSTAT_SETUP_MASK;
memcpy(setup_packet, ep_buf, 8);
// Analyze Setup packet for SetAddress
val = setup_packet[0] | (setup_packet[1] << 8);
if (val == 0x0500U) {
val = (setup_packet[2] | (setup_packet[3] << 8)) & USB_DEVCMDSTAT_DEV_ADDR_MASK;
// Set device address
USBHSD->DEVCMDSTAT = (USBHSD->DEVCMDSTAT & ~USB_DEVCMDSTAT_DEV_ADDR_MASK) |
USB_DEVCMDSTAT_DEV_ADDR(val) | USB_DEVCMDSTAT_DEV_EN_MASK;
}
setup_received = 1U;
if (SignalEndpointEvent != NULL) {
SignalEndpointEvent(0U, ARM_USBD_EVENT_SETUP);
}
} else {
// OUT Packet
ep = &endpoint[ep_idx];
num = ep->transfer->num_transferring - ep->cmd->NBytes;
// Copy EP data
memcpy (ep->transfer->buf, ep->buf, num);
ep->transfer->buf += num;
ep->transfer->num_transferred_total += num;
// Check if all OUT data received:
// - data terminated with ZLP or short packet or
// - all required data received
if ((ep->transfer->num_transferred_total == ep->transfer->num) ||
(num == 0U) || (num != ep->transfer->max_packet_sz)) {
if (SignalEndpointEvent != NULL) {
SignalEndpointEvent(ep_idx / 2U, ARM_USBD_EVENT_OUT);
}
} else {
// Remaining data to transfer
num = ep->transfer->num - ep->transfer->num_transferred_total;
if (num > ep->transfer->max_packet_sz) { num = ep->transfer->max_packet_sz; }
ep->transfer->num_transferring = num;
ep->cmd->NBytes = num;
ep->cmd->buff_addr_offset = ep->buf_offset >> 6;
// Activate EP to receive next packet
ep->cmd->active = 1U;
}
}
}
}
// IN Packet
for (ep_idx = 1; ep_idx <= USBD1_MAX_ENDPOINT_NUM * 2U; ep_idx += 2U) {
if (intstat & (USB_INT_EP(ep_idx))) {
// Clear Interrupt status
USBHSD->INTSTAT = (1 << ep_idx);
ep = &endpoint[ep_idx];
ep->transfer->buf += ep->transfer->num_transferring;
ep->transfer->num_transferred_total += ep->transfer->num_transferring;
if (ep->transfer->num_transferred_total == ep->transfer->num) {
// All data has been transfered
if (SignalEndpointEvent != NULL) {
SignalEndpointEvent(0x80 | (ep_idx / 2), ARM_USBD_EVENT_IN);
}
} else {
// Still data to transfer
num = ep->transfer->num - ep->transfer->num_transferred_total;
if (num > ep->transfer->max_packet_sz) {
// Remaining data bigger than max packet
num = ep->transfer->max_packet_sz;
}
ep->transfer->num_transferring = num;
// Copy data into IN Endpoint buffer
memcpy (ep->buf, ep->transfer->buf, num);
ep->cmd->buff_addr_offset = ep->buf_offset >> 6;
// Set number of bytes to send
ep->cmd->NBytes = num;
// Activate EP to send next packet
ep->cmd->active = 1U;
}
}
}
}
}
ARM_DRIVER_USBD Driver_USBD1 = {
USBD_GetVersion,
USBD_GetCapabilities,
USBD_Initialize,
USBD_Uninitialize,
USBD_PowerControl,
USBD_DeviceConnect,
USBD_DeviceDisconnect,
USBD_DeviceGetState,
USBD_DeviceRemoteWakeup,
USBD_DeviceSetAddress,
USBD_ReadSetupPacket,
USBD_EndpointConfigure,
USBD_EndpointUnconfigure,
USBD_EndpointStall,
USBD_EndpointTransfer,
USBD_EndpointTransferGetResult,
USBD_EndpointTransferAbort,
USBD_GetFrameNumber
};
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Examples/MCU-LINK/USBD1_LPC55xxx.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 9,365 |
```objective-c
/* your_sha256_hash-------------
*
* This software is provided 'as-is', without any express or implied warranty.
* In no event will the authors be held liable for any damages arising from
* the use of this software. Permission is granted to anyone to use this
* software for any purpose, including commercial applications, and to alter
* it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software in
* a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
*
* $Date: 28. June 2021
* $Revision: V1.0
*
* Project: USB Driver Definitions for NXP LPC55xxx
* your_sha256_hash---------- */
#ifndef __USB_LPC55XXX_H
#define __USB_LPC55XXX_H
#include <stdint.h>
// USB Device Endpoint Interrupt definitions
#define USB_INT_EP_MSK (0x0FFFU)
#define USB_INT_EP(ep_idx) ((1U << (ep_idx)) & USB_INT_EP_MSK)
// USB Driver State Flags
// Device State Flags
#define USBD_DRIVER_FLAG_INITIALIZED (1U )
#define USBD_DRIVER_FLAG_POWERED (1U << 1 )
// Transfer information structure
typedef struct {
uint32_t max_packet_sz;
uint32_t num;
uint32_t num_transferred_total;
uint32_t num_transferring;
uint8_t *buf;
} EP_TRANSFER;
// Endpoint command/status
typedef struct {
uint32_t buff_addr_offset : 11;
uint32_t NBytes : 15;
uint32_t ep_type_periodic : 1;
uint32_t toggle_value : 1;
uint32_t toggle_reset : 1;
uint32_t stall : 1;
uint32_t ep_disabled : 1;
uint32_t active : 1;
} EP_CMD;
// Endpoint structure
typedef struct __EP {
EP_CMD * const cmd;
uint8_t * const buf;
EP_TRANSFER * const transfer;
uint16_t buf_offset;
} EP;
#endif /* __USB_LPC55XXX_H */
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Examples/MCU-LINK/USB_LPC55xxx.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 546 |
```c
/*
* All rights reserved.
*
*/
/*
* Modified by Arm
*/
#define FSL_USART_MODIFIED_BY_ARM 1U
#include "fsl_usart.h"
#include "fsl_device_registers.h"
#include "fsl_flexcomm.h"
/*******************************************************************************
* Definitions
******************************************************************************/
/* Component ID definition, used by tools. */
#ifndef FSL_COMPONENT_ID
#define FSL_COMPONENT_ID "platform.drivers.flexcomm_usart"
#endif
/*!
* @brief Used for conversion from `flexcomm_usart_irq_handler_t` to `flexcomm_irq_handler_t`
*/
typedef union usart_to_flexcomm
{
flexcomm_usart_irq_handler_t usart_master_handler;
flexcomm_irq_handler_t flexcomm_handler;
} usart_to_flexcomm_t;
enum
{
kUSART_TxIdle, /* TX idle. */
kUSART_TxBusy, /* TX busy. */
kUSART_RxIdle, /* RX idle. */
kUSART_RxBusy /* RX busy. */
};
/*******************************************************************************
* Variables
******************************************************************************/
/*! @brief IRQ name array */
static const IRQn_Type s_usartIRQ[] = USART_IRQS;
/*! @brief Array to map USART instance number to base address. */
static const uint32_t s_usartBaseAddrs[FSL_FEATURE_SOC_USART_COUNT] = USART_BASE_ADDRS;
/*******************************************************************************
* Code
******************************************************************************/
/* Get the index corresponding to the USART */
/*! brief Returns instance number for USART peripheral base address. */
uint32_t USART_GetInstance(USART_Type *base)
{
uint32_t i;
for (i = 0; i < (uint32_t)FSL_FEATURE_SOC_USART_COUNT; i++)
{
if ((uint32_t)base == s_usartBaseAddrs[i])
{
break;
}
}
assert(i < (uint32_t)FSL_FEATURE_SOC_USART_COUNT);
return i;
}
/*!
* brief Get the length of received data in RX ring buffer.
*
* param handle USART handle pointer.
* return Length of received data in RX ring buffer.
*/
size_t USART_TransferGetRxRingBufferLength(usart_handle_t *handle)
{
size_t size;
/* Check arguments */
assert(NULL != handle);
uint16_t rxRingBufferHead = handle->rxRingBufferHead;
uint16_t rxRingBufferTail = handle->rxRingBufferTail;
if (rxRingBufferTail > rxRingBufferHead)
{
size = (size_t)rxRingBufferHead + handle->rxRingBufferSize - (size_t)rxRingBufferTail;
}
else
{
size = (size_t)rxRingBufferHead - (size_t)rxRingBufferTail;
}
return size;
}
static bool USART_TransferIsRxRingBufferFull(usart_handle_t *handle)
{
bool full;
/* Check arguments */
assert(NULL != handle);
if (USART_TransferGetRxRingBufferLength(handle) == (handle->rxRingBufferSize - 1U))
{
full = true;
}
else
{
full = false;
}
return full;
}
/*!
* brief Sets up the RX ring buffer.
*
* This function sets up the RX ring buffer to a specific USART handle.
*
* When the RX ring buffer is used, data received are stored into the ring buffer even when the
* user doesn't call the USART_TransferReceiveNonBlocking() API. If there is already data received
* in the ring buffer, the user can get the received data from the ring buffer directly.
*
* note When using the RX ring buffer, one byte is reserved for internal use. In other
* words, if p ringBufferSize is 32, then only 31 bytes are used for saving data.
*
* param base USART peripheral base address.
* param handle USART handle pointer.
* param ringBuffer Start address of the ring buffer for background receiving. Pass NULL to disable the ring buffer.
* param ringBufferSize size of the ring buffer.
*/
void USART_TransferStartRingBuffer(USART_Type *base, usart_handle_t *handle, uint8_t *ringBuffer, size_t ringBufferSize)
{
/* Check arguments */
assert(NULL != base);
assert(NULL != handle);
assert(NULL != ringBuffer);
/* Setup the ringbuffer address */
handle->rxRingBuffer = ringBuffer;
handle->rxRingBufferSize = ringBufferSize;
handle->rxRingBufferHead = 0U;
handle->rxRingBufferTail = 0U;
/* ring buffer is ready we can start receiving data */
base->FIFOINTENSET = USART_FIFOINTENSET_RXLVL_MASK | USART_FIFOINTENSET_RXERR_MASK;
}
/*!
* brief Aborts the background transfer and uninstalls the ring buffer.
*
* This function aborts the background transfer and uninstalls the ring buffer.
*
* param base USART peripheral base address.
* param handle USART handle pointer.
*/
void USART_TransferStopRingBuffer(USART_Type *base, usart_handle_t *handle)
{
/* Check arguments */
assert(NULL != base);
assert(NULL != handle);
if (handle->rxState == (uint8_t)kUSART_RxIdle)
{
base->FIFOINTENCLR = USART_FIFOINTENCLR_RXLVL_MASK | USART_FIFOINTENCLR_RXERR_MASK;
}
handle->rxRingBuffer = NULL;
handle->rxRingBufferSize = 0U;
handle->rxRingBufferHead = 0U;
handle->rxRingBufferTail = 0U;
}
/*!
* brief Initializes a USART instance with user configuration structure and peripheral clock.
*
* This function configures the USART module with the user-defined settings. The user can configure the configuration
* structure and also get the default configuration by using the USART_GetDefaultConfig() function.
* Example below shows how to use this API to configure USART.
* code
* usart_config_t usartConfig;
* usartConfig.baudRate_Bps = 115200U;
* usartConfig.parityMode = kUSART_ParityDisabled;
* usartConfig.stopBitCount = kUSART_OneStopBit;
* USART_Init(USART1, &usartConfig, 20000000U);
* endcode
*
* param base USART peripheral base address.
* param config Pointer to user-defined configuration structure.
* param srcClock_Hz USART clock source frequency in HZ.
* retval kStatus_USART_BaudrateNotSupport Baudrate is not support in current clock source.
* retval kStatus_InvalidArgument USART base address is not valid
* retval kStatus_Success Status USART initialize succeed
*/
status_t USART_Init(USART_Type *base, const usart_config_t *config, uint32_t srcClock_Hz)
{
int result;
/* check arguments */
assert(!((NULL == base) || (NULL == config) || (0U == srcClock_Hz)));
if ((NULL == base) || (NULL == config) || (0U == srcClock_Hz))
{
return kStatus_InvalidArgument;
}
/* initialize flexcomm to USART mode */
result = FLEXCOMM_Init(base, FLEXCOMM_PERIPH_USART);
if (kStatus_Success != result)
{
return result;
}
if (config->enableTx)
{
/* empty and enable txFIFO */
base->FIFOCFG |= USART_FIFOCFG_EMPTYTX_MASK | USART_FIFOCFG_ENABLETX_MASK;
/* setup trigger level */
base->FIFOTRIG &= ~(USART_FIFOTRIG_TXLVL_MASK);
base->FIFOTRIG |= USART_FIFOTRIG_TXLVL(config->txWatermark);
/* enable trigger interrupt */
base->FIFOTRIG |= USART_FIFOTRIG_TXLVLENA_MASK;
}
/* empty and enable rxFIFO */
if (config->enableRx)
{
base->FIFOCFG |= USART_FIFOCFG_EMPTYRX_MASK | USART_FIFOCFG_ENABLERX_MASK;
/* setup trigger level */
base->FIFOTRIG &= ~(USART_FIFOTRIG_RXLVL_MASK);
base->FIFOTRIG |= USART_FIFOTRIG_RXLVL(config->rxWatermark);
/* enable trigger interrupt */
base->FIFOTRIG |= USART_FIFOTRIG_RXLVLENA_MASK;
}
/* setup configuration and enable USART */
base->CFG = USART_CFG_PARITYSEL(config->parityMode) | USART_CFG_STOPLEN(config->stopBitCount) |
USART_CFG_DATALEN(config->bitCountPerChar) | USART_CFG_LOOP(config->loopback) |
USART_CFG_SYNCEN((uint32_t)config->syncMode >> 1) | USART_CFG_SYNCMST((uint8_t)config->syncMode) |
USART_CFG_CLKPOL(config->clockPolarity) | USART_CFG_MODE32K(config->enableMode32k) |
USART_CFG_CTSEN(config->enableHardwareFlowControl) | USART_CFG_ENABLE_MASK;
/* Setup baudrate */
if (config->enableMode32k)
{
if ((9600U % config->baudRate_Bps) == 0U)
{
base->BRG = 9600U / config->baudRate_Bps;
}
else
{
return kStatus_USART_BaudrateNotSupport;
}
}
else
{
result = USART_SetBaudRate(base, config->baudRate_Bps, srcClock_Hz);
if (kStatus_Success != result)
{
return result;
}
}
/* Setting continuous Clock configuration. used for synchronous mode. */
USART_EnableContinuousSCLK(base, config->enableContinuousSCLK);
return kStatus_Success;
}
/*!
* brief Deinitializes a USART instance.
*
* This function waits for TX complete, disables TX and RX, and disables the USART clock.
*
* param base USART peripheral base address.
*/
void USART_Deinit(USART_Type *base)
{
/* Check arguments */
assert(NULL != base);
while (0U == (base->STAT & USART_STAT_TXIDLE_MASK))
{
}
/* Disable interrupts, disable dma requests, disable peripheral */
base->FIFOINTENCLR = USART_FIFOINTENCLR_TXERR_MASK | USART_FIFOINTENCLR_RXERR_MASK | USART_FIFOINTENCLR_TXLVL_MASK |
USART_FIFOINTENCLR_RXLVL_MASK;
base->FIFOCFG &= ~(USART_FIFOCFG_DMATX_MASK | USART_FIFOCFG_DMARX_MASK);
base->CFG &= ~(USART_CFG_ENABLE_MASK);
}
/*!
* brief Gets the default configuration structure.
*
* This function initializes the USART configuration structure to a default value. The default
* values are:
* usartConfig->baudRate_Bps = 115200U;
* usartConfig->parityMode = kUSART_ParityDisabled;
* usartConfig->stopBitCount = kUSART_OneStopBit;
* usartConfig->bitCountPerChar = kUSART_8BitsPerChar;
* usartConfig->loopback = false;
* usartConfig->enableTx = false;
* usartConfig->enableRx = false;
*
* param config Pointer to configuration structure.
*/
void USART_GetDefaultConfig(usart_config_t *config)
{
/* Check arguments */
assert(NULL != config);
/* Initializes the configure structure to zero. */
(void)memset(config, 0, sizeof(*config));
/* Set always all members ! */
config->baudRate_Bps = 115200U;
config->parityMode = kUSART_ParityDisabled;
config->stopBitCount = kUSART_OneStopBit;
config->bitCountPerChar = kUSART_8BitsPerChar;
config->loopback = false;
config->enableRx = false;
config->enableTx = false;
config->enableMode32k = false;
config->txWatermark = kUSART_TxFifo0;
config->rxWatermark = kUSART_RxFifo1;
config->syncMode = kUSART_SyncModeDisabled;
config->enableContinuousSCLK = false;
config->clockPolarity = kUSART_RxSampleOnFallingEdge;
config->enableHardwareFlowControl = false;
}
#ifdef FSL_USART_MODIFIED_BY_ARM
#define FRACT_BITS 12U
#define BAUDRATE_DIVIDER_MAX_ERROR 3U
/*!
* brief Sets the USART instance baud rate.
*
* This function configures the USART module baud rate.
*
* USART_SetBaudRate(USART1, 115200U, 20000000U);
* endcode
*
* param base USART peripheral base address.
* param baudrate_Bps USART baudrate to be set.
* param srcClock_Hz USART clock source frequency in HZ (not used)
* retval kStatus_USART_BaudrateNotSupport Baudrate is not support in current clock source.
* retval kStatus_Success Set baudrate succeed.
* retval kStatus_InvalidArgument One or more arguments are invalid.
*
* Requirement:
* FlexComm input clock must be set 48MHz (fro_hf / 2).
*/
status_t USART_SetBaudRate(USART_Type *base, uint32_t baudrate_Bps, uint32_t srcClock_Hz)
{
uint32_t flexcomm_idx;
uint32_t flexcomm_clock;
uint32_t div, div_calc; /* divider, 12 LSBs are fractonal part */
uint8_t ovs, ovs_best; /* oversampling */
uint32_t br_div, br_div_best; /* baudate divider */
uint8_t mul;
uint32_t delta;
(void)srcClock_Hz;
flexcomm_idx = FLEXCOMM_GetInstance(base);
flexcomm_clock = CLOCK_GetFlexCommInputClock(flexcomm_idx);
if (flexcomm_clock != 48000000U)
{
/* FlexComm input clock must be 48000000 */
return kStatus_USART_BaudrateNotSupport;
}
/* Calculate fixed point divider (12 LSBs are fractional part) */
div = (uint32_t)(((uint64_t)flexcomm_clock << FRACT_BITS) / (uint64_t)baudrate_Bps);
if ((div >> FRACT_BITS) < 5U)
{
return kStatus_USART_BaudrateNotSupport;
}
br_div_best = 0U;
if ((div & ((1 << FRACT_BITS) - 1U)) == 0U)
{
/* Divider has no fractional part */
for (ovs = 16; ovs > 8U; ovs--)
{
br_div = div / ovs;
if ((br_div & ((1 << FRACT_BITS) - 1U)) == 0U)
{
ovs_best = ovs;
br_div_best = br_div >> FRACT_BITS;
mul = 0U;
break;
}
}
}
if (br_div_best == 0U)
{
/* Divider has fractional part */
if ((div >> FRACT_BITS) > 16)
{
/* Oversampling is fixed to 16 */
ovs_best = 16U;
br_div = (div / ovs_best)>> FRACT_BITS;
if (br_div <= 0xFFFFU)
{
br_div_best = br_div;
}
else
{
return kStatus_USART_BaudrateNotSupport;
}
/* div = (1 + (mul / 256)) * (ovs * br_div) => mul = (256 * div) / (ovs * br_div) - 256 */
mul = ((((uint64_t)div * (uint64_t)256U) / ((uint64_t)ovs_best * (uint64_t)br_div_best)) >> FRACT_BITS) - 256U;
}
else
{
/* Baudrate divider is fixed to 1. */
br_div_best = 1U;
ovs_best = div >> FRACT_BITS;
mul = ((((uint64_t)div * (uint64_t)256U) / ((uint64_t)ovs_best * (uint64_t)br_div_best)) >> FRACT_BITS) - 256U;
}
}
div_calc = (uint32_t)(((uint64_t)ovs_best * (uint64_t)br_div_best * (uint64_t)mul) << FRACT_BITS) / 256U + (((uint64_t)ovs_best * (uint64_t)br_div_best) << FRACT_BITS);
delta = (div < div_calc) ? (div_calc - div) : (div - div_calc);
if (((delta * 100U) / div) > BAUDRATE_DIVIDER_MAX_ERROR)
{
return kStatus_USART_BaudrateNotSupport;
}
CLOCK_SetClkDiv(kCLOCK_DivFlexFrg0 + flexcomm_idx, mul, false);
base->OSR = ovs_best - 1U;
base->BRG = br_div_best - 1U;
return kStatus_Success;
}
#else
/*!
* brief Sets the USART instance baud rate.
*
* This function configures the USART module baud rate. This function is used to update
* the USART module baud rate after the USART module is initialized by the USART_Init.
* code
* USART_SetBaudRate(USART1, 115200U, 20000000U);
* endcode
*
* param base USART peripheral base address.
* param baudrate_Bps USART baudrate to be set.
* param srcClock_Hz USART clock source frequency in HZ.
* retval kStatus_USART_BaudrateNotSupport Baudrate is not support in current clock source.
* retval kStatus_Success Set baudrate succeed.
* retval kStatus_InvalidArgument One or more arguments are invalid.
*/
status_t USART_SetBaudRate(USART_Type *base, uint32_t baudrate_Bps, uint32_t srcClock_Hz)
{
uint32_t best_diff = (uint32_t)-1, best_osrval = 0xf, best_brgval = (uint32_t)-1;
uint32_t osrval, brgval, diff, baudrate;
/* check arguments */
assert(!((NULL == base) || (0U == baudrate_Bps) || (0U == srcClock_Hz)));
if ((NULL == base) || (0U == baudrate_Bps) || (0U == srcClock_Hz))
{
return kStatus_InvalidArgument;
}
/* If synchronous master mode is enabled, only configure the BRG value. */
if ((base->CFG & USART_CFG_SYNCEN_MASK) != 0U)
{
if ((base->CFG & USART_CFG_SYNCMST_MASK) != 0U)
{
brgval = srcClock_Hz / baudrate_Bps;
base->BRG = brgval - 1U;
}
}
else
{
/*
* Smaller values of OSR can make the sampling position within a data bit less accurate and may
* potentially cause more noise errors or incorrect data.
*/
for (osrval = best_osrval; osrval >= 8U; osrval--)
{
brgval = (((srcClock_Hz * 10U) / ((osrval + 1U) * baudrate_Bps)) - 5U) / 10U;
if (brgval > 0xFFFFU)
{
continue;
}
baudrate = srcClock_Hz / ((osrval + 1U) * (brgval + 1U));
diff = (baudrate_Bps < baudrate) ? (baudrate - baudrate_Bps) : (baudrate_Bps - baudrate);
if (diff < best_diff)
{
best_diff = diff;
best_osrval = osrval;
best_brgval = brgval;
}
}
/* Check to see if actual baud rate is within 3% of desired baud rate
* based on the best calculated OSR and BRG value */
baudrate = srcClock_Hz / ((best_osrval + 1U) * (best_brgval + 1U));
diff = (baudrate_Bps < baudrate) ? (baudrate - baudrate_Bps) : (baudrate_Bps - baudrate);
if (diff > ((baudrate_Bps / 100U) * 3U))
{
return kStatus_USART_BaudrateNotSupport;
}
/* value over range */
if (best_brgval > 0xFFFFU)
{
return kStatus_USART_BaudrateNotSupport;
}
base->OSR = best_osrval;
base->BRG = best_brgval;
}
return kStatus_Success;
}
#endif
/*!
* brief Enable 32 kHz mode which USART uses clock from the RTC oscillator as the clock source.
*
* Please note that in order to use a 32 kHz clock to operate USART properly, the RTC oscillator
* and its 32 kHz output must be manully enabled by user, by calling RTC_Init and setting
* SYSCON_RTCOSCCTRL_EN bit to 1.
* And in 32kHz clocking mode the USART can only work at 9600 baudrate or at the baudrate that
* 9600 can evenly divide, eg: 4800, 3200.
*
* param base USART peripheral base address.
* param baudRate_Bps USART baudrate to be set..
* param enableMode32k true is 32k mode, false is normal mode.
* param srcClock_Hz USART clock source frequency in HZ.
* retval kStatus_USART_BaudrateNotSupport Baudrate is not support in current clock source.
* retval kStatus_Success Set baudrate succeed.
* retval kStatus_InvalidArgument One or more arguments are invalid.
*/
status_t USART_Enable32kMode(USART_Type *base, uint32_t baudRate_Bps, bool enableMode32k, uint32_t srcClock_Hz)
{
#ifdef FSL_USART_MODIFIED_BY_ARM
(void)base;
(void)baudRate_Bps;
(void)enableMode32k;
(void)srcClock_Hz;
return kStatus_USART_BaudrateNotSupport;
#else
status_t result = kStatus_Success;
base->CFG &= ~(USART_CFG_ENABLE_MASK);
if (enableMode32k)
{
base->CFG |= USART_CFG_MODE32K_MASK;
if ((9600U % baudRate_Bps) == 0U)
{
base->BRG = 9600U / baudRate_Bps - 1U;
}
else
{
return kStatus_USART_BaudrateNotSupport;
}
}
else
{
base->CFG &= ~(USART_CFG_MODE32K_MASK);
result = USART_SetBaudRate(base, baudRate_Bps, srcClock_Hz);
if (kStatus_Success != result)
{
return result;
}
}
base->CFG |= USART_CFG_ENABLE_MASK;
return result;
#endif
}
/*!
* brief Enable 9-bit data mode for USART.
*
* This function set the 9-bit mode for USART module. The 9th bit is not used for parity thus can be modified by user.
*
* param base USART peripheral base address.
* param enable true to enable, false to disable.
*/
void USART_Enable9bitMode(USART_Type *base, bool enable)
{
assert(base != NULL);
uint32_t temp = 0U;
if (enable)
{
/* Set USART 9-bit mode, disable parity. */
temp = base->CFG & ~((uint32_t)USART_CFG_DATALEN_MASK | (uint32_t)USART_CFG_PARITYSEL_MASK);
temp |= (uint32_t)USART_CFG_DATALEN(0x2U);
base->CFG = temp;
}
else
{
/* Set USART to 8-bit mode. */
base->CFG &= ~((uint32_t)USART_CFG_DATALEN_MASK);
base->CFG |= (uint32_t)USART_CFG_DATALEN(0x1U);
}
}
/*!
* brief Transmit an address frame in 9-bit data mode.
*
* param base USART peripheral base address.
* param address USART slave address.
*/
void USART_SendAddress(USART_Type *base, uint8_t address)
{
assert(base != NULL);
base->FIFOWR = ((uint32_t)address | 0x100UL);
}
/*!
* brief Writes to the TX register using a blocking method.
*
* This function polls the TX register, waits for the TX register to be empty or for the TX FIFO
* to have room and writes data to the TX buffer.
*
* param base USART peripheral base address.
* param data Start address of the data to write.
* param length Size of the data to write.
* retval kStatus_USART_Timeout Transmission timed out and was aborted.
* retval kStatus_InvalidArgument Invalid argument.
* retval kStatus_Success Successfully wrote all data.
*/
status_t USART_WriteBlocking(USART_Type *base, const uint8_t *data, size_t length)
{
/* Check arguments */
assert(!((NULL == base) || (NULL == data)));
#if UART_RETRY_TIMES
uint32_t waitTimes;
#endif
if ((NULL == base) || (NULL == data))
{
return kStatus_InvalidArgument;
}
/* Check whether txFIFO is enabled */
if (0U == (base->FIFOCFG & USART_FIFOCFG_ENABLETX_MASK))
{
return kStatus_InvalidArgument;
}
for (; length > 0U; length--)
{
/* Loop until txFIFO get some space for new data */
#if UART_RETRY_TIMES
waitTimes = UART_RETRY_TIMES;
while ((0U == (base->FIFOSTAT & USART_FIFOSTAT_TXNOTFULL_MASK)) && (--waitTimes != 0U))
#else
while (0U == (base->FIFOSTAT & USART_FIFOSTAT_TXNOTFULL_MASK))
#endif
{
}
#if UART_RETRY_TIMES
if (0U == waitTimes)
{
return kStatus_USART_Timeout;
}
#endif
base->FIFOWR = *data;
data++;
}
/* Wait to finish transfer */
#if UART_RETRY_TIMES
waitTimes = UART_RETRY_TIMES;
while ((0U == (base->STAT & USART_STAT_TXIDLE_MASK)) && (--waitTimes != 0U))
#else
while (0U == (base->STAT & USART_STAT_TXIDLE_MASK))
#endif
{
}
#if UART_RETRY_TIMES
if (0U == waitTimes)
{
return kStatus_USART_Timeout;
}
#endif
return kStatus_Success;
}
/*!
* brief Read RX data register using a blocking method.
*
* This function polls the RX register, waits for the RX register to be full or for RX FIFO to
* have data and read data from the TX register.
*
* param base USART peripheral base address.
* param data Start address of the buffer to store the received data.
* param length Size of the buffer.
* retval kStatus_USART_FramingError Receiver overrun happened while receiving data.
* retval kStatus_USART_ParityError Noise error happened while receiving data.
* retval kStatus_USART_NoiseError Framing error happened while receiving data.
* retval kStatus_USART_RxError Overflow or underflow rxFIFO happened.
* retval kStatus_USART_Timeout Transmission timed out and was aborted.
* retval kStatus_Success Successfully received all data.
*/
status_t USART_ReadBlocking(USART_Type *base, uint8_t *data, size_t length)
{
uint32_t statusFlag;
status_t status = kStatus_Success;
#if UART_RETRY_TIMES
uint32_t waitTimes;
#endif
/* check arguments */
assert(!((NULL == base) || (NULL == data)));
if ((NULL == base) || (NULL == data))
{
return kStatus_InvalidArgument;
}
/* Check whether rxFIFO is enabled */
if ((base->FIFOCFG & USART_FIFOCFG_ENABLERX_MASK) == 0U)
{
return kStatus_Fail;
}
for (; length > 0U; length--)
{
/* loop until rxFIFO have some data to read */
#if UART_RETRY_TIMES
waitTimes = UART_RETRY_TIMES;
while (((base->FIFOSTAT & USART_FIFOSTAT_RXNOTEMPTY_MASK) == 0U) && (--waitTimes != 0U))
#else
while ((base->FIFOSTAT & USART_FIFOSTAT_RXNOTEMPTY_MASK) == 0U)
#endif
{
}
#if UART_RETRY_TIMES
if (waitTimes == 0U)
{
status = kStatus_USART_Timeout;
break;
}
#endif
/* check rxFIFO statusFlag */
if ((base->FIFOSTAT & USART_FIFOSTAT_RXERR_MASK) != 0U)
{
base->FIFOCFG |= USART_FIFOCFG_EMPTYRX_MASK;
base->FIFOSTAT |= USART_FIFOSTAT_RXERR_MASK;
status = kStatus_USART_RxError;
break;
}
/* check receive statusFlag */
statusFlag = base->STAT;
/* Clear all status flags */
base->STAT |= statusFlag;
if ((statusFlag & USART_STAT_PARITYERRINT_MASK) != 0U)
{
status = kStatus_USART_ParityError;
}
if ((statusFlag & USART_STAT_FRAMERRINT_MASK) != 0U)
{
status = kStatus_USART_FramingError;
}
if ((statusFlag & USART_STAT_RXNOISEINT_MASK) != 0U)
{
status = kStatus_USART_NoiseError;
}
if (kStatus_Success == status)
{
*data = (uint8_t)base->FIFORD;
data++;
}
else
{
break;
}
}
return status;
}
/*!
* brief Initializes the USART handle.
*
* This function initializes the USART handle which can be used for other USART
* transactional APIs. Usually, for a specified USART instance,
* call this API once to get the initialized handle.
*
* param base USART peripheral base address.
* param handle USART handle pointer.
* param callback The callback function.
* param userData The parameter of the callback function.
*/
status_t USART_TransferCreateHandle(USART_Type *base,
usart_handle_t *handle,
usart_transfer_callback_t callback,
void *userData)
{
/* Check 'base' */
assert(!((NULL == base) || (NULL == handle)));
uint32_t instance = 0;
usart_to_flexcomm_t handler;
handler.usart_master_handler = USART_TransferHandleIRQ;
if ((NULL == base) || (NULL == handle))
{
return kStatus_InvalidArgument;
}
instance = USART_GetInstance(base);
(void)memset(handle, 0, sizeof(*handle));
/* Set the TX/RX state. */
handle->rxState = (uint8_t)kUSART_RxIdle;
handle->txState = (uint8_t)kUSART_TxIdle;
/* Set the callback and user data. */
handle->callback = callback;
handle->userData = userData;
handle->rxWatermark = (uint8_t)USART_FIFOTRIG_RXLVL_GET(base);
handle->txWatermark = (uint8_t)USART_FIFOTRIG_TXLVL_GET(base);
FLEXCOMM_SetIRQHandler(base, handler.flexcomm_handler, handle);
/* Enable interrupt in NVIC. */
(void)EnableIRQ(s_usartIRQ[instance]);
return kStatus_Success;
}
/*!
* brief Transmits a buffer of data using the interrupt method.
*
* This function sends data using an interrupt method. This is a non-blocking function, which
* returns directly without waiting for all data to be written to the TX register. When
* all data is written to the TX register in the IRQ handler, the USART driver calls the callback
* function and passes the ref kStatus_USART_TxIdle as status parameter.
*
* note The kStatus_USART_TxIdle is passed to the upper layer when all data is written
* to the TX register. However it does not ensure that all data are sent out. Before disabling the TX,
* check the kUSART_TransmissionCompleteFlag to ensure that the TX is finished.
*
* param base USART peripheral base address.
* param handle USART handle pointer.
* param xfer USART transfer structure. See #usart_transfer_t.
* retval kStatus_Success Successfully start the data transmission.
* retval kStatus_USART_TxBusy Previous transmission still not finished, data not all written to TX register yet.
* retval kStatus_InvalidArgument Invalid argument.
*/
status_t USART_TransferSendNonBlocking(USART_Type *base, usart_handle_t *handle, usart_transfer_t *xfer)
{
/* Check arguments */
assert(!((NULL == base) || (NULL == handle) || (NULL == xfer)));
if ((NULL == base) || (NULL == handle) || (NULL == xfer))
{
return kStatus_InvalidArgument;
}
/* Check xfer members */
assert(!((0U == xfer->dataSize) || (NULL == xfer->txData)));
if ((0U == xfer->dataSize) || (NULL == xfer->txData))
{
return kStatus_InvalidArgument;
}
/* Return error if current TX busy. */
if ((uint8_t)kUSART_TxBusy == handle->txState)
{
return kStatus_USART_TxBusy;
}
else
{
/* Disable IRQ when configuring transfer handle, in case interrupt occurs during the process and messes up the
* handle value. */
uint32_t interruptMask = USART_GetEnabledInterrupts(base);
USART_DisableInterrupts(base, interruptMask);
handle->txData = xfer->txData;
handle->txDataSize = xfer->dataSize;
handle->txDataSizeAll = xfer->dataSize;
handle->txState = (uint8_t)kUSART_TxBusy;
/* Enable transmiter interrupt and the previously disabled interrupt. */
USART_EnableInterrupts(base, interruptMask | (uint32_t)kUSART_TxLevelInterruptEnable);
}
return kStatus_Success;
}
/*!
* brief Aborts the interrupt-driven data transmit.
*
* This function aborts the interrupt driven data sending. The user can get the remainBtyes to find out
* how many bytes are still not sent out.
*
* param base USART peripheral base address.
* param handle USART handle pointer.
*/
void USART_TransferAbortSend(USART_Type *base, usart_handle_t *handle)
{
assert(NULL != handle);
/* Disable interrupts */
USART_DisableInterrupts(base, (uint32_t)kUSART_TxLevelInterruptEnable);
/* Empty txFIFO */
base->FIFOCFG |= USART_FIFOCFG_EMPTYTX_MASK;
handle->txDataSize = 0U;
handle->txState = (uint8_t)kUSART_TxIdle;
}
/*!
* brief Get the number of bytes that have been sent out to bus.
*
* This function gets the number of bytes that have been sent out to bus by interrupt method.
*
* param base USART peripheral base address.
* param handle USART handle pointer.
* param count Send bytes count.
* retval kStatus_NoTransferInProgress No send in progress.
* retval kStatus_InvalidArgument Parameter is invalid.
* retval kStatus_Success Get successfully through the parameter \p count;
*/
status_t USART_TransferGetSendCount(USART_Type *base, usart_handle_t *handle, uint32_t *count)
{
assert(NULL != handle);
assert(NULL != count);
if ((uint8_t)kUSART_TxIdle == handle->txState)
{
return kStatus_NoTransferInProgress;
}
*count = handle->txDataSizeAll - handle->txDataSize -
((base->FIFOSTAT & USART_FIFOSTAT_TXLVL_MASK) >> USART_FIFOSTAT_TXLVL_SHIFT);
return kStatus_Success;
}
/*!
* brief Receives a buffer of data using an interrupt method.
*
* This function receives data using an interrupt method. This is a non-blocking function, which
* returns without waiting for all data to be received.
* If the RX ring buffer is used and not empty, the data in the ring buffer is copied and
* the parameter p receivedBytes shows how many bytes are copied from the ring buffer.
* After copying, if the data in the ring buffer is not enough to read, the receive
* request is saved by the USART driver. When the new data arrives, the receive request
* is serviced first. When all data is received, the USART driver notifies the upper layer
* through a callback function and passes the status parameter ref kStatus_USART_RxIdle.
* For example, the upper layer needs 10 bytes but there are only 5 bytes in the ring buffer.
* The 5 bytes are copied to the xfer->data and this function returns with the
* parameter p receivedBytes set to 5. For the left 5 bytes, newly arrived data is
* saved from the xfer->data[5]. When 5 bytes are received, the USART driver notifies the upper layer.
* If the RX ring buffer is not enabled, this function enables the RX and RX interrupt
* to receive data to the xfer->data. When all data is received, the upper layer is notified.
*
* param base USART peripheral base address.
* param handle USART handle pointer.
* param xfer USART transfer structure, see #usart_transfer_t.
* param receivedBytes Bytes received from the ring buffer directly.
* retval kStatus_Success Successfully queue the transfer into transmit queue.
* retval kStatus_USART_RxBusy Previous receive request is not finished.
* retval kStatus_InvalidArgument Invalid argument.
*/
status_t USART_TransferReceiveNonBlocking(USART_Type *base,
usart_handle_t *handle,
usart_transfer_t *xfer,
size_t *receivedBytes)
{
uint32_t i;
/* How many bytes to copy from ring buffer to user memory. */
size_t bytesToCopy = 0U;
/* How many bytes to receive. */
size_t bytesToReceive;
/* How many bytes currently have received. */
size_t bytesCurrentReceived;
uint32_t interruptMask = 0U;
/* Check arguments */
assert(!((NULL == base) || (NULL == handle) || (NULL == xfer)));
if ((NULL == base) || (NULL == handle) || (NULL == xfer))
{
return kStatus_InvalidArgument;
}
/* Check xfer members */
assert(!((0U == xfer->dataSize) || (NULL == xfer->rxData)));
if ((0U == xfer->dataSize) || (NULL == xfer->rxData))
{
return kStatus_InvalidArgument;
}
/* Enable address detect when address match is enabled. */
if ((base->CFG & (uint32_t)USART_CFG_AUTOADDR_MASK) != 0U)
{
base->CTL |= (uint32_t)USART_CTL_ADDRDET_MASK;
}
/* How to get data:
1. If RX ring buffer is not enabled, then save xfer->data and xfer->dataSize
to uart handle, enable interrupt to store received data to xfer->data. When
all data received, trigger callback.
2. If RX ring buffer is enabled and not empty, get data from ring buffer first.
If there are enough data in ring buffer, copy them to xfer->data and return.
If there are not enough data in ring buffer, copy all of them to xfer->data,
save the xfer->data remained empty space to uart handle, receive data
to this empty space and trigger callback when finished. */
if ((uint8_t)kUSART_RxBusy == handle->rxState)
{
return kStatus_USART_RxBusy;
}
else
{
bytesToReceive = xfer->dataSize;
bytesCurrentReceived = 0U;
/* If RX ring buffer is used. */
if (handle->rxRingBuffer != NULL)
{
/* Disable IRQ, protect ring buffer. */
interruptMask = USART_GetEnabledInterrupts(base);
USART_DisableInterrupts(base, interruptMask);
/* How many bytes in RX ring buffer currently. */
bytesToCopy = USART_TransferGetRxRingBufferLength(handle);
if (bytesToCopy != 0U)
{
bytesToCopy = MIN(bytesToReceive, bytesToCopy);
bytesToReceive -= bytesToCopy;
/* Copy data from ring buffer to user memory. */
for (i = 0U; i < bytesToCopy; i++)
{
xfer->rxData[bytesCurrentReceived++] = handle->rxRingBuffer[handle->rxRingBufferTail];
/* Wrap to 0. Not use modulo (%) because it might be large and slow. */
if ((size_t)handle->rxRingBufferTail + 1U == handle->rxRingBufferSize)
{
handle->rxRingBufferTail = 0U;
}
else
{
handle->rxRingBufferTail++;
}
}
}
/* If ring buffer does not have enough data, still need to read more data. */
if (bytesToReceive != 0U)
{
/* No data in ring buffer, save the request to UART handle. */
handle->rxData = xfer->rxData + bytesCurrentReceived;
handle->rxDataSize = bytesToReceive;
handle->rxDataSizeAll = xfer->dataSize;
handle->rxState = (uint8_t)kUSART_RxBusy;
}
/* Re-enable IRQ. */
USART_EnableInterrupts(base, interruptMask);
/* Call user callback since all data are received. */
if (0U == bytesToReceive)
{
if (handle->callback != NULL)
{
handle->callback(base, handle, kStatus_USART_RxIdle, handle->userData);
}
}
}
/* Ring buffer not used. */
else
{
/* Disable IRQ when configuring transfer handle, in case interrupt occurs during the process and messes up
* the handle value. */
interruptMask = USART_GetEnabledInterrupts(base);
USART_DisableInterrupts(base, interruptMask);
handle->rxData = xfer->rxData + bytesCurrentReceived;
handle->rxDataSize = bytesToReceive;
handle->rxDataSizeAll = bytesToReceive;
handle->rxState = (uint8_t)kUSART_RxBusy;
/* Enable RX interrupt. */
base->FIFOINTENSET = USART_FIFOINTENSET_RXLVL_MASK;
/* Re-enable IRQ. */
USART_EnableInterrupts(base, interruptMask);
}
/* Return the how many bytes have read. */
if (receivedBytes != NULL)
{
*receivedBytes = bytesCurrentReceived;
}
}
return kStatus_Success;
}
/*!
* brief Aborts the interrupt-driven data receiving.
*
* This function aborts the interrupt-driven data receiving. The user can get the remainBytes to find out
* how many bytes not received yet.
*
* param base USART peripheral base address.
* param handle USART handle pointer.
*/
void USART_TransferAbortReceive(USART_Type *base, usart_handle_t *handle)
{
assert(NULL != handle);
/* Only abort the receive to handle->rxData, the RX ring buffer is still working. */
if (NULL == handle->rxRingBuffer)
{
/* Disable interrupts */
USART_DisableInterrupts(base, (uint32_t)kUSART_RxLevelInterruptEnable);
/* Empty rxFIFO */
base->FIFOCFG |= USART_FIFOCFG_EMPTYRX_MASK;
}
handle->rxDataSize = 0U;
handle->rxState = (uint8_t)kUSART_RxIdle;
}
/*!
* brief Get the number of bytes that have been received.
*
* This function gets the number of bytes that have been received.
*
* param base USART peripheral base address.
* param handle USART handle pointer.
* param count Receive bytes count.
* retval kStatus_NoTransferInProgress No receive in progress.
* retval kStatus_InvalidArgument Parameter is invalid.
* retval kStatus_Success Get successfully through the parameter \p count;
*/
status_t USART_TransferGetReceiveCount(USART_Type *base, usart_handle_t *handle, uint32_t *count)
{
assert(NULL != handle);
assert(NULL != count);
if ((uint8_t)kUSART_RxIdle == handle->rxState)
{
return kStatus_NoTransferInProgress;
}
*count = handle->rxDataSizeAll - handle->rxDataSize;
return kStatus_Success;
}
/*!
* brief USART IRQ handle function.
*
* This function handles the USART transmit and receive IRQ request.
*
* param base USART peripheral base address.
* param handle USART handle pointer.
*/
void USART_TransferHandleIRQ(USART_Type *base, usart_handle_t *handle)
{
/* Check arguments */
assert((NULL != base) && (NULL != handle));
bool receiveEnabled = ((handle->rxDataSize != 0U) || (handle->rxRingBuffer != NULL));
bool sendEnabled = (handle->txDataSize != 0U);
uint8_t rxdata;
size_t tmpsize;
/* If RX overrun. */
if ((base->FIFOSTAT & USART_FIFOSTAT_RXERR_MASK) != 0U)
{
/* Clear rx error state. */
base->FIFOSTAT |= USART_FIFOSTAT_RXERR_MASK;
/* clear rxFIFO */
base->FIFOCFG |= USART_FIFOCFG_EMPTYRX_MASK;
/* Trigger callback. */
if (handle->callback != NULL)
{
handle->callback(base, handle, kStatus_USART_RxError, handle->userData);
}
}
while ((receiveEnabled && ((base->FIFOSTAT & USART_FIFOSTAT_RXNOTEMPTY_MASK) != 0U)) ||
(sendEnabled && ((base->FIFOSTAT & USART_FIFOSTAT_TXNOTFULL_MASK) != 0U)))
{
/* Receive data */
if (receiveEnabled && ((base->FIFOSTAT & USART_FIFOSTAT_RXNOTEMPTY_MASK) != 0U))
{
/* Clear address detect when RXFIFO has data. */
base->CTL &= ~(uint32_t)USART_CTL_ADDRDET_MASK;
/* Receive to app bufffer if app buffer is present */
if (handle->rxDataSize != 0U)
{
rxdata = (uint8_t)base->FIFORD;
*handle->rxData = rxdata;
handle->rxDataSize--;
handle->rxData++;
receiveEnabled = ((handle->rxDataSize != 0U) || (handle->rxRingBuffer != NULL));
if (0U == handle->rxDataSize)
{
if (NULL == handle->rxRingBuffer)
{
base->FIFOINTENCLR = USART_FIFOINTENCLR_RXLVL_MASK | USART_FIFOINTENSET_RXERR_MASK;
}
handle->rxState = (uint8_t)kUSART_RxIdle;
if (handle->callback != NULL)
{
handle->callback(base, handle, kStatus_USART_RxIdle, handle->userData);
}
}
}
/* Otherwise receive to ring buffer if ring buffer is present */
else
{
if (handle->rxRingBuffer != NULL)
{
/* If RX ring buffer is full, trigger callback to notify over run. */
if (USART_TransferIsRxRingBufferFull(handle))
{
if (handle->callback != NULL)
{
handle->callback(base, handle, kStatus_USART_RxRingBufferOverrun, handle->userData);
}
}
/* If ring buffer is still full after callback function, the oldest data is overridden. */
if (USART_TransferIsRxRingBufferFull(handle))
{
/* Increase handle->rxRingBufferTail to make room for new data. */
if ((size_t)handle->rxRingBufferTail + 1U == handle->rxRingBufferSize)
{
handle->rxRingBufferTail = 0U;
}
else
{
handle->rxRingBufferTail++;
}
}
/* Read data. */
rxdata = (uint8_t)base->FIFORD;
handle->rxRingBuffer[handle->rxRingBufferHead] = rxdata;
/* Increase handle->rxRingBufferHead. */
if ((size_t)handle->rxRingBufferHead + 1U == handle->rxRingBufferSize)
{
handle->rxRingBufferHead = 0U;
}
else
{
handle->rxRingBufferHead++;
}
}
}
}
/* Send data */
if (sendEnabled && ((base->FIFOSTAT & USART_FIFOSTAT_TXNOTFULL_MASK) != 0U))
{
base->FIFOWR = *handle->txData;
handle->txDataSize--;
handle->txData++;
sendEnabled = handle->txDataSize != 0U;
if (!sendEnabled)
{
base->FIFOINTENCLR = USART_FIFOINTENCLR_TXLVL_MASK;
base->INTENSET = USART_INTENSET_TXIDLEEN_MASK;
}
}
}
/* Tx idle and the interrupt is enabled. */
if ((0U != (base->INTENSET & USART_INTENSET_TXIDLEEN_MASK)) && (0U != (base->INTSTAT & USART_INTSTAT_TXIDLE_MASK)))
{
/* Set txState to idle only when all data has been sent out to bus. */
handle->txState = (uint8_t)kUSART_TxIdle;
/* Disable tx idle interrupt */
base->INTENCLR = USART_INTENCLR_TXIDLECLR_MASK;
/* Trigger callback. */
if (handle->callback != NULL)
{
handle->callback(base, handle, kStatus_USART_TxIdle, handle->userData);
}
}
/* ring buffer is not used */
if (NULL == handle->rxRingBuffer)
{
tmpsize = handle->rxDataSize;
/* restore if rx transfer ends and rxLevel is different from default value */
if ((tmpsize == 0U) && (USART_FIFOTRIG_RXLVL_GET(base) != handle->rxWatermark))
{
base->FIFOTRIG =
(base->FIFOTRIG & (~USART_FIFOTRIG_RXLVL_MASK)) | USART_FIFOTRIG_RXLVL(handle->rxWatermark);
}
/* decrease level if rx transfer is bellow */
if ((tmpsize != 0U) && (tmpsize < (USART_FIFOTRIG_RXLVL_GET(base) + 1U)))
{
base->FIFOTRIG = (base->FIFOTRIG & (~USART_FIFOTRIG_RXLVL_MASK)) | (USART_FIFOTRIG_RXLVL(tmpsize - 1U));
}
}
}
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Examples/MCU-LINK/fsl_usart.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 11,246 |
```c
/*your_sha256_hash--------------
* MDK Middleware - Component ::USB:Device
*your_sha256_hash--------------
* Name: USBD_User_CustomClass_0.c
* Purpose: USB Device Custom Class User module
* Rev.: V6.7.3
*your_sha256_hash------------*/
/*
* USBD_User_CustomClass_0.c is a code template for the Custom Class 0
* class request handling. It allows user to handle all Custom Class class
* requests.
*
* Uncomment "Example code" lines to see example that receives data on
* Endpoint 1 OUT and echoes it back on Endpoint 1 IN.
* To try the example you also have to enable Bulk Endpoint 1 IN/OUT in Custom
* Class configuration in USBD_Config_CustomClass_0.h file.
*/
/**
* \addtogroup usbd_custom_classFunctions
*
*/
//! [code_USBD_User_CustomClass]
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
#include "cmsis_os2.h"
#define osObjectsExternal
#include "osObjects.h"
#include "rl_usb.h"
#include "Driver_USBD.h"
#include "DAP_config.h"
#include "DAP.h"
static volatile uint16_t USB_RequestIndexI; // Request Index In
static volatile uint16_t USB_RequestIndexO; // Request Index Out
static volatile uint16_t USB_RequestCountI; // Request Count In
static volatile uint16_t USB_RequestCountO; // Request Count Out
static volatile uint8_t USB_RequestIdle; // Request Idle Flag
static volatile uint16_t USB_ResponseIndexI; // Response Index In
static volatile uint16_t USB_ResponseIndexO; // Response Index Out
static volatile uint16_t USB_ResponseCountI; // Response Count In
static volatile uint16_t USB_ResponseCountO; // Response Count Out
static volatile uint8_t USB_ResponseIdle; // Response Idle Flag
static uint8_t USB_Request [DAP_PACKET_COUNT][DAP_PACKET_SIZE] __attribute__((section(".bss.USB_IO"))); // Request Buffer
static uint8_t USB_Response[DAP_PACKET_COUNT][DAP_PACKET_SIZE] __attribute__((section(".bss.USB_IO"))); // Response Buffer
static uint16_t USB_RespSize[DAP_PACKET_COUNT]; // Response Size
// \brief Callback function called during USBD_Initialize to initialize the USB Custom class instance
void USBD_CustomClass0_Initialize (void) {
// Handle Custom Class Initialization
// Initialize variables
USB_RequestIndexI = 0U;
USB_RequestIndexO = 0U;
USB_RequestCountI = 0U;
USB_RequestCountO = 0U;
USB_RequestIdle = 1U;
USB_ResponseIndexI = 0U;
USB_ResponseIndexO = 0U;
USB_ResponseCountI = 0U;
USB_ResponseCountO = 0U;
USB_ResponseIdle = 1U;
}
// \brief Callback function called during USBD_Uninitialize to de-initialize the USB Custom class instance
void USBD_CustomClass0_Uninitialize (void) {
// Handle Custom Class De-initialization
}
// \brief Callback function called upon USB Bus Reset signaling
void USBD_CustomClass0_Reset (void) {
// Handle USB Bus Reset Event
}
// \brief Callback function called when Endpoint Start was requested (by activating interface or configuration)
// \param[in] ep_addr endpoint address.
void USBD_CustomClass0_EndpointStart (uint8_t ep_addr) {
// Start communication on Endpoint
if (ep_addr == USB_ENDPOINT_OUT(1U)) {
USB_RequestIdle = 0U;
USBD_EndpointRead(0U, USB_ENDPOINT_OUT(1U), USB_Request[0], DAP_PACKET_SIZE);
}
}
// \brief Callback function called when Endpoint Stop was requested (by de-activating interface or activating configuration 0)
// \param[in] ep_addr endpoint address.
void USBD_CustomClass0_EndpointStop (uint8_t ep_addr) {
// Handle Endpoint communication stopped
(void)ep_addr;
}
// \brief Callback function called when Custom Class 0 received SETUP PACKET on Control Endpoint 0
// (this callback will be called only for Class Requests (USB_REQUEST_CLASS) if it was not processed
// previously by Device callback)
// \param[in] setup_packet pointer to received setup packet.
// \param[out] buf pointer to data buffer used for data stage requested by setup packet.
// \param[out] len pointer to number of data bytes in data stage requested by setup packet.
// \return usbdRequestStatus enumerator value indicating the function execution status
// \return usbdRequestNotProcessed:request was not processed; processing will be done by USB library
// \return usbdRequestOK: request was processed successfully (send Zero-Length Packet if no data stage)
// \return usbdRequestStall: request was processed but is not supported (stall Endpoint 0)
usbdRequestStatus USBD_CustomClass0_Endpoint0_SetupPacketReceived (const USB_SETUP_PACKET *setup_packet, uint8_t **buf, uint32_t *len) {
(void)setup_packet;
(void)buf;
(void)len;
switch (setup_packet->bmRequestType.Recipient) {
case USB_REQUEST_TO_DEVICE:
break;
case USB_REQUEST_TO_INTERFACE:
break;
case USB_REQUEST_TO_ENDPOINT:
break;
default:
break;
}
return usbdRequestNotProcessed;
}
// \brief Callback function called when SETUP PACKET was processed by USB library
// (this callback will be called only for Class Requests (USB_REQUEST_CLASS) if it was not processed
// previously by Device callback nor by Custom Class callback)
// \param[in] setup_packet pointer to processed setup packet.
void USBD_CustomClass0_Endpoint0_SetupPacketProcessed (const USB_SETUP_PACKET *setup_packet) {
(void)setup_packet;
switch (setup_packet->bmRequestType.Recipient) {
case USB_REQUEST_TO_DEVICE:
break;
case USB_REQUEST_TO_INTERFACE:
break;
case USB_REQUEST_TO_ENDPOINT:
break;
default:
break;
}
}
// \brief Callback function called when Custom Class 0 received OUT DATA on Control Endpoint 0
// (this callback will be called only for Class Requests (USB_REQUEST_CLASS) if it was not processed
// previously by Device callback)
// \param[in] len number of received data bytes.
// \return usbdRequestStatus enumerator value indicating the function execution status
// \return usbdRequestNotProcessed:request was not processed; processing will be done by USB library
// \return usbdRequestOK: request was processed successfully (send Zero-Length Packet)
// \return usbdRequestStall: request was processed but is not supported (stall Endpoint 0)
// \return usbdRequestNAK: request was processed but the device is busy (return NAK)
usbdRequestStatus USBD_CustomClass0_Endpoint0_OutDataReceived (uint32_t len) {
(void)len;
return usbdRequestNotProcessed;
}
// \brief Callback function called when Custom Class 0 sent IN DATA on Control Endpoint 0
// (this callback will be called only for Class Requests (USB_REQUEST_CLASS) if it was not processed
// previously by Device callback)
// \param[in] len number of sent data bytes.
// \return usbdRequestStatus enumerator value indicating the function execution status
// \return usbdRequestNotProcessed:request was not processed; processing will be done by USB library
// \return usbdRequestOK: request was processed successfully (return ACK)
// \return usbdRequestStall: request was processed but is not supported (stall Endpoint 0)
// \return usbdRequestNAK: request was processed but the device is busy (return NAK)
usbdRequestStatus USBD_CustomClass0_Endpoint0_InDataSent (uint32_t len) {
(void)len;
return usbdRequestNotProcessed;
}
// \brief Callback function called when DATA was sent or received on Endpoint n
// \param[in] event event on Endpoint:
// - ARM_USBD_EVENT_OUT = data OUT received
// - ARM_USBD_EVENT_IN = data IN sent
void USBD_CustomClass0_Endpoint1_Event (uint32_t event) {
// Handle Endpoint 1 events
uint32_t n;
if (event & ARM_USBD_EVENT_OUT) {
n = USBD_EndpointReadGetResult(0U, USB_ENDPOINT_OUT(1U));
if (n != 0U) {
if (USB_Request[USB_RequestIndexI][0] == ID_DAP_TransferAbort) {
DAP_TransferAbort = 1U;
} else {
USB_RequestIndexI++;
if (USB_RequestIndexI == DAP_PACKET_COUNT) {
USB_RequestIndexI = 0U;
}
USB_RequestCountI++;
osThreadFlagsSet(DAP_ThreadId, 0x01);
}
}
// Start reception of next request packet
if ((uint16_t)(USB_RequestCountI - USB_RequestCountO) != DAP_PACKET_COUNT) {
USBD_EndpointRead(0U, USB_ENDPOINT_OUT(1U), USB_Request[USB_RequestIndexI], DAP_PACKET_SIZE);
} else {
USB_RequestIdle = 1U;
}
}
if (event & ARM_USBD_EVENT_IN) {
if (USB_ResponseCountI != USB_ResponseCountO) {
// Load data from response buffer to be sent back
USBD_EndpointWrite(0U, USB_ENDPOINT_IN(1U), USB_Response[USB_ResponseIndexO], USB_RespSize[USB_ResponseIndexO]);
USB_ResponseIndexO++;
if (USB_ResponseIndexO == DAP_PACKET_COUNT) {
USB_ResponseIndexO = 0U;
}
USB_ResponseCountO++;
} else {
USB_ResponseIdle = 1U;
}
}
}
void USBD_CustomClass0_Endpoint2_Event (uint32_t event) {
// Handle Endpoint 2 events
if (event & ARM_USBD_EVENT_IN) {
SWO_TransferComplete();
}
}
void USBD_CustomClass0_Endpoint3_Event (uint32_t event) {
// Handle Endpoint 3 events
(void)event;
}
void USBD_CustomClass0_Endpoint4_Event (uint32_t event) {
// Handle Endpoint 4 events
(void)event;
}
void USBD_CustomClass0_Endpoint5_Event (uint32_t event) {
// Handle Endpoint 5 events
(void)event;
}
void USBD_CustomClass0_Endpoint6_Event (uint32_t event) {
// Handle Endpoint 6 events
(void)event;
}
void USBD_CustomClass0_Endpoint7_Event (uint32_t event) {
// Handle Endpoint 7 events
(void)event;
}
void USBD_CustomClass0_Endpoint8_Event (uint32_t event) {
// Handle Endpoint 8 events
(void)event;
}
void USBD_CustomClass0_Endpoint9_Event (uint32_t event) {
// Handle Endpoint 9 events
(void)event;
}
void USBD_CustomClass0_Endpoint10_Event (uint32_t event) {
// Handle Endpoint 10 events
(void)event;
}
void USBD_CustomClass0_Endpoint11_Event (uint32_t event) {
// Handle Endpoint 11 events
(void)event;
}
void USBD_CustomClass0_Endpoint12_Event (uint32_t event) {
// Handle Endpoint 12 events
(void)event;
}
void USBD_CustomClass0_Endpoint13_Event (uint32_t event) {
// Handle Endpoint 13 events
(void)event;
}
void USBD_CustomClass0_Endpoint14_Event (uint32_t event) {
// Handle Endpoint 14 events
(void)event;
}
void USBD_CustomClass0_Endpoint15_Event (uint32_t event) {
// Handle Endpoint 15 events
(void)event;
}
// DAP Thread.
__NO_RETURN void DAP_Thread (void *argument) {
uint32_t flags;
uint32_t n;
(void) argument;
for (;;) {
osThreadFlagsWait(0x81U, osFlagsWaitAny, osWaitForever);
// Process pending requests
while (USB_RequestCountI != USB_RequestCountO) {
// Handle Queue Commands
n = USB_RequestIndexO;
while (USB_Request[n][0] == ID_DAP_QueueCommands) {
USB_Request[n][0] = ID_DAP_ExecuteCommands;
n++;
if (n == DAP_PACKET_COUNT) {
n = 0U;
}
if (n == USB_RequestIndexI) {
flags = osThreadFlagsWait(0x81U, osFlagsWaitAny, osWaitForever);
if (flags & 0x80U) {
break;
}
}
}
// Execute DAP Command (process request and prepare response)
USB_RespSize[USB_ResponseIndexI] =
(uint16_t)DAP_ExecuteCommand(USB_Request[USB_RequestIndexO], USB_Response[USB_ResponseIndexI]);
// Update Request Index and Count
USB_RequestIndexO++;
if (USB_RequestIndexO == DAP_PACKET_COUNT) {
USB_RequestIndexO = 0U;
}
USB_RequestCountO++;
if (USB_RequestIdle) {
if ((uint16_t)(USB_RequestCountI - USB_RequestCountO) != DAP_PACKET_COUNT) {
USB_RequestIdle = 0U;
USBD_EndpointRead(0U, USB_ENDPOINT_OUT(1U), USB_Request[USB_RequestIndexI], DAP_PACKET_SIZE);
}
}
// Update Response Index and Count
USB_ResponseIndexI++;
if (USB_ResponseIndexI == DAP_PACKET_COUNT) {
USB_ResponseIndexI = 0U;
}
USB_ResponseCountI++;
if (USB_ResponseIdle) {
if (USB_ResponseCountI != USB_ResponseCountO) {
// Load data from response buffer to be sent back
n = USB_ResponseIndexO++;
if (USB_ResponseIndexO == DAP_PACKET_COUNT) {
USB_ResponseIndexO = 0U;
}
USB_ResponseCountO++;
USB_ResponseIdle = 0U;
USBD_EndpointWrite(0U, USB_ENDPOINT_IN(1U), USB_Response[n], USB_RespSize[n]);
}
}
}
}
}
// SWO Data Queue Transfer
// buf: pointer to buffer with data
// num: number of bytes to transfer
void SWO_QueueTransfer (uint8_t *buf, uint32_t num) {
USBD_EndpointWrite(0U, USB_ENDPOINT_IN(2U), buf, num);
}
// SWO Data Abort Transfer
void SWO_AbortTransfer (void) {
USBD_EndpointAbort(0U, USB_ENDPOINT_IN(2U));
}
//! [code_USBD_User_CustomClass]
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Examples/MCU-LINK/USBD_User_CustomClass_0.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 3,341 |
```objective-c
/***********************************************************************************************************************
* This file was generated by the MCUXpresso Config Tools. Any manual edits made to this file
* will be overwritten if the respective MCUXpresso Config Tools is used to update this file.
**********************************************************************************************************************/
#ifndef _CLOCK_CONFIG_H_
#define _CLOCK_CONFIG_H_
#include "fsl_common.h"
/*******************************************************************************
* Definitions
******************************************************************************/
#define BOARD_XTAL0_CLK_HZ 16000000U /*!< Board xtal frequency in Hz */
#define BOARD_XTAL32K_CLK_HZ 32768U /*!< Board xtal32K frequency in Hz */
/*******************************************************************************
************************ BOARD_InitBootClocks function ************************
******************************************************************************/
#if defined(__cplusplus)
extern "C" {
#endif /* __cplusplus*/
/*!
* @brief This function executes default configuration of clocks.
*
*/
void BOARD_InitBootClocks(void);
#if defined(__cplusplus)
}
#endif /* __cplusplus*/
/*******************************************************************************
********************** Configuration BOARD_BootClockRUN ***********************
******************************************************************************/
/*******************************************************************************
* Definitions for BOARD_BootClockRUN configuration
******************************************************************************/
#define BOARD_BOOTCLOCKRUN_CORE_CLOCK 150000000U /*!< Core clock frequency: 150000000Hz */
/*******************************************************************************
* API for BOARD_BootClockRUN configuration
******************************************************************************/
#if defined(__cplusplus)
extern "C" {
#endif /* __cplusplus*/
/*!
* @brief This function executes configuration of clocks.
*
*/
void BOARD_BootClockRUN(void);
#if defined(__cplusplus)
}
#endif /* __cplusplus*/
#endif /* _CLOCK_CONFIG_H_ */
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Examples/MCU-LINK/board/clock_config.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 300 |
```c
/***********************************************************************************************************************
* This file was generated by the MCUXpresso Config Tools. Any manual edits made to this file
* will be overwritten if the respective MCUXpresso Config Tools is used to update this file.
**********************************************************************************************************************/
/* clang-format off */
/* TEXT BELOW IS USED AS SETTING FOR TOOLS *************************************
!!GlobalInfo
product: Peripherals v9.0
processor: LPC55S69
package_id: LPC55S69JBD64
mcu_data: ksdk2_0
processor_version: 9.0.3
functionalGroups:
- name: BOARD_InitPeripherals
UUID: 85f4cd0c-3b58-4e23-a413-239f6952f139
called_from_default_init: true
selectedCore: cm33_core0
* BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS **********/
/* TEXT BELOW IS USED AS SETTING FOR TOOLS *************************************
component:
- type: 'system'
- type_id: 'system_54b53072540eeeb8f8e9343e71f28176'
- global_system_definitions:
- user_definitions: ''
- user_includes: ''
* BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS **********/
/* clang-format on */
/***********************************************************************************************************************
* Included files
**********************************************************************************************************************/
#include "peripherals.h"
/***********************************************************************************************************************
* BOARD_InitPeripherals functional group
**********************************************************************************************************************/
/***********************************************************************************************************************
* NVIC initialization code
**********************************************************************************************************************/
/* clang-format off */
/* TEXT BELOW IS USED AS SETTING FOR TOOLS *************************************
instance:
- name: 'NVIC'
- type: 'nvic'
- mode: 'general'
- custom_name_enabled: 'false'
- type_id: 'nvic_57b5eef3774cc60acaede6f5b8bddc67'
- functional_group: 'BOARD_InitPeripherals'
- peripheral: 'NVIC'
- config_sets:
- nvic:
- interrupt_table: []
- interrupts: []
* BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS **********/
/* clang-format on */
/* Empty initialization function (commented out)
static void NVIC_init(void) {
} */
/***********************************************************************************************************************
* Initialization functions
**********************************************************************************************************************/
void BOARD_InitPeripherals(void)
{
/* Initialize components */
}
/***********************************************************************************************************************
* BOARD_InitBootPeripherals function
**********************************************************************************************************************/
void BOARD_InitBootPeripherals(void)
{
BOARD_InitPeripherals();
}
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Examples/MCU-LINK/board/peripherals.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 527 |
```c
/***********************************************************************************************************************
* This file was generated by the MCUXpresso Config Tools. Any manual edits made to this file
* will be overwritten if the respective MCUXpresso Config Tools is used to update this file.
**********************************************************************************************************************/
/* clang-format off */
/*
* TEXT BELOW IS USED AS SETTING FOR TOOLS *************************************
!!GlobalInfo
product: Pins v9.0
processor: LPC55S69
package_id: LPC55S69JBD64
mcu_data: ksdk2_0
processor_version: 9.0.3
pin_labels:
- {pin_num: '36', pin_signal: PIO0_0/FC3_SCK/CTIMER0_MAT0/SCT_GPI0/SD1_CARD_INT_N/SECURE_GPIO0_0/ACMP0_A, label: _DBGIF_TCK_SWCLK, identifier: DBGIF_TCK_SWCLK}
- {pin_num: '2', pin_signal: PIO0_1/FC3_CTS_SDA_SSEL0/CT_INP0/SCT_GPI1/SD1_CLK/CMP0_OUT/SECURE_GPIO0_1, label: _DBGIF_TDI, identifier: DBGIF_TDI}
- {pin_num: '52', pin_signal: PIO0_2/FC3_TXD_SCL_MISO_WS/CT_INP1/SCT0_OUT0/SCT_GPI2/SECURE_GPIO0_2, label: _DBGIF_TMS_SWDIO, identifier: DBGIF_TMS_SWDIO}
- {pin_num: '44', pin_signal: PIO0_28/FC0_SCK/SD1_CMD/CT_INP11/SCT0_OUT7/USB0_OVERCURRENTN/PLU_OUT1/SECURE_GPIO0_28, label: _DBGIF_TMS_SWDIO_TXEN, identifier: DBGIF_TMS_SWDIO_TXEN}
- {pin_num: '58', pin_signal: PIO0_19/FC4_RTS_SCL_SSEL1/UTICK_CAP0/CTIMER0_MAT2/SCT0_OUT2/FC7_TXD_SCL_MISO_WS/PLU_IN4/SECURE_GPIO0_19, label: _DBGIF_RESET, identifier: DBG_IF_RESET;DBGIF_RESET}
- {pin_num: '46', pin_signal: PIO0_13/FC1_CTS_SDA_SSEL0/UTICK_CAP0/CT_INP0/SCT_GPI0/FC1_RXD_SDA_MOSI_DATA/PLU_IN0/SECURE_GPIO0_13, label: _DBGIF_RESET_TXEN, identifier: DBG_IF_RESET_TXEN;DBGIF_RESET_TXEN}
- {pin_num: '53', pin_signal: PIO0_3/FC3_RXD_SDA_MOSI_DATA/CTIMER0_MAT1/SCT0_OUT1/SCT_GPI3/SECURE_GPIO0_3, label: _DBGIF_TDO_SWO, identifier: DBG_IF_TDO_SWO;DBGIF_TDO_SWO}
- {pin_num: '45', pin_signal: PIO0_24/FC0_RXD_SDA_MOSI_DATA/SD0_D0/CT_INP8/SCT_GPI0/SECURE_GPIO0_24, label: _FC0_TARGET_RXD, identifier: FC0_TARGET_RXD}
- {pin_num: '51', pin_signal: PIO0_25/FC0_TXD_SCL_MISO_WS/SD0_D1/CT_INP9/SCT_GPI1/SECURE_GPIO0_25, label: _FC0_TARGET_TXD, identifier: FC0_TARGET_TXD}
- {pin_num: '56', pin_signal: PIO0_5/FC4_RXD_SDA_MOSI_DATA/CTIMER3_MAT0/SCT_GPI5/FC3_RTS_SCL_SSEL1/MCLK/SECURE_GPIO0_5, label: _LED1, identifier: LED1}
* BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS ***********
*/
/* clang-format on */
#include "fsl_common.h"
#include "fsl_gpio.h"
#include "pin_mux.h"
/* FUNCTION ************************************************************************************************************
*
* Function Name : BOARD_InitBootPins
* Description : Calls initialization functions.
*
* END ****************************************************************************************************************/
void BOARD_InitBootPins(void)
{
MCU_LINK_InitPins();
}
/* clang-format off */
/*
* TEXT BELOW IS USED AS SETTING FOR TOOLS *************************************
MCU_LINK_InitPins:
- options: {callFromInitBoot: 'true', prefix: '', coreID: cm33_core0, enableClock: 'true'}
- pin_list:
- {pin_num: '36', peripheral: GPIO, signal: 'PIO0, 0', pin_signal: PIO0_0/FC3_SCK/CTIMER0_MAT0/SCT_GPI0/SD1_CARD_INT_N/SECURE_GPIO0_0/ACMP0_A, direction: INPUT,
slew_rate: fast}
- {pin_num: '2', peripheral: GPIO, signal: 'PIO0, 1', pin_signal: PIO0_1/FC3_CTS_SDA_SSEL0/CT_INP0/SCT_GPI1/SD1_CLK/CMP0_OUT/SECURE_GPIO0_1, direction: INPUT, slew_rate: fast}
- {pin_num: '52', peripheral: GPIO, signal: 'PIO0, 2', pin_signal: PIO0_2/FC3_TXD_SCL_MISO_WS/CT_INP1/SCT0_OUT0/SCT_GPI2/SECURE_GPIO0_2, direction: INPUT, mode: inactive,
slew_rate: fast}
- {pin_num: '44', peripheral: GPIO, signal: 'PIO0, 28', pin_signal: PIO0_28/FC0_SCK/SD1_CMD/CT_INP11/SCT0_OUT7/USB0_OVERCURRENTN/PLU_OUT1/SECURE_GPIO0_28, direction: OUTPUT,
gpio_init_state: 'false', slew_rate: fast}
- {pin_num: '58', peripheral: GPIO, signal: 'PIO0, 19', pin_signal: PIO0_19/FC4_RTS_SCL_SSEL1/UTICK_CAP0/CTIMER0_MAT2/SCT0_OUT2/FC7_TXD_SCL_MISO_WS/PLU_IN4/SECURE_GPIO0_19,
identifier: DBGIF_RESET, direction: INPUT, slew_rate: fast}
- {pin_num: '46', peripheral: GPIO, signal: 'PIO0, 13', pin_signal: PIO0_13/FC1_CTS_SDA_SSEL0/UTICK_CAP0/CT_INP0/SCT_GPI0/FC1_RXD_SDA_MOSI_DATA/PLU_IN0/SECURE_GPIO0_13,
identifier: DBGIF_RESET_TXEN, direction: OUTPUT, gpio_init_state: 'false'}
- {pin_num: '53', peripheral: FLEXCOMM3, signal: RXD_SDA_MOSI_DATA, pin_signal: PIO0_3/FC3_RXD_SDA_MOSI_DATA/CTIMER0_MAT1/SCT0_OUT1/SCT_GPI3/SECURE_GPIO0_3, identifier: DBGIF_TDO_SWO,
slew_rate: fast}
- {pin_num: '45', peripheral: FLEXCOMM0, signal: RXD_SDA_MOSI_DATA, pin_signal: PIO0_24/FC0_RXD_SDA_MOSI_DATA/SD0_D0/CT_INP8/SCT_GPI0/SECURE_GPIO0_24, slew_rate: fast}
- {pin_num: '51', peripheral: FLEXCOMM0, signal: TXD_SCL_MISO_WS, pin_signal: PIO0_25/FC0_TXD_SCL_MISO_WS/SD0_D1/CT_INP9/SCT_GPI1/SECURE_GPIO0_25, slew_rate: fast}
- {pin_num: '23', peripheral: USBHSH, signal: USB_DP, pin_signal: USB1_DP}
- {pin_num: '24', peripheral: USBHSH, signal: USB_DM, pin_signal: USB1_DM}
- {pin_num: '25', peripheral: USBHSH, signal: USB_VBUS, pin_signal: USB1_VBUS}
- {pin_num: '22', peripheral: USBHSH, signal: USB_VSS, pin_signal: USB1_VSS22}
- {pin_num: '26', peripheral: USBHSH, signal: USB_VSS, pin_signal: USB1_VSS26}
- {pin_num: '41', peripheral: USBHSH, signal: USB_PORTPWRN, pin_signal: PIO1_2/CTIMER0_MAT3/SCT_GPI6/HS_SPI_SCK/USB1_PORTPWRN/PLU_OUT5}
- {pin_num: '56', peripheral: GPIO, signal: 'PIO0, 5', pin_signal: PIO0_5/FC4_RXD_SDA_MOSI_DATA/CTIMER3_MAT0/SCT_GPI5/FC3_RTS_SCL_SSEL1/MCLK/SECURE_GPIO0_5, direction: OUTPUT,
gpio_init_state: 'true', mode: pullUp}
* BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS ***********
*/
/* clang-format on */
/* FUNCTION ************************************************************************************************************
*
* Function Name : MCU_LINK_InitPins
* Description : Configures pin routing and optionally pin electrical features.
*
* END ****************************************************************************************************************/
/* Function assigned for the Cortex-M33 (Core #0) */
void MCU_LINK_InitPins(void)
{
/* Enables the clock for the I/O controller.: Enable Clock. */
CLOCK_EnableClock(kCLOCK_Iocon);
/* Enables the clock for the GPIO0 module */
CLOCK_EnableClock(kCLOCK_Gpio0);
gpio_pin_config_t DBGIF_TCK_SWCLK_config = {
.pinDirection = kGPIO_DigitalInput,
.outputLogic = 0U
};
/* Initialize GPIO functionality on pin PIO0_0 (pin 36) */
GPIO_PinInit(DBGIF_TCK_SWCLK_GPIO, DBGIF_TCK_SWCLK_PORT, DBGIF_TCK_SWCLK_PIN, &DBGIF_TCK_SWCLK_config);
gpio_pin_config_t DBGIF_TDI_config = {
.pinDirection = kGPIO_DigitalInput,
.outputLogic = 0U
};
/* Initialize GPIO functionality on pin PIO0_1 (pin 2) */
GPIO_PinInit(DBGIF_TDI_GPIO, DBGIF_TDI_PORT, DBGIF_TDI_PIN, &DBGIF_TDI_config);
gpio_pin_config_t DBGIF_TMS_SWDIO_config = {
.pinDirection = kGPIO_DigitalInput,
.outputLogic = 0U
};
/* Initialize GPIO functionality on pin PIO0_2 (pin 52) */
GPIO_PinInit(DBGIF_TMS_SWDIO_GPIO, DBGIF_TMS_SWDIO_PORT, DBGIF_TMS_SWDIO_PIN, &DBGIF_TMS_SWDIO_config);
gpio_pin_config_t LED1_config = {
.pinDirection = kGPIO_DigitalOutput,
.outputLogic = 1U
};
/* Initialize GPIO functionality on pin PIO0_5 (pin 56) */
GPIO_PinInit(LED1_GPIO, LED1_PORT, LED1_PIN, &LED1_config);
gpio_pin_config_t DBGIF_RESET_TXEN_config = {
.pinDirection = kGPIO_DigitalOutput,
.outputLogic = 0U
};
/* Initialize GPIO functionality on pin PIO0_13 (pin 46) */
GPIO_PinInit(DBGIF_RESET_TXEN_GPIO, DBGIF_RESET_TXEN_PORT, DBGIF_RESET_TXEN_PIN, &DBGIF_RESET_TXEN_config);
gpio_pin_config_t DBGIF_RESET_config = {
.pinDirection = kGPIO_DigitalInput,
.outputLogic = 0U
};
/* Initialize GPIO functionality on pin PIO0_19 (pin 58) */
GPIO_PinInit(DBGIF_RESET_GPIO, DBGIF_RESET_PORT, DBGIF_RESET_PIN, &DBGIF_RESET_config);
gpio_pin_config_t DBGIF_TMS_SWDIO_TXEN_config = {
.pinDirection = kGPIO_DigitalOutput,
.outputLogic = 0U
};
/* Initialize GPIO functionality on pin PIO0_28 (pin 44) */
GPIO_PinInit(DBGIF_TMS_SWDIO_TXEN_GPIO, DBGIF_TMS_SWDIO_TXEN_PORT, DBGIF_TMS_SWDIO_TXEN_PIN, &DBGIF_TMS_SWDIO_TXEN_config);
IOCON->PIO[0][0] = ((IOCON->PIO[0][0] &
/* Mask bits to zero which are setting */
(~(IOCON_PIO_FUNC_MASK | IOCON_PIO_SLEW_MASK | IOCON_PIO_DIGIMODE_MASK)))
/* Selects pin function.
* : PORT00 (pin 36) is configured as PIO0_0. */
| IOCON_PIO_FUNC(PIO0_0_FUNC_ALT0)
/* Driver slew rate.
* : Fast-mode, output slew rate is faster.
* Refer to the appropriate specific device data sheet for details. */
| IOCON_PIO_SLEW(PIO0_0_SLEW_FAST)
/* Select Digital mode.
* : Enable Digital mode.
* Digital input is enabled. */
| IOCON_PIO_DIGIMODE(PIO0_0_DIGIMODE_DIGITAL));
IOCON->PIO[0][1] = ((IOCON->PIO[0][1] &
/* Mask bits to zero which are setting */
(~(IOCON_PIO_FUNC_MASK | IOCON_PIO_SLEW_MASK | IOCON_PIO_DIGIMODE_MASK)))
/* Selects pin function.
* : PORT01 (pin 2) is configured as PIO0_1. */
| IOCON_PIO_FUNC(PIO0_1_FUNC_ALT0)
/* Driver slew rate.
* : Fast-mode, output slew rate is faster.
* Refer to the appropriate specific device data sheet for details. */
| IOCON_PIO_SLEW(PIO0_1_SLEW_FAST)
/* Select Digital mode.
* : Enable Digital mode.
* Digital input is enabled. */
| IOCON_PIO_DIGIMODE(PIO0_1_DIGIMODE_DIGITAL));
IOCON->PIO[0][13] = ((IOCON->PIO[0][13] &
/* Mask bits to zero which are setting */
(~(IOCON_PIO_FUNC_MASK | IOCON_PIO_DIGIMODE_MASK)))
/* Selects pin function.
* : PORT013 (pin 46) is configured as PIO0_13. */
| IOCON_PIO_FUNC(PIO0_13_FUNC_ALT0)
/* Select Digital mode.
* : Enable Digital mode.
* Digital input is enabled. */
| IOCON_PIO_DIGIMODE(PIO0_13_DIGIMODE_DIGITAL));
IOCON->PIO[0][19] = ((IOCON->PIO[0][19] &
/* Mask bits to zero which are setting */
(~(IOCON_PIO_FUNC_MASK | IOCON_PIO_SLEW_MASK | IOCON_PIO_DIGIMODE_MASK)))
/* Selects pin function.
* : PORT019 (pin 58) is configured as PIO0_19. */
| IOCON_PIO_FUNC(PIO0_19_FUNC_ALT0)
/* Driver slew rate.
* : Fast-mode, output slew rate is faster.
* Refer to the appropriate specific device data sheet for details. */
| IOCON_PIO_SLEW(PIO0_19_SLEW_FAST)
/* Select Digital mode.
* : Enable Digital mode.
* Digital input is enabled. */
| IOCON_PIO_DIGIMODE(PIO0_19_DIGIMODE_DIGITAL));
IOCON->PIO[0][2] = ((IOCON->PIO[0][2] &
/* Mask bits to zero which are setting */
(~(IOCON_PIO_FUNC_MASK | IOCON_PIO_MODE_MASK | IOCON_PIO_SLEW_MASK | IOCON_PIO_DIGIMODE_MASK)))
/* Selects pin function.
* : PORT02 (pin 52) is configured as PIO0_2. */
| IOCON_PIO_FUNC(PIO0_2_FUNC_ALT0)
/* Selects function mode (on-chip pull-up/pull-down resistor control).
* : Inactive.
* Inactive (no pull-down/pull-up resistor enabled). */
| IOCON_PIO_MODE(PIO0_2_MODE_INACTIVE)
/* Driver slew rate.
* : Fast-mode, output slew rate is faster.
* Refer to the appropriate specific device data sheet for details. */
| IOCON_PIO_SLEW(PIO0_2_SLEW_FAST)
/* Select Digital mode.
* : Enable Digital mode.
* Digital input is enabled. */
| IOCON_PIO_DIGIMODE(PIO0_2_DIGIMODE_DIGITAL));
IOCON->PIO[0][24] = ((IOCON->PIO[0][24] &
/* Mask bits to zero which are setting */
(~(IOCON_PIO_FUNC_MASK | IOCON_PIO_SLEW_MASK | IOCON_PIO_DIGIMODE_MASK)))
/* Selects pin function.
* : PORT024 (pin 45) is configured as FC0_RXD_SDA_MOSI_DATA. */
| IOCON_PIO_FUNC(PIO0_24_FUNC_ALT1)
/* Driver slew rate.
* : Fast-mode, output slew rate is faster.
* Refer to the appropriate specific device data sheet for details. */
| IOCON_PIO_SLEW(PIO0_24_SLEW_FAST)
/* Select Digital mode.
* : Enable Digital mode.
* Digital input is enabled. */
| IOCON_PIO_DIGIMODE(PIO0_24_DIGIMODE_DIGITAL));
IOCON->PIO[0][25] = ((IOCON->PIO[0][25] &
/* Mask bits to zero which are setting */
(~(IOCON_PIO_FUNC_MASK | IOCON_PIO_SLEW_MASK | IOCON_PIO_DIGIMODE_MASK)))
/* Selects pin function.
* : PORT025 (pin 51) is configured as FC0_TXD_SCL_MISO_WS. */
| IOCON_PIO_FUNC(PIO0_25_FUNC_ALT1)
/* Driver slew rate.
* : Fast-mode, output slew rate is faster.
* Refer to the appropriate specific device data sheet for details. */
| IOCON_PIO_SLEW(PIO0_25_SLEW_FAST)
/* Select Digital mode.
* : Enable Digital mode.
* Digital input is enabled. */
| IOCON_PIO_DIGIMODE(PIO0_25_DIGIMODE_DIGITAL));
IOCON->PIO[0][28] = ((IOCON->PIO[0][28] &
/* Mask bits to zero which are setting */
(~(IOCON_PIO_FUNC_MASK | IOCON_PIO_SLEW_MASK | IOCON_PIO_DIGIMODE_MASK)))
/* Selects pin function.
* : PORT028 (pin 44) is configured as PIO0_28. */
| IOCON_PIO_FUNC(PIO0_28_FUNC_ALT0)
/* Driver slew rate.
* : Fast-mode, output slew rate is faster.
* Refer to the appropriate specific device data sheet for details. */
| IOCON_PIO_SLEW(PIO0_28_SLEW_FAST)
/* Select Digital mode.
* : Enable Digital mode.
* Digital input is enabled. */
| IOCON_PIO_DIGIMODE(PIO0_28_DIGIMODE_DIGITAL));
IOCON->PIO[0][3] = ((IOCON->PIO[0][3] &
/* Mask bits to zero which are setting */
(~(IOCON_PIO_FUNC_MASK | IOCON_PIO_SLEW_MASK | IOCON_PIO_DIGIMODE_MASK)))
/* Selects pin function.
* : PORT03 (pin 53) is configured as FC3_RXD_SDA_MOSI_DATA. */
| IOCON_PIO_FUNC(PIO0_3_FUNC_ALT1)
/* Driver slew rate.
* : Fast-mode, output slew rate is faster.
* Refer to the appropriate specific device data sheet for details. */
| IOCON_PIO_SLEW(PIO0_3_SLEW_FAST)
/* Select Digital mode.
* : Enable Digital mode.
* Digital input is enabled. */
| IOCON_PIO_DIGIMODE(PIO0_3_DIGIMODE_DIGITAL));
IOCON->PIO[0][5] = ((IOCON->PIO[0][5] &
/* Mask bits to zero which are setting */
(~(IOCON_PIO_FUNC_MASK | IOCON_PIO_MODE_MASK | IOCON_PIO_DIGIMODE_MASK)))
/* Selects pin function.
* : PORT05 (pin 56) is configured as PIO0_5. */
| IOCON_PIO_FUNC(PIO0_5_FUNC_ALT0)
/* Selects function mode (on-chip pull-up/pull-down resistor control).
* : Pull-up.
* Pull-up resistor enabled. */
| IOCON_PIO_MODE(PIO0_5_MODE_PULL_UP)
/* Select Digital mode.
* : Enable Digital mode.
* Digital input is enabled. */
| IOCON_PIO_DIGIMODE(PIO0_5_DIGIMODE_DIGITAL));
IOCON->PIO[1][2] = ((IOCON->PIO[1][2] &
/* Mask bits to zero which are setting */
(~(IOCON_PIO_FUNC_MASK | IOCON_PIO_DIGIMODE_MASK)))
/* Selects pin function.
* : PORT12 (pin 41) is configured as USB1_PORTPWRN. */
| IOCON_PIO_FUNC(PIO1_2_FUNC_ALT7)
/* Select Digital mode.
* : Enable Digital mode.
* Digital input is enabled. */
| IOCON_PIO_DIGIMODE(PIO1_2_DIGIMODE_DIGITAL));
}
/***********************************************************************************************************************
* EOF
**********************************************************************************************************************/
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Examples/MCU-LINK/board/pin_mux.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 4,827 |
```objective-c
/***********************************************************************************************************************
* This file was generated by the MCUXpresso Config Tools. Any manual edits made to this file
* will be overwritten if the respective MCUXpresso Config Tools is used to update this file.
**********************************************************************************************************************/
#ifndef _PIN_MUX_H_
#define _PIN_MUX_H_
/*!
* @addtogroup pin_mux
* @{
*/
/***********************************************************************************************************************
* API
**********************************************************************************************************************/
#if defined(__cplusplus)
extern "C" {
#endif
/*!
* @brief Calls initialization functions.
*
*/
void BOARD_InitBootPins(void);
/*!
* @brief Select Digital mode.: Enable Digital mode. Digital input is enabled. */
#define PIO0_0_DIGIMODE_DIGITAL 0x01u
/*!
* @brief Selects pin function.: Alternative connection 0. */
#define PIO0_0_FUNC_ALT0 0x00u
/*!
* @brief
* Driver slew rate.
* : Fast-mode, output slew rate is faster.
* Refer to the appropriate specific device data sheet for details.
*/
#define PIO0_0_SLEW_FAST 0x01u
/*!
* @brief Select Digital mode.: Enable Digital mode. Digital input is enabled. */
#define PIO0_13_DIGIMODE_DIGITAL 0x01u
/*!
* @brief Selects pin function.: Alternative connection 0. */
#define PIO0_13_FUNC_ALT0 0x00u
/*!
* @brief Select Digital mode.: Enable Digital mode. Digital input is enabled. */
#define PIO0_19_DIGIMODE_DIGITAL 0x01u
/*!
* @brief Selects pin function.: Alternative connection 0. */
#define PIO0_19_FUNC_ALT0 0x00u
/*!
* @brief
* Driver slew rate.
* : Fast-mode, output slew rate is faster.
* Refer to the appropriate specific device data sheet for details.
*/
#define PIO0_19_SLEW_FAST 0x01u
/*!
* @brief Select Digital mode.: Enable Digital mode. Digital input is enabled. */
#define PIO0_1_DIGIMODE_DIGITAL 0x01u
/*!
* @brief Selects pin function.: Alternative connection 0. */
#define PIO0_1_FUNC_ALT0 0x00u
/*!
* @brief
* Driver slew rate.
* : Fast-mode, output slew rate is faster.
* Refer to the appropriate specific device data sheet for details.
*/
#define PIO0_1_SLEW_FAST 0x01u
/*!
* @brief Select Digital mode.: Enable Digital mode. Digital input is enabled. */
#define PIO0_24_DIGIMODE_DIGITAL 0x01u
/*!
* @brief Selects pin function.: Alternative connection 1. */
#define PIO0_24_FUNC_ALT1 0x01u
/*!
* @brief
* Driver slew rate.
* : Fast-mode, output slew rate is faster.
* Refer to the appropriate specific device data sheet for details.
*/
#define PIO0_24_SLEW_FAST 0x01u
/*!
* @brief Select Digital mode.: Enable Digital mode. Digital input is enabled. */
#define PIO0_25_DIGIMODE_DIGITAL 0x01u
/*!
* @brief Selects pin function.: Alternative connection 1. */
#define PIO0_25_FUNC_ALT1 0x01u
/*!
* @brief
* Driver slew rate.
* : Fast-mode, output slew rate is faster.
* Refer to the appropriate specific device data sheet for details.
*/
#define PIO0_25_SLEW_FAST 0x01u
/*!
* @brief Select Digital mode.: Enable Digital mode. Digital input is enabled. */
#define PIO0_28_DIGIMODE_DIGITAL 0x01u
/*!
* @brief Selects pin function.: Alternative connection 0. */
#define PIO0_28_FUNC_ALT0 0x00u
/*!
* @brief
* Driver slew rate.
* : Fast-mode, output slew rate is faster.
* Refer to the appropriate specific device data sheet for details.
*/
#define PIO0_28_SLEW_FAST 0x01u
/*!
* @brief Select Digital mode.: Enable Digital mode. Digital input is enabled. */
#define PIO0_2_DIGIMODE_DIGITAL 0x01u
/*!
* @brief Selects pin function.: Alternative connection 0. */
#define PIO0_2_FUNC_ALT0 0x00u
/*!
* @brief
* Selects function mode (on-chip pull-up/pull-down resistor control).
* : Inactive.
* Inactive (no pull-down/pull-up resistor enabled).
*/
#define PIO0_2_MODE_INACTIVE 0x00u
/*!
* @brief
* Driver slew rate.
* : Fast-mode, output slew rate is faster.
* Refer to the appropriate specific device data sheet for details.
*/
#define PIO0_2_SLEW_FAST 0x01u
/*!
* @brief Select Digital mode.: Enable Digital mode. Digital input is enabled. */
#define PIO0_3_DIGIMODE_DIGITAL 0x01u
/*!
* @brief Selects pin function.: Alternative connection 1. */
#define PIO0_3_FUNC_ALT1 0x01u
/*!
* @brief
* Driver slew rate.
* : Fast-mode, output slew rate is faster.
* Refer to the appropriate specific device data sheet for details.
*/
#define PIO0_3_SLEW_FAST 0x01u
/*!
* @brief Select Digital mode.: Enable Digital mode. Digital input is enabled. */
#define PIO0_5_DIGIMODE_DIGITAL 0x01u
/*!
* @brief Selects pin function.: Alternative connection 0. */
#define PIO0_5_FUNC_ALT0 0x00u
/*!
* @brief Selects function mode (on-chip pull-up/pull-down resistor control).: Pull-up. Pull-up resistor enabled. */
#define PIO0_5_MODE_PULL_UP 0x02u
/*!
* @brief Select Digital mode.: Enable Digital mode. Digital input is enabled. */
#define PIO1_2_DIGIMODE_DIGITAL 0x01u
/*!
* @brief Selects pin function.: Alternative connection 7. */
#define PIO1_2_FUNC_ALT7 0x07u
/*! @name PIO0_0 (number 36), _DBGIF_TCK_SWCLK
@{ */
/* Symbols to be used with GPIO driver */
#define DBGIF_TCK_SWCLK_GPIO GPIO /*!<@brief GPIO peripheral base pointer */
#define DBGIF_TCK_SWCLK_GPIO_PIN_MASK (1U << 0U) /*!<@brief GPIO pin mask */
#define DBGIF_TCK_SWCLK_PORT 0U /*!<@brief PORT peripheral base pointer */
#define DBGIF_TCK_SWCLK_PIN 0U /*!<@brief PORT pin number */
#define DBGIF_TCK_SWCLK_PIN_MASK (1U << 0U) /*!<@brief PORT pin mask */
/* @} */
/*! @name PIO0_1 (number 2), _DBGIF_TDI
@{ */
/* Symbols to be used with GPIO driver */
#define DBGIF_TDI_GPIO GPIO /*!<@brief GPIO peripheral base pointer */
#define DBGIF_TDI_GPIO_PIN_MASK (1U << 1U) /*!<@brief GPIO pin mask */
#define DBGIF_TDI_PORT 0U /*!<@brief PORT peripheral base pointer */
#define DBGIF_TDI_PIN 1U /*!<@brief PORT pin number */
#define DBGIF_TDI_PIN_MASK (1U << 1U) /*!<@brief PORT pin mask */
/* @} */
/*! @name PIO0_2 (number 52), _DBGIF_TMS_SWDIO
@{ */
/* Symbols to be used with GPIO driver */
#define DBGIF_TMS_SWDIO_GPIO GPIO /*!<@brief GPIO peripheral base pointer */
#define DBGIF_TMS_SWDIO_GPIO_PIN_MASK (1U << 2U) /*!<@brief GPIO pin mask */
#define DBGIF_TMS_SWDIO_PORT 0U /*!<@brief PORT peripheral base pointer */
#define DBGIF_TMS_SWDIO_PIN 2U /*!<@brief PORT pin number */
#define DBGIF_TMS_SWDIO_PIN_MASK (1U << 2U) /*!<@brief PORT pin mask */
/* @} */
/*! @name PIO0_28 (number 44), _DBGIF_TMS_SWDIO_TXEN
@{ */
/* Symbols to be used with GPIO driver */
#define DBGIF_TMS_SWDIO_TXEN_GPIO GPIO /*!<@brief GPIO peripheral base pointer */
#define DBGIF_TMS_SWDIO_TXEN_GPIO_PIN_MASK (1U << 28U) /*!<@brief GPIO pin mask */
#define DBGIF_TMS_SWDIO_TXEN_PORT 0U /*!<@brief PORT peripheral base pointer */
#define DBGIF_TMS_SWDIO_TXEN_PIN 28U /*!<@brief PORT pin number */
#define DBGIF_TMS_SWDIO_TXEN_PIN_MASK (1U << 28U) /*!<@brief PORT pin mask */
/* @} */
/*! @name PIO0_19 (number 58), _DBGIF_RESET
@{ */
/* Symbols to be used with GPIO driver */
#define DBGIF_RESET_GPIO GPIO /*!<@brief GPIO peripheral base pointer */
#define DBGIF_RESET_GPIO_PIN_MASK (1U << 19U) /*!<@brief GPIO pin mask */
#define DBGIF_RESET_PORT 0U /*!<@brief PORT peripheral base pointer */
#define DBGIF_RESET_PIN 19U /*!<@brief PORT pin number */
#define DBGIF_RESET_PIN_MASK (1U << 19U) /*!<@brief PORT pin mask */
/* @} */
/*! @name PIO0_13 (number 46), _DBGIF_RESET_TXEN
@{ */
/* Symbols to be used with GPIO driver */
#define DBGIF_RESET_TXEN_GPIO GPIO /*!<@brief GPIO peripheral base pointer */
#define DBGIF_RESET_TXEN_GPIO_PIN_MASK (1U << 13U) /*!<@brief GPIO pin mask */
#define DBGIF_RESET_TXEN_PORT 0U /*!<@brief PORT peripheral base pointer */
#define DBGIF_RESET_TXEN_PIN 13U /*!<@brief PORT pin number */
#define DBGIF_RESET_TXEN_PIN_MASK (1U << 13U) /*!<@brief PORT pin mask */
/* @} */
/*! @name PIO0_3 (number 53), _DBGIF_TDO_SWO
@{ */
#define DBGIF_TDO_SWO_PORT 0U /*!<@brief PORT peripheral base pointer */
#define DBGIF_TDO_SWO_PIN 3U /*!<@brief PORT pin number */
#define DBGIF_TDO_SWO_PIN_MASK (1U << 3U) /*!<@brief PORT pin mask */
/* @} */
/*! @name PIO0_24 (number 45), _FC0_TARGET_RXD
@{ */
#define FC0_TARGET_RXD_PORT 0U /*!<@brief PORT peripheral base pointer */
#define FC0_TARGET_RXD_PIN 24U /*!<@brief PORT pin number */
#define FC0_TARGET_RXD_PIN_MASK (1U << 24U) /*!<@brief PORT pin mask */
/* @} */
/*! @name PIO0_25 (number 51), _FC0_TARGET_TXD
@{ */
#define FC0_TARGET_TXD_PORT 0U /*!<@brief PORT peripheral base pointer */
#define FC0_TARGET_TXD_PIN 25U /*!<@brief PORT pin number */
#define FC0_TARGET_TXD_PIN_MASK (1U << 25U) /*!<@brief PORT pin mask */
/* @} */
/*! @name PIO0_5 (number 56), _LED1
@{ */
/* Symbols to be used with GPIO driver */
#define LED1_GPIO GPIO /*!<@brief GPIO peripheral base pointer */
#define LED1_GPIO_PIN_MASK (1U << 5U) /*!<@brief GPIO pin mask */
#define LED1_PORT 0U /*!<@brief PORT peripheral base pointer */
#define LED1_PIN 5U /*!<@brief PORT pin number */
#define LED1_PIN_MASK (1U << 5U) /*!<@brief PORT pin mask */
/* @} */
/*!
* @brief Configures pin routing and optionally pin electrical features.
*
*/
void MCU_LINK_InitPins(void); /* Function assigned for the Cortex-M33 (Core #0) */
#if defined(__cplusplus)
}
#endif
/*!
* @}
*/
#endif /* _PIN_MUX_H_ */
/***********************************************************************************************************************
* EOF
**********************************************************************************************************************/
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Examples/MCU-LINK/board/pin_mux.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 2,590 |
```objective-c
/***********************************************************************************************************************
* This file was generated by the MCUXpresso Config Tools. Any manual edits made to this file
* will be overwritten if the respective MCUXpresso Config Tools is used to update this file.
**********************************************************************************************************************/
#ifndef _PERIPHERALS_H_
#define _PERIPHERALS_H_
/***********************************************************************************************************************
* Included files
**********************************************************************************************************************/
#include "fsl_common.h"
#if defined(__cplusplus)
extern "C" {
#endif /* __cplusplus */
/***********************************************************************************************************************
* Initialization functions
**********************************************************************************************************************/
void BOARD_InitPeripherals(void);
/***********************************************************************************************************************
* BOARD_InitBootPeripherals function
**********************************************************************************************************************/
void BOARD_InitBootPeripherals(void);
#if defined(__cplusplus)
}
#endif
#endif /* _PERIPHERALS_H_ */
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Examples/MCU-LINK/board/peripherals.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 149 |
```c
/***********************************************************************************************************************
* This file was generated by the MCUXpresso Config Tools. Any manual edits made to this file
* will be overwritten if the respective MCUXpresso Config Tools is used to update this file.
**********************************************************************************************************************/
/*
* How to set up clock using clock driver functions:
*
* 1. Setup clock sources.
*
* 2. Set up wait states of the flash.
*
* 3. Set up all dividers.
*
* 4. Set up all selectors to provide selected clocks.
*/
/* clang-format off */
/* TEXT BELOW IS USED AS SETTING FOR TOOLS *************************************
!!GlobalInfo
product: Clocks v7.0
processor: LPC55S69
package_id: LPC55S69JBD64
mcu_data: ksdk2_0
processor_version: 9.0.3
* BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS **********/
/* clang-format on */
#include "fsl_power.h"
#include "fsl_clock.h"
#include "clock_config.h"
/*******************************************************************************
* Definitions
******************************************************************************/
/*******************************************************************************
* Variables
******************************************************************************/
/* System clock frequency. */
extern uint32_t SystemCoreClock;
/*******************************************************************************
************************ BOARD_InitBootClocks function ************************
******************************************************************************/
void BOARD_InitBootClocks(void)
{
BOARD_BootClockRUN();
}
/*******************************************************************************
********************** Configuration BOARD_BootClockRUN ***********************
******************************************************************************/
/* clang-format off */
/* TEXT BELOW IS USED AS SETTING FOR TOOLS *************************************
!!Configuration
name: BOARD_BootClockRUN
called_from_default_init: true
outputs:
- {id: FXCOM0_clock.outFreq, value: 48 MHz}
- {id: FXCOM3_clock.outFreq, value: 48 MHz}
- {id: System_clock.outFreq, value: 150 MHz, locked: true, accuracy: '0.001'}
- {id: USB1_PHY_clock.outFreq, value: 16 MHz}
settings:
- {id: PLL0_Mode, value: Normal}
- {id: ANALOG_CONTROL_FRO192M_CTRL_ENDI_FRO_96M_CFG, value: Enable}
- {id: ENABLE_CLKIN_ENA, value: Enabled}
- {id: ENABLE_PLL_USB_OUT, value: Enabled}
- {id: ENABLE_SYSTEM_CLK_OUT, value: Enabled}
- {id: SYSCON.FCCLKSEL0.sel, value: SYSCON.FROHFDIV}
- {id: SYSCON.FCCLKSEL3.sel, value: SYSCON.FROHFDIV}
- {id: SYSCON.FRGCTRL3_DIV.scale, value: '256', locked: true}
- {id: SYSCON.FROHFDIV.scale, value: '2', locked: true}
- {id: SYSCON.MAINCLKSELB.sel, value: SYSCON.PLL0_BYPASS}
- {id: SYSCON.PLL0CLKSEL.sel, value: SYSCON.CLK_IN_EN}
- {id: SYSCON.PLL0M_MULT.scale, value: '150', locked: true}
- {id: SYSCON.PLL0N_DIV.scale, value: '8', locked: true}
- {id: SYSCON.PLL0_PDEC.scale, value: '2'}
sources:
- {id: ANACTRL.fro_hf.outFreq, value: 96 MHz}
- {id: SYSCON.XTAL32M.outFreq, value: 16 MHz, enabled: true}
* BE CAREFUL MODIFYING THIS COMMENT - IT IS YAML SETTINGS FOR TOOLS **********/
/* clang-format on */
/*******************************************************************************
* Variables for BOARD_BootClockRUN configuration
******************************************************************************/
/*******************************************************************************
* Code for BOARD_BootClockRUN configuration
******************************************************************************/
void BOARD_BootClockRUN(void)
{
#ifndef SDK_SECONDARY_CORE
/*!< Set up the clock sources */
/*!< Configure FRO192M */
POWER_DisablePD(kPDRUNCFG_PD_FRO192M); /*!< Ensure FRO is on */
CLOCK_SetupFROClocking(12000000U); /*!< Set up FRO to the 12 MHz, just for sure */
CLOCK_AttachClk(kFRO12M_to_MAIN_CLK); /*!< Switch to FRO 12MHz first to ensure we can change the clock setting */
CLOCK_SetupFROClocking(96000000U); /* Enable FRO HF(96MHz) output */
/*!< Configure XTAL32M */
POWER_DisablePD(kPDRUNCFG_PD_XTAL32M); /* Ensure XTAL32M is powered */
POWER_DisablePD(kPDRUNCFG_PD_LDOXO32M); /* Ensure XTAL32M is powered */
CLOCK_SetupExtClocking(16000000U); /* Enable clk_in clock */
SYSCON->CLOCK_CTRL |= SYSCON_CLOCK_CTRL_CLKIN_ENA_MASK; /* Enable clk_in from XTAL32M clock */
ANACTRL->XO32M_CTRL |= ANACTRL_XO32M_CTRL_ENABLE_SYSTEM_CLK_OUT_MASK; /* Enable clk_in to system */
ANACTRL->XO32M_CTRL |= ANACTRL_XO32M_CTRL_ENABLE_PLL_USB_OUT_MASK; /* Enable clk_in to HS USB */
POWER_SetVoltageForFreq(150000000U); /*!< Set voltage for the one of the fastest clock outputs: System clock output */
CLOCK_SetFLASHAccessCyclesForFreq(150000000U); /*!< Set FLASH wait states for core */
/*!< Set up PLL */
CLOCK_AttachClk(kEXT_CLK_to_PLL0); /*!< Switch PLL0CLKSEL to EXT_CLK */
POWER_DisablePD(kPDRUNCFG_PD_PLL0); /* Ensure PLL is on */
POWER_DisablePD(kPDRUNCFG_PD_PLL0_SSCG);
const pll_setup_t pll0Setup = {
.pllctrl = SYSCON_PLL0CTRL_CLKEN_MASK | SYSCON_PLL0CTRL_SELI(53U) | SYSCON_PLL0CTRL_SELP(31U),
.pllndec = SYSCON_PLL0NDEC_NDIV(8U),
.pllpdec = SYSCON_PLL0PDEC_PDIV(1U),
.pllsscg = {0x0U,(SYSCON_PLL0SSCG1_MDIV_EXT(150U) | SYSCON_PLL0SSCG1_SEL_EXT_MASK)},
.pllRate = 150000000U,
.flags = PLL_SETUPFLAG_WAITLOCK
};
CLOCK_SetPLL0Freq(&pll0Setup); /*!< Configure PLL0 to the desired values */
/*!< Set up dividers */
#if FSL_CLOCK_DRIVER_VERSION >= MAKE_VERSION(2, 3, 4)
CLOCK_SetClkDiv(kCLOCK_DivFlexFrg0, 0U, false); /*!< Set DIV to value 0xFF and MULT to value 0U in related FLEXFRGCTRL register */
#else
CLOCK_SetClkDiv(kCLOCK_DivFlexFrg0, 256U, false); /*!< Set DIV to value 0xFF and MULT to value 0U in related FLEXFRGCTRL register */
#endif
#if FSL_CLOCK_DRIVER_VERSION >= MAKE_VERSION(2, 3, 4)
CLOCK_SetClkDiv(kCLOCK_DivFlexFrg3, 0U, false); /*!< Set DIV to value 0xFF and MULT to value 0U in related FLEXFRGCTRL register */
#else
CLOCK_SetClkDiv(kCLOCK_DivFlexFrg3, 256U, false); /*!< Set DIV to value 0xFF and MULT to value 0U in related FLEXFRGCTRL register */
#endif
CLOCK_SetClkDiv(kCLOCK_DivAhbClk, 1U, false); /*!< Set AHBCLKDIV divider to value 1 */
CLOCK_SetClkDiv(kCLOCK_DivFrohfClk, 0U, true); /*!< Reset FROHFDIV divider counter and halt it */
CLOCK_SetClkDiv(kCLOCK_DivFrohfClk, 2U, false); /*!< Set FROHFDIV divider to value 2 */
/*!< Set up clock selectors - Attach clocks to the peripheries */
CLOCK_AttachClk(kPLL0_to_MAIN_CLK); /*!< Switch MAIN_CLK to PLL0 */
CLOCK_AttachClk(kFRO_HF_DIV_to_FLEXCOMM0); /*!< Switch FLEXCOMM0 to FRO_HF_DIV */
CLOCK_AttachClk(kFRO_HF_DIV_to_FLEXCOMM3); /*!< Switch FLEXCOMM3 to FRO_HF_DIV */
/*!< Set SystemCoreClock variable. */
SystemCoreClock = BOARD_BOOTCLOCKRUN_CORE_CLOCK;
#endif
}
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Examples/MCU-LINK/board/clock_config.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 1,886 |
```c
/*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* your_sha256_hash-------------
*
* $Revision: V5.1.1
*
* Project: CMSIS-RTOS RTX
* Title: RTX Configuration
*
* your_sha256_hash-------------
*/
#include "cmsis_compiler.h"
#include "rtx_os.h"
// OS Idle Thread
__WEAK __NO_RETURN void osRtxIdleThread (void *argument) {
(void)argument;
for (;;) {}
}
// OS Error Callback function
__WEAK uint32_t osRtxErrorNotify (uint32_t code, void *object_id) {
(void)object_id;
switch (code) {
case osRtxErrorStackOverflow:
// Stack overflow detected for thread (thread_id=object_id)
break;
case osRtxErrorISRQueueOverflow:
// ISR Queue overflow detected when inserting object (object_id)
break;
case osRtxErrorTimerQueueOverflow:
// User Timer Callback Queue overflow detected for timer (timer_id=object_id)
break;
case osRtxErrorClibSpace:
// Standard C/C++ library libspace not available: increase OS_THREAD_LIBSPACE_NUM
break;
case osRtxErrorClibMutex:
// Standard C/C++ library mutex initialization failed
break;
default:
// Reserved
break;
}
for (;;) {}
//return 0U;
}
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Examples/MCU-LINK/RTE/CMSIS/RTX_Config.c | c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 345 |
```objective-c
/*
*
*
*
* www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* your_sha256_hash-------------
*
* $Revision: V5.5.2
*
* Project: CMSIS-RTOS RTX
* Title: RTX Configuration definitions
*
* your_sha256_hash-------------
*/
#ifndef RTX_CONFIG_H_
#define RTX_CONFIG_H_
#ifdef _RTE_
#include "RTE_Components.h"
#ifdef RTE_RTX_CONFIG_H
#include RTE_RTX_CONFIG_H
#endif
#endif
//-------- <<< Use Configuration Wizard in Context Menu >>> --------------------
// <h>System Configuration
// =======================
// <o>Global Dynamic Memory size [bytes] <0-1073741824:8>
// <i> Defines the combined global dynamic memory size.
// <i> Default: 32768
#ifndef OS_DYNAMIC_MEM_SIZE
#define OS_DYNAMIC_MEM_SIZE 4096
#endif
// <o>Kernel Tick Frequency [Hz] <1-1000000>
// <i> Defines base time unit for delays and timeouts.
// <i> Default: 1000 (1ms tick)
#ifndef OS_TICK_FREQ
#define OS_TICK_FREQ 1000
#endif
// <e>Round-Robin Thread switching
// <i> Enables Round-Robin Thread switching.
#ifndef OS_ROBIN_ENABLE
#define OS_ROBIN_ENABLE 1
#endif
// <o>Round-Robin Timeout <1-1000>
// <i> Defines how many ticks a thread will execute before a thread switch.
// <i> Default: 5
#ifndef OS_ROBIN_TIMEOUT
#define OS_ROBIN_TIMEOUT 5
#endif
// </e>
// <o>ISR FIFO Queue
// <4=> 4 entries <8=> 8 entries <12=> 12 entries <16=> 16 entries
// <24=> 24 entries <32=> 32 entries <48=> 48 entries <64=> 64 entries
// <96=> 96 entries <128=> 128 entries <196=> 196 entries <256=> 256 entries
// <i> RTOS Functions called from ISR store requests to this buffer.
// <i> Default: 16 entries
#ifndef OS_ISR_FIFO_QUEUE
#define OS_ISR_FIFO_QUEUE 32
#endif
// <q>Object Memory usage counters
// <i> Enables object memory usage counters (requires RTX source variant).
#ifndef OS_OBJ_MEM_USAGE
#define OS_OBJ_MEM_USAGE 0
#endif
// </h>
// <h>Thread Configuration
// =======================
// <e>Object specific Memory allocation
// <i> Enables object specific memory allocation.
#ifndef OS_THREAD_OBJ_MEM
#define OS_THREAD_OBJ_MEM 0
#endif
// <o>Number of user Threads <1-1000>
// <i> Defines maximum number of user threads that can be active at the same time.
// <i> Applies to user threads with system provided memory for control blocks.
#ifndef OS_THREAD_NUM
#define OS_THREAD_NUM 1
#endif
// <o>Number of user Threads with default Stack size <0-1000>
// <i> Defines maximum number of user threads with default stack size.
// <i> Applies to user threads with zero stack size specified.
#ifndef OS_THREAD_DEF_STACK_NUM
#define OS_THREAD_DEF_STACK_NUM 0
#endif
// <o>Total Stack size [bytes] for user Threads with user-provided Stack size <0-1073741824:8>
// <i> Defines the combined stack size for user threads with user-provided stack size.
// <i> Applies to user threads with user-provided stack size and system provided memory for stack.
// <i> Default: 0
#ifndef OS_THREAD_USER_STACK_SIZE
#define OS_THREAD_USER_STACK_SIZE 0
#endif
// </e>
// <o>Default Thread Stack size [bytes] <96-1073741824:8>
// <i> Defines stack size for threads with zero stack size specified.
// <i> Default: 3072
#ifndef OS_STACK_SIZE
#define OS_STACK_SIZE 1024
#endif
// <o>Idle Thread Stack size [bytes] <72-1073741824:8>
// <i> Defines stack size for Idle thread.
// <i> Default: 512
#ifndef OS_IDLE_THREAD_STACK_SIZE
#define OS_IDLE_THREAD_STACK_SIZE 512
#endif
// <o>Idle Thread TrustZone Module Identifier
// <i> Defines TrustZone Thread Context Management Identifier.
// <i> Applies only to cores with TrustZone technology.
// <i> Default: 0 (not used)
#ifndef OS_IDLE_THREAD_TZ_MOD_ID
#define OS_IDLE_THREAD_TZ_MOD_ID 0
#endif
// <q>Stack overrun checking
// <i> Enables stack overrun check at thread switch (requires RTX source variant).
// <i> Enabling this option increases slightly the execution time of a thread switch.
#ifndef OS_STACK_CHECK
#define OS_STACK_CHECK 0
#endif
// <q>Stack usage watermark
// <i> Initializes thread stack with watermark pattern for analyzing stack usage.
// <i> Enabling this option increases significantly the execution time of thread creation.
#ifndef OS_STACK_WATERMARK
#define OS_STACK_WATERMARK 0
#endif
// <o>Processor mode for Thread execution
// <0=> Unprivileged mode
// <1=> Privileged mode
// <i> Default: Privileged mode
#ifndef OS_PRIVILEGE_MODE
#define OS_PRIVILEGE_MODE 1
#endif
// </h>
// <h>Timer Configuration
// ======================
// <e>Object specific Memory allocation
// <i> Enables object specific memory allocation.
#ifndef OS_TIMER_OBJ_MEM
#define OS_TIMER_OBJ_MEM 0
#endif
// <o>Number of Timer objects <1-1000>
// <i> Defines maximum number of objects that can be active at the same time.
// <i> Applies to objects with system provided memory for control blocks.
#ifndef OS_TIMER_NUM
#define OS_TIMER_NUM 1
#endif
// </e>
// <o>Timer Thread Priority
// <8=> Low
// <16=> Below Normal <24=> Normal <32=> Above Normal
// <40=> High
// <48=> Realtime
// <i> Defines priority for timer thread
// <i> Default: High
#ifndef OS_TIMER_THREAD_PRIO
#define OS_TIMER_THREAD_PRIO 40
#endif
// <o>Timer Thread Stack size [bytes] <0-1073741824:8>
// <i> Defines stack size for Timer thread.
// <i> May be set to 0 when timers are not used.
// <i> Default: 512
#ifndef OS_TIMER_THREAD_STACK_SIZE
#define OS_TIMER_THREAD_STACK_SIZE 512
#endif
// <o>Timer Thread TrustZone Module Identifier
// <i> Defines TrustZone Thread Context Management Identifier.
// <i> Applies only to cores with TrustZone technology.
// <i> Default: 0 (not used)
#ifndef OS_TIMER_THREAD_TZ_MOD_ID
#define OS_TIMER_THREAD_TZ_MOD_ID 0
#endif
// <o>Timer Callback Queue entries <0-256>
// <i> Number of concurrent active timer callback functions.
// <i> May be set to 0 when timers are not used.
// <i> Default: 4
#ifndef OS_TIMER_CB_QUEUE
#define OS_TIMER_CB_QUEUE 4
#endif
// </h>
// <h>Event Flags Configuration
// ============================
// <e>Object specific Memory allocation
// <i> Enables object specific memory allocation.
#ifndef OS_EVFLAGS_OBJ_MEM
#define OS_EVFLAGS_OBJ_MEM 0
#endif
// <o>Number of Event Flags objects <1-1000>
// <i> Defines maximum number of objects that can be active at the same time.
// <i> Applies to objects with system provided memory for control blocks.
#ifndef OS_EVFLAGS_NUM
#define OS_EVFLAGS_NUM 1
#endif
// </e>
// </h>
// <h>Mutex Configuration
// ======================
// <e>Object specific Memory allocation
// <i> Enables object specific memory allocation.
#ifndef OS_MUTEX_OBJ_MEM
#define OS_MUTEX_OBJ_MEM 0
#endif
// <o>Number of Mutex objects <1-1000>
// <i> Defines maximum number of objects that can be active at the same time.
// <i> Applies to objects with system provided memory for control blocks.
#ifndef OS_MUTEX_NUM
#define OS_MUTEX_NUM 1
#endif
// </e>
// </h>
// <h>Semaphore Configuration
// ==========================
// <e>Object specific Memory allocation
// <i> Enables object specific memory allocation.
#ifndef OS_SEMAPHORE_OBJ_MEM
#define OS_SEMAPHORE_OBJ_MEM 0
#endif
// <o>Number of Semaphore objects <1-1000>
// <i> Defines maximum number of objects that can be active at the same time.
// <i> Applies to objects with system provided memory for control blocks.
#ifndef OS_SEMAPHORE_NUM
#define OS_SEMAPHORE_NUM 1
#endif
// </e>
// </h>
// <h>Memory Pool Configuration
// ============================
// <e>Object specific Memory allocation
// <i> Enables object specific memory allocation.
#ifndef OS_MEMPOOL_OBJ_MEM
#define OS_MEMPOOL_OBJ_MEM 0
#endif
// <o>Number of Memory Pool objects <1-1000>
// <i> Defines maximum number of objects that can be active at the same time.
// <i> Applies to objects with system provided memory for control blocks.
#ifndef OS_MEMPOOL_NUM
#define OS_MEMPOOL_NUM 1
#endif
// <o>Data Storage Memory size [bytes] <0-1073741824:8>
// <i> Defines the combined data storage memory size.
// <i> Applies to objects with system provided memory for data storage.
// <i> Default: 0
#ifndef OS_MEMPOOL_DATA_SIZE
#define OS_MEMPOOL_DATA_SIZE 0
#endif
// </e>
// </h>
// <h>Message Queue Configuration
// ==============================
// <e>Object specific Memory allocation
// <i> Enables object specific memory allocation.
#ifndef OS_MSGQUEUE_OBJ_MEM
#define OS_MSGQUEUE_OBJ_MEM 0
#endif
// <o>Number of Message Queue objects <1-1000>
// <i> Defines maximum number of objects that can be active at the same time.
// <i> Applies to objects with system provided memory for control blocks.
#ifndef OS_MSGQUEUE_NUM
#define OS_MSGQUEUE_NUM 1
#endif
// <o>Data Storage Memory size [bytes] <0-1073741824:8>
// <i> Defines the combined data storage memory size.
// <i> Applies to objects with system provided memory for data storage.
// <i> Default: 0
#ifndef OS_MSGQUEUE_DATA_SIZE
#define OS_MSGQUEUE_DATA_SIZE 0
#endif
// </e>
// </h>
// <h>Event Recorder Configuration
// ===============================
// <e>Global Initialization
// <i> Initialize Event Recorder during 'osKernelInitialize'.
#ifndef OS_EVR_INIT
#define OS_EVR_INIT 0
#endif
// <q>Start recording
// <i> Start event recording after initialization.
#ifndef OS_EVR_START
#define OS_EVR_START 1
#endif
// <h>Global Event Filter Setup
// <i> Initial recording level applied to all components.
// <o.0>Error events
// <o.1>API function call events
// <o.2>Operation events
// <o.3>Detailed operation events
// </h>
#ifndef OS_EVR_LEVEL
#define OS_EVR_LEVEL 0x00U
#endif
// <h>RTOS Event Filter Setup
// <i> Recording levels for RTX components.
// <i> Only applicable if events for the respective component are generated.
// <e.7>Memory Management
// <i> Recording level for Memory Management events.
// <o.0>Error events
// <o.1>API function call events
// <o.2>Operation events
// <o.3>Detailed operation events
// </e>
#ifndef OS_EVR_MEMORY_LEVEL
#define OS_EVR_MEMORY_LEVEL 0x81U
#endif
// <e.7>Kernel
// <i> Recording level for Kernel events.
// <o.0>Error events
// <o.1>API function call events
// <o.2>Operation events
// <o.3>Detailed operation events
// </e>
#ifndef OS_EVR_KERNEL_LEVEL
#define OS_EVR_KERNEL_LEVEL 0x81U
#endif
// <e.7>Thread
// <i> Recording level for Thread events.
// <o.0>Error events
// <o.1>API function call events
// <o.2>Operation events
// <o.3>Detailed operation events
// </e>
#ifndef OS_EVR_THREAD_LEVEL
#define OS_EVR_THREAD_LEVEL 0x85U
#endif
// <e.7>Generic Wait
// <i> Recording level for Generic Wait events.
// <o.0>Error events
// <o.1>API function call events
// <o.2>Operation events
// <o.3>Detailed operation events
// </e>
#ifndef OS_EVR_WAIT_LEVEL
#define OS_EVR_WAIT_LEVEL 0x81U
#endif
// <e.7>Thread Flags
// <i> Recording level for Thread Flags events.
// <o.0>Error events
// <o.1>API function call events
// <o.2>Operation events
// <o.3>Detailed operation events
// </e>
#ifndef OS_EVR_THFLAGS_LEVEL
#define OS_EVR_THFLAGS_LEVEL 0x81U
#endif
// <e.7>Event Flags
// <i> Recording level for Event Flags events.
// <o.0>Error events
// <o.1>API function call events
// <o.2>Operation events
// <o.3>Detailed operation events
// </e>
#ifndef OS_EVR_EVFLAGS_LEVEL
#define OS_EVR_EVFLAGS_LEVEL 0x81U
#endif
// <e.7>Timer
// <i> Recording level for Timer events.
// <o.0>Error events
// <o.1>API function call events
// <o.2>Operation events
// <o.3>Detailed operation events
// </e>
#ifndef OS_EVR_TIMER_LEVEL
#define OS_EVR_TIMER_LEVEL 0x81U
#endif
// <e.7>Mutex
// <i> Recording level for Mutex events.
// <o.0>Error events
// <o.1>API function call events
// <o.2>Operation events
// <o.3>Detailed operation events
// </e>
#ifndef OS_EVR_MUTEX_LEVEL
#define OS_EVR_MUTEX_LEVEL 0x81U
#endif
// <e.7>Semaphore
// <i> Recording level for Semaphore events.
// <o.0>Error events
// <o.1>API function call events
// <o.2>Operation events
// <o.3>Detailed operation events
// </e>
#ifndef OS_EVR_SEMAPHORE_LEVEL
#define OS_EVR_SEMAPHORE_LEVEL 0x81U
#endif
// <e.7>Memory Pool
// <i> Recording level for Memory Pool events.
// <o.0>Error events
// <o.1>API function call events
// <o.2>Operation events
// <o.3>Detailed operation events
// </e>
#ifndef OS_EVR_MEMPOOL_LEVEL
#define OS_EVR_MEMPOOL_LEVEL 0x81U
#endif
// <e.7>Message Queue
// <i> Recording level for Message Queue events.
// <o.0>Error events
// <o.1>API function call events
// <o.2>Operation events
// <o.3>Detailed operation events
// </e>
#ifndef OS_EVR_MSGQUEUE_LEVEL
#define OS_EVR_MSGQUEUE_LEVEL 0x81U
#endif
// </h>
// </e>
// <h>RTOS Event Generation
// <i> Enables event generation for RTX components (requires RTX source variant).
// <q>Memory Management
// <i> Enables Memory Management event generation.
#ifndef OS_EVR_MEMORY
#define OS_EVR_MEMORY 1
#endif
// <q>Kernel
// <i> Enables Kernel event generation.
#ifndef OS_EVR_KERNEL
#define OS_EVR_KERNEL 1
#endif
// <q>Thread
// <i> Enables Thread event generation.
#ifndef OS_EVR_THREAD
#define OS_EVR_THREAD 1
#endif
// <q>Generic Wait
// <i> Enables Generic Wait event generation.
#ifndef OS_EVR_WAIT
#define OS_EVR_WAIT 1
#endif
// <q>Thread Flags
// <i> Enables Thread Flags event generation.
#ifndef OS_EVR_THFLAGS
#define OS_EVR_THFLAGS 1
#endif
// <q>Event Flags
// <i> Enables Event Flags event generation.
#ifndef OS_EVR_EVFLAGS
#define OS_EVR_EVFLAGS 1
#endif
// <q>Timer
// <i> Enables Timer event generation.
#ifndef OS_EVR_TIMER
#define OS_EVR_TIMER 1
#endif
// <q>Mutex
// <i> Enables Mutex event generation.
#ifndef OS_EVR_MUTEX
#define OS_EVR_MUTEX 1
#endif
// <q>Semaphore
// <i> Enables Semaphore event generation.
#ifndef OS_EVR_SEMAPHORE
#define OS_EVR_SEMAPHORE 1
#endif
// <q>Memory Pool
// <i> Enables Memory Pool event generation.
#ifndef OS_EVR_MEMPOOL
#define OS_EVR_MEMPOOL 1
#endif
// <q>Message Queue
// <i> Enables Message Queue event generation.
#ifndef OS_EVR_MSGQUEUE
#define OS_EVR_MSGQUEUE 1
#endif
// </h>
// </h>
// Number of Threads which use standard C/C++ library libspace
// (when thread specific memory allocation is not used).
#if (OS_THREAD_OBJ_MEM == 0)
#ifndef OS_THREAD_LIBSPACE_NUM
#define OS_THREAD_LIBSPACE_NUM 4
#endif
#else
#define OS_THREAD_LIBSPACE_NUM OS_THREAD_NUM
#endif
//------------- <<< end of configuration section >>> ---------------------------
#endif // RTX_CONFIG_H_
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Examples/MCU-LINK/RTE/CMSIS/RTX_Config.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 4,298 |
```objective-c
/*
* All rights reserved.
*
*/
#ifndef _RTE_DEVICE_H
#define _RTE_DEVICE_H
#include "pin_mux.h"
/* UART Select, UART0-UART7. */
/* User needs to provide the implementation of USARTX_GetFreq/USARTX_InitPins/USARTX_DeinitPins for the enabled USART
* instance. */
#define RTE_USART0 1
#define RTE_USART0_DMA_EN 1
#define RTE_USART1 0
#define RTE_USART1_DMA_EN 0
#define RTE_USART2 0
#define RTE_USART2_DMA_EN 0
#define RTE_USART3 1
#define RTE_USART3_DMA_EN 1
#define RTE_USART4 0
#define RTE_USART4_DMA_EN 0
#define RTE_USART5 0
#define RTE_USART5_DMA_EN 0
#define RTE_USART6 0
#define RTE_USART6_DMA_EN 0
#define RTE_USART7 0
#define RTE_USART7_DMA_EN 0
/* USART configuration. */
#define USART_RX_BUFFER_LEN 64
#define USART0_RX_BUFFER_ENABLE 1
#define USART1_RX_BUFFER_ENABLE 0
#define USART2_RX_BUFFER_ENABLE 0
#define USART3_RX_BUFFER_ENABLE 1
#define USART4_RX_BUFFER_ENABLE 0
#define USART5_RX_BUFFER_ENABLE 0
#define USART6_RX_BUFFER_ENABLE 0
#define USART7_RX_BUFFER_ENABLE 0
#define RTE_USART0_DMA_TX_CH 5
#define RTE_USART0_DMA_TX_DMA_BASE DMA0
#define RTE_USART0_DMA_RX_CH 4
#define RTE_USART0_DMA_RX_DMA_BASE DMA0
#define RTE_USART1_DMA_TX_CH 7
#define RTE_USART1_DMA_TX_DMA_BASE DMA0
#define RTE_USART1_DMA_RX_CH 6
#define RTE_USART1_DMA_RX_DMA_BASE DMA0
#define RTE_USART2_DMA_TX_CH 8
#define RTE_USART2_DMA_TX_DMA_BASE DMA0
#define RTE_USART2_DMA_RX_CH 9
#define RTE_USART2_DMA_RX_DMA_BASE DMA0
#define RTE_USART3_DMA_TX_CH 9
#define RTE_USART3_DMA_TX_DMA_BASE DMA0
#define RTE_USART3_DMA_RX_CH 8
#define RTE_USART3_DMA_RX_DMA_BASE DMA0
#define RTE_USART4_DMA_TX_CH 13
#define RTE_USART4_DMA_TX_DMA_BASE DMA0
#define RTE_USART4_DMA_RX_CH 12
#define RTE_USART4_DMA_RX_DMA_BASE DMA0
#define RTE_USART5_DMA_TX_CH 15
#define RTE_USART5_DMA_TX_DMA_BASE DMA0
#define RTE_USART5_DMA_RX_CH 14
#define RTE_USART5_DMA_RX_DMA_BASE DMA0
#define RTE_USART6_DMA_TX_CH 17
#define RTE_USART6_DMA_TX_DMA_BASE DMA0
#define RTE_USART6_DMA_RX_CH 16
#define RTE_USART6_DMA_RX_DMA_BASE DMA0
#define RTE_USART7_DMA_TX_CH 19
#define RTE_USART7_DMA_TX_DMA_BASE DMA0
#define RTE_USART7_DMA_RX_CH 18
#define RTE_USART7_DMA_RX_DMA_BASE DMA0
/* I2C Select, I2C0 -I2C7*/
/* User needs to provide the implementation of I2CX_GetFreq/I2CX_InitPins/I2CX_DeinitPins for the enabled I2C instance.
*/
#define RTE_I2C0 0
#define RTE_I2C0_DMA_EN 0
#define RTE_I2C1 0
#define RTE_I2C1_DMA_EN 0
#define RTE_I2C2 0
#define RTE_I2C2_DMA_EN 0
#define RTE_I2C3 0
#define RTE_I2C3_DMA_EN 0
#define RTE_I2C4 0
#define RTE_I2C4_DMA_EN 0
#define RTE_I2C5 0
#define RTE_I2C5_DMA_EN 0
#define RTE_I2C6 0
#define RTE_I2C6_DMA_EN 0
#define RTE_I2C7 0
#define RTE_I2C7_DMA_EN 0
/*I2C configuration*/
#define RTE_I2C0_Master_DMA_BASE DMA0
#define RTE_I2C0_Master_DMA_CH 1
#define RTE_I2C1_Master_DMA_BASE DMA0
#define RTE_I2C1_Master_DMA_CH 3
#define RTE_I2C2_Master_DMA_BASE DMA0
#define RTE_I2C2_Master_DMA_CH 5
#define RTE_I2C3_Master_DMA_BASE DMA0
#define RTE_I2C3_Master_DMA_CH 7
#define RTE_I2C4_Master_DMA_BASE DMA0
#define RTE_I2C4_Master_DMA_CH 9
#define RTE_I2C5_Master_DMA_BASE DMA0
#define RTE_I2C5_Master_DMA_CH 11
#define RTE_I2C6_Master_DMA_BASE DMA0
#define RTE_I2C6_Master_DMA_CH 13
#define RTE_I2C7_Master_DMA_BASE DMA0
#define RTE_I2C7_Master_DMA_CH 15
/* SPI select, SPI0 - SPI7.*/
/* User needs to provide the implementation of SPIX_GetFreq/SPIX_InitPins/SPIX_DeinitPins for the enabled SPI instance.
*/
#define RTE_SPI0 0
#define RTE_SPI0_DMA_EN 0
#define RTE_SPI1 0
#define RTE_SPI1_DMA_EN 0
#define RTE_SPI2 0
#define RTE_SPI2_DMA_EN 0
#define RTE_SPI3 0
#define RTE_SPI3_DMA_EN 0
#define RTE_SPI4 0
#define RTE_SPI4_DMA_EN 0
#define RTE_SPI5 0
#define RTE_SPI5_DMA_EN 0
#define RTE_SPI6 0
#define RTE_SPI6_DMA_EN 0
#define RTE_SPI7 0
#define RTE_SPI7_DMA_EN 0
/* SPI configuration. */
#define RTE_SPI0_SSEL_NUM kSPI_Ssel0
#define RTE_SPI0_PIN_INIT SPI0_InitPins
#define RTE_SPI0_PIN_DEINIT SPI0_DeinitPins
#define RTE_SPI0_DMA_TX_CH 1
#define RTE_SPI0_DMA_TX_DMA_BASE DMA0
#define RTE_SPI0_DMA_RX_CH 0
#define RTE_SPI0_DMA_RX_DMA_BASE DMA0
#define RTE_SPI1_SSEL_NUM kSPI_Ssel0
#define RTE_SPI1_PIN_INIT SPI1_InitPins
#define RTE_SPI1_PIN_DEINIT SPI1_DeinitPins
#define RTE_SPI1_DMA_TX_CH 3
#define RTE_SPI1_DMA_TX_DMA_BASE DMA0
#define RTE_SPI1_DMA_RX_CH 2
#define RTE_SPI1_DMA_RX_DMA_BASE DMA0
#define RTE_SPI2_SSEL_NUM kSPI_Ssel0
#define RTE_SPI2_PIN_INIT SPI2_InitPins
#define RTE_SPI2_PIN_DEINIT SPI2_DeinitPins
#define RTE_SPI2_DMA_TX_CH 5
#define RTE_SPI2_DMA_TX_DMA_BASE DMA0
#define RTE_SPI2_DMA_RX_CH 4
#define RTE_SPI2_DMA_RX_DMA_BASE DMA0
#define RTE_SPI3_SSEL_NUM kSPI_Ssel0
#define RTE_SPI3_PIN_INIT SPI3_InitPins
#define RTE_SPI3_PIN_DEINIT SPI3_DeinitPins
#define RTE_SPI3_DMA_TX_CH 7
#define RTE_SPI3_DMA_TX_DMA_BASE DMA0
#define RTE_SPI3_DMA_RX_CH 6
#define RTE_SPI3_DMA_RX_DMA_BASE DMA0
#define RTE_SPI4_SSEL_NUM kSPI_Ssel0
#define RTE_SPI4_PIN_INIT SPI4_InitPins
#define RTE_SPI4_PIN_DEINIT SPI4_DeinitPins
#define RTE_SPI4_DMA_TX_CH 9
#define RTE_SPI4_DMA_TX_DMA_BASE DMA0
#define RTE_SPI4_DMA_RX_CH 8
#define RTE_SPI4_DMA_RX_DMA_BASE DMA0
#define RTE_SPI5_SSEL_NUM kSPI_Ssel0
#define RTE_SPI5_PIN_INIT SPI5_InitPins
#define RTE_SPI5_PIN_DEINIT SPI5_DeinitPins
#define RTE_SPI5_DMA_TX_CH 11
#define RTE_SPI5_DMA_TX_DMA_BASE DMA0
#define RTE_SPI5_DMA_RX_CH 10
#define RTE_SPI5_DMA_RX_DMA_BASE DMA0
#define RTE_SPI6_SSEL_NUM kSPI_Ssel0
#define RTE_SPI6_PIN_INIT SPI6_InitPins
#define RTE_SPI6_PIN_DEINIT SPI6_DeinitPins
#define RTE_SPI6_DMA_TX_CH 13
#define RTE_SPI6_DMA_TX_DMA_BASE DMA0
#define RTE_SPI6_DMA_RX_CH 12
#define RTE_SPI6_DMA_RX_DMA_BASE DMA0
#define RTE_SPI7_SSEL_NUM kSPI_Ssel0
#define RTE_SPI7_PIN_INIT SPI7_InitPins
#define RTE_SPI7_PIN_DEINIT SPI7_DeinitPins
#define RTE_SPI7_DMA_TX_CH 15
#define RTE_SPI7_DMA_TX_DMA_BASE DMA0
#define RTE_SPI7_DMA_RX_CH 14
#define RTE_SPI7_DMA_RX_DMA_BASE DMA0
#endif /* _RTE_DEVICE_H */
``` | /content/code_sandbox/CMSIS/DAP/Firmware/Examples/MCU-LINK/RTE/Device/LPC55S69JBD64_cm33_core0/RTE_Device.h | objective-c | 2016-02-18T08:04:18 | 2024-08-16T08:24:23 | CMSIS_5 | ARM-software/CMSIS_5 | 1,295 | 1,950 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.