C Program to Police Bicycle Lamp Hacker

How to write a C Program to Police Bicycle Lamp Hacker in C Programming Language ?


Solution For C Program :

/*
 * Policyjna Lampa Rowerowa Hackera
 */

#define F_CPU 1000000UL // Define the speed the clock is running at.
                        // Used for the delay.h functions
#include <avr/io.h>
#include <avr/sleep.h>
#include <util/delay.h>
// Outputs
#define blueLED     PB0
#define redLED      PB1
#define whiteLED    PB2
#define speaker     PB4
// Inputs
#define reedSwitch  PB3
// Config
#define lowFreq    145   // 145 -  440Hz
#define highFreq    45   //  45 - 1400Hz
#define stepsUp    100
#define stepsDown  200
#define multiUp     ( lowFreq - highFreq ) / stepsUp
#define multiDown   ( lowFreq - highFreq ) / stepsDown
#define sleep       10

char blinkCounter = 0;
int  stopCounter  = 0;
char reset_cntr __attribute__ ((section (".noinit")));
char mode       __attribute__ ((section (".noinit")));  // biała lampa / policja

// Prototypes
void Delay_ms       ( int cnt );
void init_io        ( void );
void ResetHandler   ( void );
void PoliceLamp     ( void );
void WhiteLamp      ( void );
void Sound          ( char );
void Blink          ( void );
void PowerOff       ( void );


// Functions
void Delay_ms( int cnt )
{
  while( cnt-- > 0 ) _delay_ms( 1 );
}
void init_io( void )
{
  if ( mode )
  { // Police Lamp
    DDRB   = ( 1 << redLED ) | ( 1 << blueLED ) | ( 1 << speaker ); // Set pins as outputs
 
    // TCCR1: Timer/Counter1 Control Register
    // CTC1 PWM1A COM1A1 COM1A0 CS13 CS12 CS11 CS10
    // Prescale Select
    TCCR1 = ( 0 << CS13   ) | ( 1 << CS12    ) | ( 0 << CS11    ) | ( 1 << CS10 );
    //General Timer/Counter Control Register
    GTCCR  = ( 1 << PWM1B  ) | ( 1 << COM0B1 ) | ( 0 << COM0B0 );
//    OCR1A = 100; // wtf
    OCR1B = 5; // szerokość impulsu
    OCR1C = 0; // czestotliwosc
  }
  else
  { // White Lamp
    DDRB = ( 1 << whiteLED ); // Set pins as outputs
  }

  PORTB = ( 1 << reedSwitch ); // włącza PullUp na WEJŚCIU
}
void ResetHandler( void )
{
// MCUSR: 0 0 0 0 WDRF BORF EXTRF PORF
  if ( MCUSR & 0x1 ) // PORF
  {
    reset_cntr = 0;
    mode       = 0;
    MCUSR      = 0;
  }
  if ( MCUSR & 0x2 ) // EXTRF
  {
    reset_cntr++;
    MCUSR      = 0;
  }

  /* // BORF nie działa w moim attiny :/
  if (MCUSR & 0x3 ) // BORF
  {
    MCUSR      = 0;
    PowerOff();
  }
  */

  if ( reset_cntr >= 2 )
  {
    mode       = ~mode;
    reset_cntr = 0;
  }
}
void Sound ( char i )
{
  OCR1C = i;
  Delay_ms( sleep );
}


void Blink( void )
{
  blinkCounter++;
  if ( blinkCounter % 6 == 0 ) PORTB &= ~( ( 1 << redLED  ) |
                                           ( 1 << blueLED ) );
  if ( blinkCounter % 6 == 3 )
  {
    if ( blinkCounter < 60 )   PORTB |=    ( 1 << redLED  );
    else                       PORTB |=    ( 1 << blueLED );
  }
  if ( blinkCounter > 120 ) blinkCounter = 0;
}


void PoliceLamp ( void )
{

  while ( stopCounter++ < 10 ) // was 2
  {
    for (int i = stepsUp; i >= 1; i-- )
    {
      Sound( i * multiUp + highFreq );
      Blink();
      if ( ( PINB & ( 1 << reedSwitch ) ) == 0 ) stopCounter = 0;
    }
 
    for (int i = 1; i <= stepsDown; i++ )
    {
      Sound( i * multiDown + highFreq );
      Blink();
      if ( ( PINB & ( 1 << reedSwitch ) ) == 0 ) stopCounter = 0;
    }
    reset_cntr = 0;
  }
  Sound( 0 );
}

void WhiteLamp( void )
{

  while ( stopCounter++ < 10 ) // was 2
  {
    for ( int i = 1; i < 300; i++ )
    {
      PORTB |=  ( 1 << whiteLED );
      Delay_ms( 5 );
   
      //PORTB &= ~( 1 << whiteLED );
      Delay_ms( 3 );
      if ( ( PINB & ( 1 << reedSwitch ) ) == 0 ) stopCounter = 0;
    }
    reset_cntr = 0;
  }
}
void PowerOff ( void )
{
  PORTB = 0;
  DDRB =  0; // ważne dla oszczędzenia prądu!
  set_sleep_mode( SLEEP_MODE_PWR_DOWN );
  sleep_mode(  );
}
//Main Function
int main( void )
{
  ResetHandler(  );

  init_io(  );

  if ( mode ) PoliceLamp(  );
  else        WhiteLamp (  );

  PowerOff(  );
}

C Program to LightSaber

How to write a C Program to Lightsaber in C Programming Language ?


Solution For C Program :

#include <Adafruit_NeoPixel.h>
#include<Wire.h>

#define PIN 6
Adafruit_NeoPixel strip = Adafruit_NeoPixel(1, PIN, NEO_GRB + NEO_KHZ800);
int color;
const int MPU_addr=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
void setup() {
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);  // PWR_MGMT_1 register
  Wire.write(0);     // set to zero (wakes up the MPU-6050)
  Wire.endTransmission(true);
    strip.begin();
  strip.show();
  Serial.begin(9600);
}
/*Light Saber*/
void loop(){
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
  Wire.endTransmission(false);
  Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
  AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)  
  AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
  AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
 // Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
 // GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
 // GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
//  GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
int X = map(AcX, -32768, 32768, 0,255);
int Y = map(AcY, -32768, 32768, 0,255);
int Z = map(AcZ, -32768, 32768, 0,255);

 uint16_t i;
 for (i = 0; i < strip.numPixels(); i++) {
strip.setPixelColor(i, strip.Color(X,Y,Z));
 }
 strip.show();
}

C Program Recursive

How to write a C Program Recursive in C Programming Language ?


Solution For C Program :

C Program to Check Prime Use Loop And Recursive

How to write a C Program to Check Prime Use Loop And Recursive in C Programming Language ?


Solution For C Program :
/*Check Prime Use Loop And Recursive*/

C Program to Calculate Grid Size, Initialized Number onto tile, Initialize Tile Loop and If Grid is Even, Swap The Tiles Numbered 1 and 2

How to write a C Program to Calculate Grid Size, Initialized Number onto tile, Initialize Tile Loop and If Grid is Even, Swap The Tiles Numbered 1 and 2 in C Programming Language ?

Solution For C Program:
/*C Program to Calculate Grid Size, Initialized Number onto tile, Initialize Tile Loop and If Grid is Even, Swap The Tiles Numbered 1 and 2*/

C Program To Calculate The pi By Maths Expression

How to write a C Program to calculate the pi by maths expression Using a array of willing value to calculated in C Programming Language ?

Solution:
/* Program to calculate the pi by math expression
  Using a array of willing value to calculated */
#include <stdio.h>
#include <stdlib.h>
#include <math.h> //to take the pi

double CountPi(int); //function to calculate the pi's expression

int main(void)
{
printf("Exactly value of pi to compare = %1.17f\n\n", M_PI);

int i = 0; //variable to count all willing results in to array
int N[6] = {1 ,2 ,10, 50, 100, 500}; //array with elements of willing number to calculate
double my_pi = 0.0; //the current pi by specific value

while(i < (sizeof(N) / sizeof(N[0]))) //until all the numbers of array calculated
{
double dif_pi = 0.0; //for the different of exactly pi
my_pi = CountPi(N[i]); //calculate the pi with specific value
dif_pi = my_pi - M_PI;
printf("The difference is %1.17f\n\n", dif_pi);
i++;
}
return 0;
}

/* Function to calculate the pi by math expresion */
double CountPi(int n) //n = N
{
int i = 1; //number to calculate until n

double sum = 0.0; //total addition of expression

double nume_1,s_fr1,deno_1; //nume_1->numerator , deno_1->denominator , s_fr1->fraction of math expression

while(i <= n) //addition until the willing value
{
nume_1 = pow(i - 0.5 , 2);
deno_1 = pow( n , 2);
s_fr1 = 1.0 + (nume_1 / deno_1);
sum += 1.0 / s_fr1;
i++;
}
sum *= 4;
sum /= n;
printf("pi(%d) = %1.17f\n", n, sum);
return sum; //returning the calculating value of pi
}

C del programma: si assume che B è un array di n> 0 cifre binarie, la seguente funzione calcola il valore decimale rappresentato da b in forma binaria

C del programma: si assume che B è un array di n> 0 cifre binarie, la seguente funzione calcola il valore decimale rappresentato da b in forma binaria


/*Assumiamo che b sia un array di n>0 cifre binarie, la funzione che segue calcola il valore decimale rappresentato da b in forma binaria*/

#include <stdio.h>

int Bin2Dec(int b[], int n){

int decimale=0;
int p;
p=1;

for(int k=0; k<n; k++){

decimale=decimale+b[k]*p;
p=p*2;
}
return decimale;
}

int main(void){

int n;

printf("Inserisci la grandezza dell'array; \n");
scanf("%d", &n);

int b[n];

printf("Inserisci gli elementi dell'array \n");
for(int k=0; k<n; k++){
printf("Inserisci l'elemento %d: \n", k+1);
scanf("%d", &b[k]);
}

printf("Il decimanle è: %d", Bin2Dec(b, n));
return 0;


}

C or C++ program to print prime number

How to write a C Program to print Prime Number From a Given Value (50) in C Programming Language ?


Solution For C Program:

C or C++ Program To Print Prime Number

How to write a C or C++ program to print prime number in C Programming Language ?

This Program print first 50 prime number.

To print first 50 prime number

Solution For C Program:

C or C++ program to read marks of 4 subjects and find how many students are pass and fail with division

Write a C or C++ program to read marks of 4 subjects and find how many students are pass and fail with division.

This program to read marks of 4 subjects and find how many students are pass and fail with division.

To read marks of 4 subjects and find out how many students fall under the following categories:

a) avg<45 - Fail
b) 45 <= avg <55- Third Division
c) 55<= avg <60 - Second Division
d) 60<= avg <75 - First Division
e) avg >=75 - Distinction

Solution For C Program:

C Program to Reverse a Word

How to write a C Program to Reverse a Word in C Programming Language ?

This program reverse a word.

Solution For C Program:

Dictionary Word Search C Program

How to write a C Program to Find Dictionary Word Search ?


Solution For C Program to Find a Word in Dictionary :

Write overloaded function templates for finding the roots of the linear (a * x + b = 0) and square (a * x2 + b * x + c = 0) uravneniy.Zamechanie: in function to send coefficients of the equations.

Solution For C Program - 

Write overloaded function templates for finding the roots of the linear (a * x + b = 0) and square (a * x2 + b * x + c = 0) uravneniy.Zamechanie: in function to send coefficients of the equations.


#include <iostream>
#include <math.h>
#include <windows.h>

using namespace std;

HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);



double findUnknown(int, int);
double findUnknown(double, double);

double findUnknown(int, int, int);
double findUnknown(double, double, double);

void testFindUnknow2IntType(int test, int a, int b , double expected)
{
double result = findUnknown(a,b);

if (expected == result)
{
SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN);
cout << test << " passed\n";
}
else
{
SetConsoleTextAttribute(hConsole, FOREGROUND_RED);
cout << test << " failed\n";
cout << result << " actual\n";
cout << expected << " expected\n\n";
}
}

void testFindUnknow2DoubleType(int test, double a, double b, double expected)
{
double result = findUnknown(a, b);

if (expected == result)
{
SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN);
cout << test << " passed\n";
}
else
{
SetConsoleTextAttribute(hConsole, FOREGROUND_RED);
cout << test << " failed\n";
cout << result << " actual\n";
cout << expected << " expected\n\n";
}
}

void testFindUnknow3IntType(int test, int a, int b, int c, double expected)
{
double result = findUnknown(a, b, c);

if (expected == result)
{
SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN);
cout << test << " passed\n";
}
else
{
SetConsoleTextAttribute(hConsole, FOREGROUND_RED);
cout << test << " failed\n";
cout << result << " actual\n";
cout << expected << " expected\n\n";
}
}

void testFindUnknow3DoubleType(int test, double a, double b, double c, double expected)
{
double result = findUnknown(a, b, c);

if (expected == result)
{
SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN);
cout << test << " passed\n";
}
else
{
SetConsoleTextAttribute(hConsole, FOREGROUND_RED);
cout << test << " failed\n";
cout << result << " actual\n";
cout << expected << " expected\n\n";
}
}


void main()
{
int menuButton = 0;
int show = 0;

int a = 0;
int b = 0;
int c = 0;

cout << "1.Line\n2.Square\n";
cin >> menuButton;

if (menuButton == 1)
{
/*cout << "1. a*x + b = 0" << endl;
cin >> a >> b;

cout << findUnknown(a, b) << endl;*/

testFindUnknow2IntType(1, 2, 4, -2);
testFindUnknow2IntType(2, 1, 5, -5);
testFindUnknow2DoubleType(3, 4, 2, 0.5);
testFindUnknow2DoubleType(4, 5, 2.5 , 0.5);

}

if (menuButton == 2)
{
/*cout << "2. a*x^2 + b*x + c = 0" << endl;
cin >> a >> b >> c;

show = findUnknown(a, b, c);
cout << "X2 = " << show << endl;*/

testFindUnknow3IntType(1, 1, -2, -3, -1);
testFindUnknow3IntType(2, 1, 5, 6, -3);
testFindUnknow3DoubleType(3, 0.5, 6, 0, -12);
testFindUnknow3DoubleType(4, 12, 5, -0.5, -0.5);

}
}


double findUnknown(int a, int b)
{
double x = b * (-1) / a;
return x;
}

double findUnknown(double a, double b)
{
double x = b / a;
return x;
}

double findUnknown(int a, int b, int c)
{
int discriminant = b*b - 4 * a * c;

double x1 = (b*(-1) - sqrt(discriminant)) / 2 * a;
//double x2 = (b*(-1) - sqrt(discriminant)) / 2 * a;

return x1;
}

double findUnknown(double a, double b, double c)
{
double discriminant = b*b - 4 * a * c;

double x1 = (b*(-1) - sqrt(discriminant)) / ( 2 * a );
//double x2 = (b*(-1) - sqrt(discriminant)) / ( 2 * a );

return x1;
}

C program acquires keyboard 10 numbers for each of these numbers to determine if it is a first issue, by printing immediately message should at the end, if none of the numbers you entered was a first issue, print an appropriate message.

Write a C program acquires keyboard 10 numbers for each of these numbers to determine if it is a first issue, by printing immediately message should at the end, if none of the numbers you entered was a first issue, print an appropriate message.

Solution For C Program:

C Depth First Search

How to write a C Program Depth First Search in C Programming Language ?


Solution For C Program :

C Program Generates 10 Random Integers Between 0 and 99.

How to write a C Program that Generates 10 Random Integers Number Between 0 and 99 in C Programming Language ?


This C program generates 10 random integers between 0 and 99. 
The srand() function generates a seed value for the rand() function.

Solution For C Program:

C Parse Graph From .col File

How to write a C Program - C Parse Graph From .col File in C Programming Language ?


Solution For C Program:
#include<stdio.h>
#include<stdlib.h>

//file name
char str[] = "sample.col\0";

//declare enum without specific name
enum {
G_PROPERTY = 'p',
G_EDGE = 'e',
BUF_SIZE = 64
};

struct node {
unsigned id;
struct node *next;
};

struct graph {
unsigned nOfNodes;
unsigned nOfEdges;

struct {
unsigned length;
        struct node *first;
        struct node *last;
} *nodes;

int (*add_edge)(struct graph*, unsigned, unsigned);

//gr->addEdge()
};

//allocate memory for graph and initialize graph
struct graph *init_graph (void);

//add edge to graph
int graph_add_edge (struct graph *g, unsigned from, unsigned to);

//parse graph
int parse_graph (FILE *file, struct graph *g);

//parse property file, called from parse_graph()
int parse_property_line (char line[], struct graph *g);

//parse edge, called from parse_graph()
int parse_edge (char line[], struct graph *g);

void print_graph (struct graph *g);

//verbose
int verbose = 0;

int main (void) {
//open file
FILE *file = fopen("sample.col", "r");

//declare and assign variable for graph
struct graph *g = init_graph();

//parse graph
parse_graph(file, g);

//close file
fclose(file);

//print graph
print_graph(g);

//return 0
return 0;
}

int parse_graph (FILE *file, struct graph *g) {
//check if file parameter is null
if (file == NULL) {
return 1;
}

//declare and assign variable for line
char line[BUF_SIZE] = {};

while (fgets(line, (sizeof line) / sizeof(char), file) != NULL) {
switch (line[0]) {
case G_PROPERTY:
parse_property_line(line, g);
break;
case G_EDGE:
parse_edge(line, g);
break;
default:
if (verbose == 1) {
printf("[DEBUG] failure in line: %s", line);
}

break;
}
}

//return 0
return 0;
}

int parse_property_line (char line[], struct graph *g) {
//delcare and assign variable for number of nodes
unsigned nOfNodes = 0;
unsigned nOfEdges = 0;

//scan readed line and check, if line format is correct
if (sscanf(line, "p edge %u %u", &nOfNodes, &nOfEdges) < 2) {
return 1;
}

//print number of nodes to console
//printf("Number of nodes: %u\nNumber of edges: %u\n", nOfNodes, nOfEdges);

//check, if graph is already initialized
if (g->nOfNodes != 0) {
//print to console
puts("Warning: file contains two property lines.");

//return 2
return 2;
}

//alocate memory for node list
g->nodes = calloc((nOfNodes), sizeof *g->nodes);

//check, if nodes could be allocated successfully
if (g->nodes == NULL) {
//print error to console
perror("parse_property_line");

//exit with error code
exit(EXIT_FAILURE);
}

//set number of nodes
g->nOfNodes = nOfNodes;

//set number of edges
g->nOfEdges = nOfEdges;

return 0;
}

int parse_edge (char line[], struct graph *g) {
//declare variables for from and to nodes
unsigned from = 0;
unsigned to = 0;

//scan readed line and check, if line format is correct
if (sscanf(line, "e %u %u", &from, &to) < 2) {
return 1;
}

//printf("Edge from %u to %u\n", from, to);

//add edge to graph
return graph_add_edge(g, from, to);
}

struct graph *init_graph (void) {
struct graph *g = malloc(sizeof *g);

//check, if malloc was successful
if (g == NULL) {
//error function from stdio.h, prints error message to console
perror("init_graph");

//exit with error code
exit(EXIT_FAILURE);
}

//set number of nodes and edges to 0, because graph doesnt have nodes and edges yet
g->nOfNodes = 0;
g->nOfEdges = 0;

//clear node list
g->nodes = NULL;

//return graph struct
return g;
}

int graph_add_edge (struct graph *g, unsigned from, unsigned to) {
//check, if node is in graph
if (g->nOfNodes < from || g->nOfNodes < to) {
//print to console
printf("Edge from %u to %u isnt in graph.\n", from, to);

//return 1
return 1;
}

//check, if edge is already in graph to avoid redundancy
for (struct node *n = g->nodes[from - 1].first; n != NULL; n = n->next) {
if (n->id == to) {
//print warning to console
printf("Warning: redundant edge (%u, %u).\n", from, to);

//return with error code
return 1;
}
}

//allocate memory for node
struct node *n = malloc(sizeof *n);

//check, if allocation was successful
if (n == NULL) {
//print error message to console
perror("graph_add_edge");

//exit with error code
exit(EXIT_FAILURE);
}

//set if to to edge
n->id = to;

//set next node to null, because node doesnt have an next node yet
n->next = NULL;

//check, if we insert the first node in graph
if (g->nodes[from - 1].length == 0) {
//set node to first node
g->nodes[from - 1].first = n;

//set node to last node
g->nodes[from - 1].last = n;
} else {
//set neighboor node
g->nodes[from - 1].last->next = n;

//set new last node in graph
g->nodes[from - 1].last = n;
}

//increment count of neighboor nodes for node
g->nodes[from - 1].length++;

//increment count of edges
//g->nOfEdges++;

//success, return 0
return 0;
}

void print_graph (struct graph *g) {
//print to console
printf("-------- Graph with %u nodes and %u edges --------\n", g->nOfNodes, g->nOfEdges);

//iterate through graph
for (unsigned from = 1; from <= g->nOfNodes; from++) {
//iterate through nodes, start with from - 1, because first node in file specification is 1
for (struct node *n = g->nodes[from - 1].first; n != NULL; n = n->next) {
//print to console
printf("\t(%u, %u)\n", from, n->id);
}
}

//print to console
printf("-------- END of Graph --------\n");

}

C Graph

How to write a C Program - C Graph in C Programming Language ?


Solution For C Graph:

C Program Arduino Serial PIN control for Relay

Arduino Code for relay

  Turns given PIN (exmaple 12) on for a third of a second when receiving any input through serial connection
  Recommend not using PIN13 due to signals being sent to it durning startup


  To send signal to Arduino from computer (Linux):
  echo '1' > /dev/ttyUSB0 #as root

  Created By
  Kris Occhipinti
  June 19th, 2015
  http://www.filmsbykris.com

  License GPLv3
  http://www.gnu.org/licenses/gpl-3.0.txt

Solution:

C Program to Demonstrates changing the keypad size and key values.

How to write a C Program to Demonstrates changing the keypad size and key values ?

Solution:

/* C Program to Demonstrates changing the keypad size and key values.*/
#include <Keypad.h>
#include <stdlib.h>
#include <pitches.h>

double notes[89] = {31,33,35,37,39,41,44,46,49,52,55,58,62,65,69,73,78,82,87,93,98,104,110,117,123,131,139,147,156,165,175,185,196,208,220,233,247,262,277,294,311,330,349,370,392,415,440,466,494,523,554,587,622,659,698,740,784,831,880,932,988,1047,1109,1175,1245,1319,1397,1480,1568,1661,1760,1865,1976,2093,2217,2349,2489,2637,2794,2960,3136,3322,3520,3729,3951,4186,4435,4699,4978};
const byte ROWS = 8; //four rows
const byte COLS = 8; //four columns
//define the cymbols on the buttons of the keypads
byte hexaKeys[ROWS][COLS] = {
  {1, 1, 9, 9, 17, 17, 25, 25},
  {2, 2, 10, 10, 18, 18, 26, 26},
  {3, 3, 11, 11, 19, 19, 27, 27},
  {4, 4, 12, 12, 20, 20, 28, 28},
  {5, 5, 13, 13, 21, 21, 29, 29},
  {6, 6, 14, 14, 22, 22, 30, 30},
  {7, 7, 15, 15, 23, 23, 31, 31},
  {8, 8, 16, 16, 24, 24, 32, 32}

};
byte rowPins[ROWS] = {2, 3, 4, 5, 6, 7, 8, 9}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {A8, A9, A10, A11, A12, A13, A14, A15}; //connect to the column pinouts of the keypad

//initialize an instance of class NewKeypad
Keypad kpd = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

#define trigPin 53
#define echoPin 51

void setup(){
  Serial.begin(9600);
  pinMode(49, HIGH);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop(){
  if (kpd.getKeys()){
        for (int i=0; i<LIST_MAX; i++) {  // Scan the whole key list.
            if ( kpd.key[i].stateChanged ) {  // Only find keys that have changed state.
                char j = kpd.key[i].kchar + 40;
                switch (kpd.key[i].kstate) {  // Report active key state : IDLE, PRESSED, HOLD, or RELEASED
                    case PRESSED:
                    tone(13, (notes[j] * pitchBend()), 0);
                    Serial.print(pitchBend());
                    Serial.print("\n");
                    break;
             
                    case RELEASED:
                    tone(13, 0, 1);
                }
            }
        }
    }
}

double pitchBend(){
  double duration, distance;
  digitalWrite(trigPin, LOW);  // Added this line
  delayMicroseconds(2); // Added this line
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10); // Added this line
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  Serial.print(distance);
  if (distance < 50){
    return distance/200+1;
  }
  else{
    return 1;
  }
}

C Program to Trying out socket communication between processes using the Internet protocol family.

How to write a C Program to Trying out socket communication between processes using the Internet protocol family ?

Solution:

/*
 * Trying out socket communication between processes using the Internet protocol family.
 */

#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/times.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>

#define PORT 5558
#define MAXMSG 512

/* makeSocket
 * Creates and names a socket in the Internet
 * name-space. The socket created exists
 * on the machine from which the function is
 * called. Instead of finding and using the
 * machine's Internet address, the function
 * specifies INADDR_ANY as the host address;
 * the system replaces that with the machine's
 * actual address.
 */

 void writeMessage(int fileDescriptor, char *message);
void writeMessage(int fileDescriptor, char *message);

int makeSocket(unsigned short int port) {
      int sock;
      struct sockaddr_in name;

      /* Create a socket. */
      sock = socket(PF_INET, SOCK_STREAM, 0);
      if(sock < 0) {
            perror("Could not create a socket\n");
            exit(EXIT_FAILURE);
      }
      /* Give the socket a name. */
      /* Socket address format set to AF_INET for Internet use. */
      name.sin_family = AF_INET;
      /* Set port number. The function htons converts from host byte order to network byte order.*/
      name.sin_port = htons(port);
      /* Set the Internet address of the host the function is called from. */
      /* The function htonl converts INADDR_ANY from host byte order to network byte order. */
      /* (htonl does the same thing as htons but the former converts a long integer whereas
       * htons converts a short.)
       */
       /*INADDR_ANY = machine's actual address*/
      name.sin_addr.s_addr = htonl(INADDR_ANY);
      /* Assign an address to the socket by calling bind. */
      if(bind(sock, (struct sockaddr *)&name, sizeof(name)) < 0) {
            perror("Could not bind a name to the socket\n");
            exit(EXIT_FAILURE);
      }
      return(sock);
}

/* readMessageFromClient
 * Reads and prints data read from the file (socket
 * denoted by the file descriptor 'fileDescriptor'.
 */
int readMessageFromClient(int fileDescriptor) {
      char buffer[MAXMSG];
      int nOfBytes;
      nOfBytes = read(fileDescriptor, buffer, MAXMSG);
      if(nOfBytes < 0) {
            perror("Could not read data from client\n");
            exit(EXIT_FAILURE);
      }
      else
        if(nOfBytes == 0)
              /* End of file */
              return(-1);
        else
        {
              /* Data read */
              printf(">Incoming message: %s\n",  buffer);
              writeMessage(fileDescriptor, "Server: I hear you, dude...\n");
        }

      return(0);
}
void writeMessage(int fileDescriptor, char *message) {
      int nOfBytes;

      nOfBytes = write(fileDescriptor, message, strlen(message) + 1);
      if(nOfBytes < 0) {
            perror("writeMessage - Could not write data\n");
            exit(EXIT_FAILURE);
      }
}

void broadcastMessage(int serverSocket, fd_set *activeFdSet, char *message) {

    for(int i = 0; i < FD_SETSIZE; ++i)
    {
        if(FD_ISSET(i, activeFdSet)) {
            if(i!=serverSocket)
                writeMessage(i, message);
        }
    }
}

int main(int argc, char *argv[]) {
      int sock;
      int clientSocket;
      int i;
      fd_set activeFdSet, readFdSet; /* Used by select */
      struct sockaddr_in clientName;
      socklen_t size;
      char message[128];

      /* Create a socket and set it up to accept connections */
      sock = makeSocket(PORT);
      /* Listen for connection requests from clients */
      if(listen(sock,1) < 0) {
            perror("Could not listen for connections\n");
            exit(EXIT_FAILURE);
      }
      /* Initialize the set of active sockets */
      FD_ZERO(&activeFdSet);
      FD_SET(sock, &activeFdSet);
      printf("\n[waiting for connections...]\n");
      while(1) {
            /* Block until input arrives on one or more active sockets
               FD_SETSIZE is a constant with value = 1024 */
            readFdSet = activeFdSet;
            if(select(FD_SETSIZE, &readFdSet, NULL, NULL, NULL) < 0) {
                  perror("Select failed\n");
                  exit(EXIT_FAILURE);
            }
            /* Service all the sockets with input pending */
            for(i = 0; i < FD_SETSIZE; ++i)
            {
                if(FD_ISSET(i, &readFdSet)) {
                    if(i == sock) {
                          /* Connection request on original socket */
                          size = sizeof(struct sockaddr_in);
                          /* Accept the connection request from a client. */
                          clientSocket = accept(sock, (struct sockaddr *)&clientName, (socklen_t *)&size);
                          if(clientSocket < 0) {
                                perror("Could not accept connection\n");
                                exit(EXIT_FAILURE);
                          }
                          if(strncmp(inet_ntoa(clientName.sin_addr), "127.0.0.1", strlen(inet_ntoa(clientName.sin_addr))+1) == 0)
                          {
                                printf("This is the adress that wont connect\n");
                                writeMessage(clientSocket, "RIP");
                                close(clientSocket);
                                continue;
                          }
                          sprintf(message, "Server: Connect from client %s, port %d\n", inet_ntoa(clientName.sin_addr), ntohs(clientName.sin_port));
                          printf(message);
                          FD_SET(clientSocket, &activeFdSet);
                          broadcastMessage(sock, &activeFdSet, message);
                    }
                    else {
                          /* Data arriving on an already connected socket */
                          if(readMessageFromClient(i) < 0) {
                                close(i);
                                FD_CLR(i, &activeFdSet);
                          }
                    }
                }
            }
      }
}

C Program Palindrom: reliefpfeiler, otto

How to write a C Program Palindrom: reliefpfeiler, otto ?


Solution:

#include <stdio.h>
#include <stdlib.h>
// Palindrom: reliefpfeiler, otto

int isPalindrom_iter(char *pal, int strlen) {
int i;
for (i = 0; i < strlen; i++) if (pal[i] != pal[strlen - i-1]) return 0;
return 1;
}

int isPalindrom_rek(char *pal, int strlen) {
if (strlen < 1) return 1;
return (pal[0] == pal[strlen - 1]) && isPalindrom_rek(pal + 1, strlen - 2);
}



int main(void) {
char *jn[] = { "no", "yes" };
printf("Is Palindrom, %s!\n", jn[isPalindrom_iter("reliefpfeiler", 13)]);
printf("Is Palindrom, %s!\n", jn[isPalindrom_rek("reliefpfeiler", 13)]);
system("pause");

return 0;
}

C Program dec to oct

How to write a C Program Decimal to Octal Number,  ?


Solution:

#include <stdio.h>
#include <stdlib.h>

int dodaj()
{
    unsigned short int n;
    printf("Podaj liczbe: ");
    while(scanf("%hu", &n)!=1 || n<=0){
    printf("Blad danych!");
        while(getchar()!='\n');
    }
    return n;
}
int zamiana(unsigned short int n, int tab[31])
{
    int i=0,j;
    while(n>0){
    tab[i++]=n%8;
    n/=8;
    }
    j=i-1;
    return j;
}
void wyswietl(int tab[31], int j)
{
    for(j;j>=0;j--){
        printf("%d", tab[j]);
    }
}
int main()
{
    unsigned short int n;
    int j;
    int tab[31];
    n=dodaj();
    j=zamiana(n, tab);
    wyswietl(tab,j);
    return 0;
}

C Program to Recovers JPEGs from a forensic image.

Write a C Program to Recovers JPEGs from a forensic image ?


Solution:

/* Recovers JPEGs from a forensic image. */
#include <stdio.h>
#include <stdint.h>
// Makes the possibility to create a byte array
typedef uint8_t  BYTE;

