in this code, I am creating two threads (joystick and motor). The intention of the joystick thread is to ask the user to input a certain speed integer value (for eg. 200). From my understanding, this integer value must be converted to a string in-order for the motor thread to receive this string value and convert it back to an integer value, before passing it into my application.
The result of the compiled code in GCC is my motor application receives a speed of zero despite a user input of any other numbers, and hence, it is not moving. May I know if I had done the conversion from integer to string or vice versa wrongly?
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <semaphore.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
#define MAX_LEN 128
//char n[1024];
pthread_mutex_t lock= PTHREAD_MUTEX_INITIALIZER;
int string_read=FALSE;
pthread_cond_t cond;
void * joystick()
{
while (1)
{
int s;
char str[7];
while(string_read);
pthread_mutex_lock(&lock);
printf("Enter speed: ");
scanf("%d", &s);
snprintf(str, 7, "%d", s); //Convert int to string: itoa or snprintf
//itoa (j, n, 10);
//printf ("Decimal: %s\n", n);
string_read=TRUE;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
}
}
void * motor()
{
while (1)
{
pthread_mutex_lock(&lock);
while (!string_read)
pthread_cond_wait(&cond,&lock);
char *s = "s"; //How to receive the string value from joystick()?
int val = atoi(s);
printf ("Integer value of string is %d\n", val);
char buffer [MAX_LEN];
system ("./SmcCmd --resume"); //WORKING
snprintf (buffer, MAX_LEN, "./SmcCmd --speed %d", val); //WORKING
int status = system(buffer); //WORKING
string_read=FALSE;
pthread_mutex_unlock(&lock);
}
}
int main ()
{
int status;
pthread_t tj, tm;
pthread_create(&tj, NULL, joystick, NULL);
pthread_create(&tm, NULL, motor, NULL);
pthread_join(tj, NULL);
pthread_join(tm, NULL);
return 0;
}