본문 바로가기
카테고리 없음

C Read From Dev Input Event

by glosriguipetjumag 2020. 11. 4.


All my code was based upon an article from linuxjournal.com here is the article I based my code on

Mar 13, 2017  Linux: Reading the Mouse events datas from /dev/input/mouse0 A simple program to check the /dev/input/mouse0 datas Tested on the raspberry PI with GPM installed. At this point you might wonder why I don't simply read the input event to read the keyboard input. This is because read is a blocking function. While ioctl is not blocking. If anyone could please help me figure out why EVIOCGKEY is returning the incorrect key values, I'd be very grateful.

I'm writing an embedded app, and I'm trying to read the keystrokes from a keyboard.
Here is the code I'm using

For the most part this code works, EXCEPT when I press 'a'.

According to the input.h KEY_A is set to be the value 30. But when I press 'a' on the keyboard, it returns the value 102 instead of 30. I've tested the other keys on the keyboard, and it seems like the keys 1-6 return the expected value of KEY_1, KEY_2 and etc., but after that the values returned aren't right.

I've tried reading the even directly from the /dev/input/eventX file. And the code returned in the events are expected.

The above code gives this print out when I hit the 'a' key. type 1 code 30 value 1

At this point you might wonder why I don't simply read the input event to read the keyboard input. This is because read() is a blocking function. While ioctl() is not blocking.

If anyone could please help me figure out why EVIOCGKEY() is returning the incorrect key values, I'd be very grateful. Thanks!

Ok, I figured out what the problem was.

my test_bit() macro was written incorrectly.
Basically, key_b[] represents the state of the keys, bit by bit. Meaning if KEY_A is pressed, then bit 30 will be set to 1. In this case, bit 30 will show up in key_b[3] as the value 0x40.

Here's a few more examples of how each key will map into key_b[].

  • KEY_1 = 2 represented in key_b as --> key_b[0] = 0x04;
  • KEY_2 = 3 represented in key_b as --> key_b[0] = 0x08;
  • KEY_3 = 4 represented in key_b as --> key_b[0] = 0x10;
  • KEY_4 = 5 represented in key_b as --> key_b[0] = 0x20;
  • KEY_5 = 6 represented in key_b as --> key_b[0] = 0x40;
  • KEY_6 = 7 represented in key_b as --> key_b[0] = 0x80;
  • KEY_7 = 8 represented in key_b as --> key_b[1] = 0x01;
  • KEY_8 = 9 represented in key_b as --> key_b[1] = 0x02;
  • KEY_9 = 10 represented in key_b as --> key_b[2] = 0x04;
  • KEY_0 = 11 represented in key_b as --> key_b[3] = 0x08;

While loop in bash using variable from txt file

linux,bash,rhel

As indicated in the comments, you need to provide 'something' to your while loop. The while construct is written in a way that will execute with a condition; if a file is given, it will proceed until the read exhausts. #!/bin/bash file=Sheetone.txt while IFS= read -r line do echo sh...

Django MySQLClient pip compile failure on Linux

python,linux,django,gcc,pip

It looks like you're missing zlib; you'll want to install it: apt-get install zlib1g-dev I also suggest reading over the README and confirming you have all other dependencies met: https://github.com/dccmx/mysqldb/blob/master/README Also, I suggest using mysqlclient over MySQLdb as its a fork of MySQLdb and what Django recommends....

ret_from_syscall source code and when it is called

linux,linux-kernel,kernel,linux-device-driver,system-calls

The ret_from_syscall symbol will be in architecture-specific assembly code (it does not exist for all architectures). I would look in arch/XXX/kernel/entry.S. It's not actually a function. It is part of the assembly code that handles the transition from user-space into kernel-space for a system call. It's simply a label to...

Using an ad-hoc libc with a tool which is an argument of another tool

linux,shared-libraries

You can achieve that by using the env utility: timeout 10 /usr/bin/env LD_LIBRARY_PATH=/path/to/mod/libc/ cp a b Env will set the environment variable and exec the other utility with that environment....

What does it indicate if /proc/PID/maps shows zero for all addresses?

linux,linux-kernel

I found the discussion in Valgrind mail list when someone had the same problem. The issue was that the kernel have been patched with PaX patches, one of which doesn't allow to look at the /proc/pid/maps. The quote about the patch from wikipedia The second and third classes of attacks...

Disadvantages of calling realloc in a loop

c,memory-management,out-of-memory,realloc

When you allocate/deallocate memory many times, it may create fragmentation in the memory and you may not get big contiguous chunk of the memory. When you do a realloc, some extra memory may be needed for a short period of time to move the data. If your algorithm does...

What does `strcpy(x+1, SEQX)` do?

c,strcpy

The pointer + offset notation is used as a convenient means to reference memory locations. In your case, the pointer is provided by malloc() after allocating sufficient heap memory, and represents an array of M + 2 elements of type char, thus the notation as used in your code represents...

Syncing Vagrant VMs across different physical servers

linux,vagrant,backup,virtual-machine,sync

Vagrant doesn't inherently support this, since it's intended audience is really development environments. It seems like you're looking for something more like what VMWare vSphere does.

Force linux to use php as php55

php,linux,fedora

You can create an alias: alias php='php55' Now if you type php it uses php55...

How can I resolve the “Could not fix timestamps in …” “…Error: The requested feature is not implemented.”

linux,build,f#

This is usually a sign that you should update your mono. Older mono versions have issues with their unzip implementation

VS2012 Identifer not found when part of static lib

c,visual-studio-2012,linker,static-libraries

C++ uses something called name mangling when it creates symbol names. It's needed because the symbol names must contain the complete function signature. When you use extern 'C' the names will not be mangled, and can be used from other programming languages, like C. You clearly make the shunt library...

Segmentation Fault if I don't say int i=0

c,arrays,segmentation-fault,initialization,int

In your code, int i is an automatic local variable. If not initialized explicitly, the value held by that variable in indeterministic. So, without explicit initialization, using (reading the value of ) i in any form, like array[i] invokes undefined behaviour, the side-effect being a segmentation fault. Isn't it automatically...

Bash modify CSV to change a field

linux,bash,awk

Please save following awk script as awk.src: function date_str(val) { Y = substr(val,0,4); M = substr(val,5,2); D = substr(val,7,2); date = sprintf('%s-%s-%s',Y,M,D); return date; } function time_str(val) { h = substr(val,9,2); m = substr(val,11,2); s = substr(val,13,2); time = sprintf('%s:%s:%s',h,m,s); return time; } BEGIN { FS='|' } # ## MAIN...

scanf get multiple values at once

c,char,segmentation-fault,user-input,scanf

I'm not saying that it cannot be done using scanf(), but IMHO, that's not the best way to do it. Instead, use fgets() to read the whole like, use strtok() to tokenize the input and then, based on the first token value, iterate over the input string as required. A...

Is post-increment operator guaranteed to run instantly?

c,c89,post-increment,ansi-c

This code is broken for two reasons: Accessing a variable twice between sequence points, for other purposes than to determine which value to store, is undefined behavior. There are no sequence points between the evaluation of function parameters. Meaning anything could happen, your program might crash & burn (or more...

C binary tree sort - extending it

c,binary-tree,binary-search-tree

a sample to modify like as void inorder ( struct btreenode *, int ** ) ; int* sort(int *array, int arr_size) { struct btreenode *bt = NULL; int i, *p = array; for ( i = 0 ; i < arr_size ; i++ ) insert ( &bt, array[i] ) ;...

How does this code print odd and even?

c,if-statement,macros,logic

In binary any numbers LSB (Least Significant Bit) is set or 1 means the number is odd, and LSB 0 means the number is even. Lets take a look: Decimal binary 1 001 (odd) 2 010 (even) 3 011 (odd) 4 100 (even) 5 101 (odd) SO, the following line...

Galois LFSR - how to specify the output bit number

c,prng,shift-register

If you need bit k (k = 0 ..15), you can do the following: return (lfsr >> k) & 1; This shifts the register kbit positions to the right and masks the least significant bit....

AWK count number of times a term appear with respect to other columns

linux,shell,command-line,awk,sed

Almost same as the other answer, but printing 0 instead of blank. AMD$ awk -F, 'NR>1{a[$2]+=$3;b[$2]++} END{for(i in a)print i, a[i], b[i]}' File pear 1 1 apple 2 3 orange 0 1 peach 0 1 Taking , as field seperator. For all lines except the first, update array a. i.e...

Counting bytes received by posix read()

Dev

c,function,serial-port,posix

Yes, temp_uart_count will contain the actual number of bytes read, and obviously that number will be smaller or equal to the number of elements of temp_uart_data. If you get 0, it means that the end of file (or an equivalent condition) has been reached and there is nothing else to...

CallXXXMethod undefined using JNI in C

java,c,jni

There are few fixes required in the code: CallIntMethod should be (*env)->CallIntMethod class Test should be public Invocation should be jint age = (*env)->CallIntMethod(env, mod_obj, mid, NULL); Note that you need class name to call a static function but an object to call a method. (cls2 -> person) mid =...

Extra backslash when storing grep in a value

linux,bash

The output from set -x uses single quotes. So the outer double quotes were replaced with single quotes but you can't escape single quotes inside a single quoted string so when it then replaced the inner double quotes it needed, instead, to replace them with '' which ends the single...

C programming - Confusion regarding curly braces

c,scope

The only difference between the two is the scope of the else. Without the braces, it spans until the end of the full statement, which is the next ;, i.e the next line: else putchar(ch); /* end of else */ lastch = ch; /* outside of if-else */ With the...

How to control C Macro Precedence

c,macros

You can redirect the JOIN operation to another macro, which then does the actual pasting, in order to enforce expansion of its arguments: #define VAL1CHK 20 #define NUM 1 #define JOIN1(A, B, C) A##B##C #define JOIN(A, B, C) JOIN1(A, B, C) int x = JOIN(VAL,NUM,CHK); This technique is often used...

How to read string until two consecutive spaces?

c,format,sscanf,c-strings

The scanf family of functions are good for simple parsing, but not for more complicated things like you seem to do. You could probably solve it by using e.g. strstr to find the comment starter '//', terminate the string there, and then remove trailing space....

Loop through database table and compare user input

mysql,c

If you are only looking for fields that match the input, you'll want to search the database using the input string. In other words, write your query string so that it only gives you results that match the user input. This will be much faster than searching through every returned...

What are correct permissions for Linux Apache2 PHP 5.3 log file?

php,linux,apache,logging,permissions

I'd simply set its owner to apache user. This will give you the name of apache user : ps aux | grep httpd In my case (CentOS), it's 'apache' but sometimes it's 'www-data'... chown apache:apache /var/log/httpd/php_errors.log chmod 600 /var/log/httpd/php_errors.log ...

Array breaking in Pebble C

c,arrays,pebble-watch,cloudpebble

The problem is this line static char *die_label = 'D'; That points die_label to a region of memory that a) should not be written to, and b) only has space for two characters, the D and the 0 terminator. So the strcat is writing into memory that it shouldn't be....