//start
int main(int argc, char* argv[])
{
    //creates a buffer to store the image data
    BYTE buffer[512];
    //open card.raw
    FILE *card = fopen("card.raw","r");
    //chekc if card is null
    if(card == NULL){
        printf("cannot open file");
        return 2;
    }
    //will count the number of images encountered
    int filecount = 0;
    //creates the img FILE outside the while (to avoid the scope)
    FILE *img = NULL;
    //creates an array for the name of file (to avoid scope)
    char name[8];
    //while we can read the file
    while(fread(&buffer, 512, 1, card)){
        //if the jpg signature is found in file
        if(buffer[0] ==  0xff  && buffer[1] ==  0xd8  && buffer[2] ==  0xff  && 
        (buffer[3] ==  0xe1  || buffer[3] ==  0xe2  || buffer[3] ==  0xe3  || 
         buffer[3] ==  0xe4  || buffer[3] ==  0xe5  || buffer[3] ==  0xe6  || 
         buffer[3] ==  0xe7  || buffer[3] ==  0xe0  || buffer[3] ==  0xe8  || 
         buffer[3] ==  0xe9  || buffer[3] ==  0xea  || buffer[3] ==  0xeb  || 
         buffer[3] ==  0xec  || buffer[3] ==  0xed  || buffer[3] ==  0xef ) ){
            //if the image is already open, close it
            if(img != NULL){
                fclose(img);
            }
            //just make this for the naming the file
            if(filecount <= 9){
                sprintf(name, "00%d.jpg", filecount);
            } else if (filecount >= 10){
                sprintf(name,"0%d.jpg",filecount);
            }
            //open the file
            img = fopen(name, "w");
            //check if we can open it
            if (img == NULL){
                return 3;
            }
            //increments the file counter
            filecount++;
            //writes the first 512 bytes to file
            fwrite(&buffer, 512, 1, img);
        } else{
            // if an image is already open, close it
            if(img)
                fclose(img);
            //and reopen to ensure we are writing in the same file over the time
            img = fopen(name, "w");
            //write to file
            fwrite(&buffer, 512, 1, img);
         }
    }
    //close pointers
    fclose(card);
    fclose(img);
    
    //Be happy!
    return 0;
}

C Program to Client That Calls The Remote Procedure

Write a C Program to Client That Calls The Remote Procedure ?


Solution:

//La Spada Cristina 0000669010


/* RPC_Client.c: client che chiama la procedura remota */

#include <stdio.h>
#include <rpc/rpc.h>
#include "RPC_xFile.h"

#define COMMAND_SIZE 20

main(int argc, char *argv[]){

CLIENT *cl;
int num;
char *server, *stringa_op1;
char buffer[COMMAND_SIZE], c;
int *risultato_op2; //serve come risultato della funzione in .x che mi restituisce un int

Struttura1 *struttura1;

if (argc < 2) {
fprintf(stderr, "Usage: %s <serverhost>\n", argv[0]);
exit(1);
}
server = argv[1];


cl = clnt_create(server, FILEX, FILEVERS, "udp");

if (cl == NULL) {
clnt_pcreateerror(server);
exit(2);
}

stringa_op1 = (char *)malloc(strlen(buffer) + 1);

do{
printf("\nChe operazione vuoi fare? (A:visualizza dettagli volo, B: elimina volo o uscire) "); 
gets(buffer);


if (buffer == NULL) {
break;
}
else if (strcmp(buffer, "A") == 0) {
printf("inserire id volo: \n");
gets(stringa_op1);
struttura1 = visualizza_dati_1(&stringa_op1, cl); 

if (struttura1->error == -1)
{
printf("l'id non esiste\n");
exit(3);
}
else
{
printf("Trovato volo: \nid: %s\nnumero: %s\norario: %s\npasseggero: %s\ngate: %s\n\n", struttura1->id, struttura1->numero, struttura1->ora, struttura1->nome, struttura1->gate);
}//operazione1

else if (strcmp(buffer, "A") == 0) {
printf("Inserisci id volo da cancellare: ");
gets(stringa_op1);

risultato_op2 = elimina_volo_1(&stringa_op1, cl);
if (risultato_op2== -1)
{
printf("errore nella eliminazione\n");
exit(4);

}
else
{
printf("Eliminazione effettuata correttamente\n");
}
}//operazione2
}while(buffer != NULL && strcmp(buffer, "uscire") != 0);


// Libero le risorse distruggendo il gestore di trasporto
free(stringa_op1);

clnt_destroy(cl);
printf("\nRPC_Client Termino...\n");
exit(0);
}

C Program readers/writers

Write a C Program readers/writers ?


Solution:

int writers = 0;
int readers = 0;
bool writing = false;

write() {
writers += 1;
await(readers == 0);
await(writing == false);
writing = true;
}

endWrite() {
writing = false;
writers -= 1;
}

read() {
await(writers == 0);
readers += 1;
}

endRead() {
readers -= 1;
}