准备15张bmp图片,点击左边切换上一张,右边切换下一张,循环显示
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <linux/input.h>
void init_lcd(void); //打开lcd
void uninit_lcd(void);//解除映射,关闭lcd
void show_bmp(int x0,int y0,char *bmp_name);//坐标和图片名
void init_ts(void);//打开触摸屏
void gets_pos(int *x,int *y); //获取触摸屏位置
int lcd_fd=-1;
int ts_fd=-1;
int *p = NULL; //野指针,可能会指向不可访问区域,导致程序崩溃
int main(int argc, char const *argv[])
{
//15张图片的名称,用U盘cp到开发板
char bmp[][16]={"0.bmp","1.bmp","2.bmp","3.bmp","4.bmp","5.bmp",
"6.bmp","7.bmp","8.bmp","9.bmp","10.bmp","11.bmp",
"12.bmp","13.bmp","14.bmp","15.bmp"};
int i=0,x,y;
init_lcd();
init_ts();
show_bmp(0,0,"0.bmp");
while(1) //在死循环中
{
gets_pos(&x,&y);//获取坐标
printf("(%d,%d)\n",x,y);//打印坐标
if(x>0 && x<100 &&y>0 && y <480)//判断是否在左边
{
i--;
if(i <0) i=15;
}
else if(x>700 && x<800 && y>0 && y<480)//判断是否在右边
{
i++;
if(i>15) i=0;
}
show_bmp(0,0,bmp[i]);//显示图片
printf("%s\n",bmp[i]);//打印显示的哪张图片
}
uninit_lcd();
close(ts_fd);
return 0;
}
void init_lcd(void)
{
//打开lcd
lcd_fd = open("/dev/fb0",O_RDWR);
if(lcd_fd < 0) //打开失败
{
perror("open lcd failed");
return;
}
//进行内存映射
p = mmap(NULL,800*480*4,PROT_READ | PROT_WRITE,MAP_SHARED,lcd_fd,0);
if(p == NULL)
{
perror("mmap failed");
return;
}
}
void uninit_lcd(void)
{
//解除映射
munmap(p,800*480*4);
//关闭lcd
close(lcd_fd);
}
void show_bmp(int x0,int y0,char *bmp_name)
{
//打开bmp
int bmp_fd = open(bmp_name,O_RDWR);
if(bmp_fd < 0) //打开失败
{
perror("open bmp failed");
return;
}
//读取前54个字节,获取图片的宽度和高度
char head[54];
read(bmp_fd,head,54);
//宽度:第18~21字节
int width = head[18] | head[19] << 8 | head[20] << 16 | head[21] << 24;
//高度:第22~25字节
int height = head[22] | head[23] << 8 | head[24] << 16 | head[25] << 24;
//printf("w = %d,h = %d\n",width,height);
//判断图片越界
if(width+x0 > 800 || height+y0 > 480)
{
printf("out of range\n");
return;
}
//读取图片数据
char bmp_buf[width*height*3];
read(bmp_fd,bmp_buf,width*height*3);
int x,y,color,i=0;
char r,g,b;
for(y=0;y<height;y++)
{
for(x=0;x<width;x++)
{
b = bmp_buf[i++];
g = bmp_buf[i++];
r = bmp_buf[i++];
color = b | g << 8 | r << 16;
*(p+800*(height-1-y+y0)+x+x0) = color;
}
}
close(bmp_fd);
}
void init_ts(void)
{
//打开ts,路径:/dev/input/event0
ts_fd = open("/dev/input/event0",O_RDWR);
if (ts_fd < 0)
{
perror("open ts_fd failed");//打印错误信息
return;
}
}
void gets_pos(int *x,int *y)
{
//读取触摸屏数据,获取坐标
struct input_event buf;
while(1)
{
read(ts_fd,&buf,sizeof(buf));
if(buf.type == EV_ABS) //触摸屏事件
{
if(buf.code == ABS_X) //x轴
{
*x = buf.value*800/1024;
}
if(buf.code == ABS_Y) //Y轴
{
*y = buf.value*480/600;
}
}
//判断手指松开
if(buf.type == EV_KEY && buf.code == BTN_TOUCH && buf.value == 0) break;
}
}