Skip to content

Instantly share code, notes, and snippets.

@aleksmk
Forked from gdamjan/pedometer.c
Created December 17, 2010 14:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aleksmk/745027 to your computer and use it in GitHub Desktop.
Save aleksmk/745027 to your computer and use it in GitHub Desktop.
... and the idea gave birth to a fruit
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#define INTERFACE "wlan0"
#define IOBASE 0x0378 /* printer port base address */
#define PWM_PERIOD 1000 /* micro seconds */
#define MAX_DUTY_CYCLE 650 /* micro seconds */
#define MAX_RX_RATE (3500000 / 8) /* 4 mbit/s */
#define MAX_TX_RATE (760000 / 8) /* 500kbit/s */
#define REFRESH_INTERVAL 0.5 /* 0.5 seconds */
#define MICROSECONDS 1000000
#define LINE_BUFFER 4096 /* Size of buffer for reading /proc/net/dev */
int sendport(int i)
{
if (!ioperm(IOBASE, 1, 1)) {
outb((unsigned char)i, IOBASE);
return 1;
}
else { return 0; }
}
/*
duty_cycle in percent 0-100%
always sleeps PWM_PERIOD uS
*/
void pwm(int percent)
{
unsigned int duty_cycle;
if (percent > 100)
percent = 100;
duty_cycle = MAX_DUTY_CYCLE * percent / 100;
if (duty_cycle > 0) {
sendport(1);
usleep(duty_cycle);
}
sendport(0);
usleep(PWM_PERIOD - duty_cycle);
}
void get_bytes(unsigned long *receive, unsigned long *transmit)
{
char line[LINE_BUFFER];
unsigned long a[16];
int k;
FILE *fd = fopen("/proc/net/dev", "r");
while (fgets(line, sizeof(line), fd)) {
k = sscanf(line, " " INTERFACE ": %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
&a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &a[6], &a[7],
&a[8], &a[9], &a[10], &a[11], &a[12], &a[13], &a[14], &a[15]);
if (k)
break;
}
fclose(fd);
*receive = a[0];
*transmit = a[8];
}
void sig_handler(int signum) {
printf("Reiceived %d signal\nShutting down...", signum);
pwm(0);
exit(0);
}
int main(int argc, char* argv[])
{
unsigned long receive, prev_receive, transmit, prev_transmit;
unsigned long tx_rate, rx_rate;
unsigned int usec;
get_bytes(&prev_receive, &prev_transmit);
usleep((int)(REFRESH_INTERVAL*MICROSECONDS));
signal(SIGINT, sig_handler);
while (1) {
get_bytes(&receive, &transmit);
rx_rate = (receive - prev_receive) / REFRESH_INTERVAL;
rx_rate = 100 * rx_rate / MAX_RX_RATE; // percent of MAX
tx_rate = (transmit - prev_transmit) / REFRESH_INTERVAL;
tx_rate = 100 * tx_rate / MAX_TX_RATE; // percent of MAX
printf("%lu%% %lu%%\n", rx_rate, tx_rate);
prev_transmit = transmit;
prev_receive = receive;
usec = 0;
while (usec < REFRESH_INTERVAL * MICROSECONDS) {
pwm(rx_rate);
usec += PWM_PERIOD;
}
}
}
@gdamjan
Copy link

gdamjan commented Apr 2, 2011

pwm((tx_rate > rx_rate) ? tx_rate : rx_rate)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment