主题 : mini2440上的PWM编程示例源代码(Linux) 复制链接 | 浏览器收藏 | 打印
这个阶段正是我事业的上升期,我怎么能走得开呢?
级别: 精灵王
UID: 3197
精华: 3
发帖: 770
金钱: 6995 两
威望: 5398 点
贡献值: 21 点
综合积分: 1600 分
注册时间: 2008-12-30
最后登录: 2010-12-31
楼主  发表于: 2009-04-10 16:25

 mini2440上的PWM编程示例源代码(Linux)

本程序摘自友善光盘 \linux\examples.tgz(解压可得)

不管是友善提供linux-2.6.13还是linux-2.6.29内核,均已经提供了pwm控制蜂鸣器的驱动源代码,它们的名字或者路径可能不同,要自己仔细看看了。
这里的源代码是使用底层驱动的上层应用示例,它是命令行程序:

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <stdlib.h>
#define PWM_IOCTL_SET_FREQ  1
#define PWM_IOCTL_STOP   2
#define ESC_KEY  0x1b
static int getch(void)
{
 struct termios oldt,newt;
 int ch;
 if (!isatty(STDIN_FILENO)) {
  fprintf(stderr, "this problem should be run at a terminal\n");
  exit(1);
 }
 // save terminal setting
 if(tcgetattr(STDIN_FILENO, &oldt) < 0) {
  perror("save the terminal setting");
  exit(1);
 }
 // set terminal as need
 newt = oldt;
 newt.c_lflag &= ~( ICANON | ECHO );
 if(tcsetattr(STDIN_FILENO,TCSANOW, &newt) < 0) {
  perror("set terminal");
  exit(1);
 }
 ch = getchar();
 // restore termial setting
 if(tcsetattr(STDIN_FILENO,TCSANOW,&oldt) < 0) {
  perror("restore the termial setting");
  exit(1);
 }
 return ch;
}
static int fd = -1;
static void close_buzzer(void);
static void open_buzzer(void)
{
 fd = open("/dev/pwm", 0);
 if (fd < 0) {
  perror("open pwm_buzzer device");
  exit(1);
 }
 // any function exit call will stop the buzzer
 atexit(close_buzzer);
}
static void close_buzzer(void)
{
 if (fd >= 0) {
  ioctl(fd, PWM_IOCTL_STOP);
  close(fd);
  fd = -1;
 }
}
static void set_buzzer_freq(int freq)
{
 // this IOCTL command is the key to set frequency
 int ret = ioctl(fd, PWM_IOCTL_SET_FREQ, freq);
 if(ret < 0) {
  perror("set the frequency of the buzzer");
  exit(1);
 }
}
static void stop_buzzer(void)
{
 int ret = ioctl(fd, PWM_IOCTL_STOP);
 if(ret < 0) {
  perror("stop the buzzer");
  exit(1);
 }
}
int main(int argc, char **argv)
{
 int freq = 1000 ;
 
 open_buzzer();
 printf( "\nBUZZER TEST ( PWM Control )\n" );
 printf( "Press +/- to increase/reduce the frequency of the BUZZER\n" ) ;
 printf( "Press 'ESC' key to Exit this program\n\n" );
 
 
 while( 1 )
 {
  int key;
  set_buzzer_freq(freq);
  printf( "\tFreq = %d\n", freq );
  key = getch();
  switch(key) {
  case '+':
   if( freq < 20000 )
    freq += 10;
   break;
  case '-':
   if( freq > 11 )
    freq -= 10 ;
   break;
  case ESC_KEY:
  case EOF:
   stop_buzzer();
   exit(0);
  default:
   break;
  }
 }
}

编译方法:
(这是原光盘使用的编译方法)
arm-linux-gcc -o pwm_test pwm_test.c
适用于所有版本的编译器,但要注意链接库。

若要静态编译,可以这样:
arm-linux-gcc -static -o pwm_test pwm_test.c


不要为了学习而学习!
级别: 新手上路
UID: 15608
精华: 0
发帖: 17
金钱: 90 两
威望: 18 点
贡献值: 0 点
综合积分: 34 分
注册时间: 2010-03-07
最后登录: 2012-03-04
1楼  发表于: 2010-04-18 14:42
测试……
级别: 新手上路
UID: 73910
精华: 0
发帖: 3
金钱: 15 两
威望: 3 点
贡献值: 0 点
综合积分: 6 分
注册时间: 2012-07-16
最后登录: 2013-04-09
2楼  发表于: 2012-08-24 15:27