Add strcmp and readline

This commit is contained in:
Mathieu Maret 2022-03-21 21:54:58 +01:00 committed by Mathieu Maret
parent 694257c5ac
commit 9ffa7dde85
2 changed files with 46 additions and 17 deletions

61
utils.c
View File

@ -1,25 +1,25 @@
#include <stdint.h>
#include "uart.h"
#include "clock.h" #include "clock.h"
#include "uart.h"
#include <stdint.h>
// K&R inspirated // K&R inspirated
void printhex(unsigned int d) void printhex(unsigned int d)
{ {
char n; char n;
for(int c=28;c>=0;c-=4) { for (int c = 28; c >= 0; c -= 4) {
// get highest tetrad // get highest tetrad
n=(d>>c)&0xF; n = (d >> c) & 0xF;
// 0-9 => '0'-'9', 10-15 => 'A'-'F' // 0-9 => '0'-'9', 10-15 => 'A'-'F'
n+=n>9?0x37:0x30; n += n > 9 ? 0x37 : 0x30;
putc(n); putc(n);
} }
} }
int strlen(char s[]) int strlen(char s[])
{ {
int i=0; int i = 0;
while(s[i]!= '\0') { while (s[i] != '\0') {
++i; ++i;
} }
return i; return i;
@ -28,20 +28,20 @@ int strlen(char s[])
void reverse(char s[]) void reverse(char s[])
{ {
int c, i, j; int c, i, j;
for(i=0, j=strlen(s)-1; i<j; i++, j--) { for (i = 0, j = strlen(s) - 1; i < j; i++, j--) {
c=s[i]; c = s[i];
s[i]=s[j]; s[i] = s[j];
s[j]=c; s[j] = c;
} }
} }
void itoa(unsigned int n, char s[]) void itoa(unsigned int n, char s[])
{ {
int i=0; int i = 0;
do { do {
s[i++]=n%10+'0'; s[i++] = n % 10 + '0';
} while((n/=10)>0); } while ((n /= 10) > 0);
s[i]='\0'; s[i] = '\0';
reverse(s); reverse(s);
} }
@ -49,7 +49,7 @@ void printdec(unsigned int d)
{ {
char s[16]; char s[16];
itoa(d, s); itoa(d, s);
for(int i=0; i<strlen(s); i++) { for (int i = 0; i < strlen(s); i++) {
putc(s[i]); putc(s[i]);
} }
} }
@ -61,7 +61,7 @@ void printclock()
"PWM", "HEVC", "EMMC2", "M2MC", "PIXEL_BVB"}; "PWM", "HEVC", "EMMC2", "M2MC", "PIXEL_BVB"};
puts("Clocks:\n"); puts("Clocks:\n");
for(int i =1; i <= CLK_PIXEL_BVB; i++ ){ for (int i = 1; i <= CLK_PIXEL_BVB; i++) {
puts(" "); puts(" ");
puts(clocktxts[i]); puts(clocktxts[i]);
puts(": "); puts(": ");
@ -71,3 +71,30 @@ void printclock()
puts(" Hz\n"); puts(" Hz\n");
} }
} }
int readline(char *buf, int maxlen)
{
int num = 0;
while (num < maxlen - 1) {
char c = uart_recv();
// It seems like screen sends \r when I press enter
if (c == '\n' || c == '\0' || c == '\r') {
break;
}
buf[num] = c;
num++;
}
buf[num] = '\0';
return num;
}
// Returns <0 if s1<s2, 0 if s1==s2, >0 if s1>s2
int strcmp(const char s1[], const char s2[])
{
int i;
for (i = 0; s1[i] == s2[i]; i++) {
if (s1[i] == '\0')
return 0;
}
return s1[i] - s2[i];
}

View File

@ -6,3 +6,5 @@ void reverse(char s[]);
void itoa(unsigned int n, char s[]); void itoa(unsigned int n, char s[]);
void printdec(unsigned int d); void printdec(unsigned int d);
void printclock(); void printclock();
int strcmp(const char s1[], const char s2[]);
int readline(char *buf, int maxlen);