Text justification C language

c,text,alignment

From printf's manual: The field width An optional decimal digit string (with nonzero first digit) specifying a minimum field width. If the converted value has fewer characters than the field width, it will be padded with spaces on the left (or right, if the left-adjustment flag has been given). Instead...

How to append entry the end of a multi-line entry using any of stream editors like sed or awk

linux,bash,awk,sed,sh

Here's a sed version: /^Host_Alias/{ # whenever we match Host_Alias at line start : /$/{N;b} # if backslash, append next line and repeat s/$/,host25/ # add the new host to end of line } If you need to add your new host to just one of the host aliases, adjust...

Passing int using char pointer in C

c,exec,ipc

Programs simply do not take integers as arguments, they take strings. Those strings can be decimal representations of integers, but they are still strings. So you are asking how to do something that simply doesn't make any sense. Twenty is an integer. It's the number of things you have if...

How does ((a++,b)) work? [duplicate]

c,function,recursion,comma

In your first code, Case 1: return reverse(i++); will cause stack overflow as the value of unchanged i will be used as the function argument (as the effect of post increment will be sequenced after the function call), and then i will be increased. So, it is basically calling the...

Reverse ^ operator for decryption

c,algorithm,security,math,encryption

C Read From Dev Input Event Center

This is not a power operator. It is the XOR operator. The thing that you notice for the XOR operator is that x ^ k ^ k x. That means that your encryption function is already the decryption function when called with the same key and the ciphertext instead...

Set precision dynamically using sprintf

c,printf,format-string

Yes, you can do that. You need to use an asterisk * as the field width and .* as the precision. Then, you need to supply the arguments carrying the values. Something like sprintf(myNumber,'%*.*lf',A,B,a); Note: A and B need to be type int. From the C11 standard, chapter §7.21.6.1, fprintf()...

linux running command as root from c code that run as normal user

c++,linux

A workaround is to modify the sudoers file and remove the requirement of a password from your user ID for a particular script to have sudo privileges. Enter sudo visudo After this, add the details in the following manner. username ALL=(ALL) NOPASSWD: /path/to/script Another method would be to pipe the...

Does realloc() invalidate all pointers?

c,pointers,dynamic-memory-allocation,behavior,realloc

Yes, ptr2 is unaffected by realloc(), it has no connection to realloc() call whatsoever(as per the current code). However, FWIW, as per the man page of realloc(), (emphasis mine) The realloc() function returns a pointer to the newly allocated memory, which is suitably aligned for any kind of variable and...

AWK write to new column base on if else of other column

linux,bash,shell,awk,sed

You can use: awk -F, 'NR>1 {$0 = $0 FS (($4 >= 0.7) ? 1 : 0)} 1' test_file.csv ...

Infinite loop with fread

c,arrays,loops,malloc,fread

If you're 'trying to allocate an array 64 bytes in size', you may consider uint8_t Buffer[64]; instead of uint8_t *Buffer[64]; (the latter is an array of 64 pointers to byte) After doing this, you will have no need in malloc as your structure with a 64 bytes array inside is...

getchar() not working in c

c,while-loop,char,scanf,getchar

C Read From Dev Input Event Free

That's because scanf() left the trailing newline in input. I suggest replacing this: ch = getchar(); With: scanf(' %c', &ch); Note the leading space in the format string. It is needed to force scanf() to ignore every whitespace character until a non-whitespace is read. This is generally more robust than...

Segmentation fault with generating an RSA and saving in ASN.1/DER?

c,openssl,cryptography,rsa

pub_l = malloc(sizeof(pub_l)); is simply not needed. Nor is priv_l = malloc(sizeof(priv_l));. Remove them both from your function. You should be populating your out-parameters; instead you're throwing out the caller's provided addresses to populate and (a) populating your own, then (b) leaking the memory you just allocated. The result is...

Is there Predefined-Macros define about byte order in armcc

c,armcc,predefined-macro

Well according to this page: http://www.keil.com/support/man/docs/armccref/armccref_BABJFEFG.htm You have __BIG_ENDIAN which is defined when compiling for a big endian target....

how to modify an array value with given index?

arrays,linux,bash

You don't need the quotes. Just use ${i}, or even $i: pomme[${i}]=' Or pomme[$i]=' ...

Does strlen() always correctly report the number of char's in a pointer initialized string?

c,strlen

What strlen does is basically count all bytes until it hits a zero-byte, the so-called null-terminator, character '0'. So as long as the string contains a terminator within the bounds of the memory allocated for the string, strlen will correctly return the number of char in the string. Note that...

Delete some lines from text using Linux command

linux,shell,sed,grep,pattern-matching

The -v option to grep inverts the search, reporting only the lines that don't match the pattern. Since you know how to use grep to find the lines to be deleted, using grep -v and the same pattern will give you all the lines to be kept. You can write...

Linux-wget command

linux,shell,wget

Try this to create a string variable n, with no leading whitespace (thanks @011c): n='10.0.0.135.527' wget http://infamvn:8081/nexus/content/groups/LDM_REPO_LIN64/com/infa/com.infa.products.ldm.ingestion.server.scala/'$n'-SNAPSHOT/com.infa.products.ldm.ingestion.server.scala-'$n'-20150622.210643-1-sources.jar ...

Program to reverse a string in C without declaring a char[]

c,string,pointers,char

Important: scanf(' %s', name); has no bounds checking on the input. If someone enters more than 255 characters into your program, it may give undefined behaviour. Now, you have the char array you have the count (number of char in the array), why do you need to bother doing stuffs...

How to increment the value of an unsigned char * (C)

c++,c,openssl,byte,sha1

I am assuming your pointer refers to 20 bytes, for the 160 bit value. (An alternative may be text characters representing hex values for the same 160 bit meaning, but occupying more characters) You can declare a class for the data, and implement a method to increment the low order...

C++ / C #define macro calculation

c++,c,macros

How To Read /dev/input/event

Are DETUNE1 and DETUNE2 calculated every time it is called? Very unlikely. Because you are calling sqrt with constants, most compilers would optimize the call to the sqrt functions and replace it with a constant value. GCC does that at -O1. So does clang. (See live). In the general...

NASM: copying a pointer from a register to a buffer in .data

Linux Dev Input

linux,assembly,nasm,x86-64

The problem is, you don't have debug info for the ptr type, so gdb treats it as integer. You can examine its real contents using: (gdb) x/a &ptr 0x600124 <ptr>: 0x7fffffffe950 (gdb) p/a $rsp $3 = 0x7fffffffe950 Of course I have a different value for rsp than you, but you...

Ignore first few lines and last few lines in a file Linux

linux,awk

awk cannot look ahead so you'll have to save the lines. awk 'NR>2{if(z!=')print z;z=y;y=x;x=$0}' file Practically zero memory overhead...

-->

The ReadConsoleInput function can be used to directly access a console's input buffer. When a console is created, mouse input is enabled and window input is disabled. To ensure that the process receives all types of events, this example uses the SetConsoleMode function to enable window and mouse input. Then it goes into a loop that reads and handles 100 console input events. For example, the message 'Keyboard event' is displayed when the user presses a key and the message 'Mouse event' is displayed when the user interacts with the mouse.