---
# System prepended metadata

title: 微算機期末專案報告文檔

---

# 微算機期末專案報告文檔
## 架構圖
![](https://hackmd.io/_uploads/SkB9hETvn.png)
## python flask+ngrok
https://colab.research.google.com/drive/1ilHqHKBFiekiIuFoh0_3OYH1chBUfBZB?usp=sharing
## TX2-上面執行的code
```cpp=

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <iostream>
#include <map>
#include <string>
#include <cstring>
#include <stdlib.h>
#include <errno.h>
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#include <bitset>
using namespace std;

int gpio_export(unsigned int gpio){
	int fd,len;
	char buf[64];
	fd = open("/sys/class/gpio/export",O_WRONLY);
	if(fd<0){
		perror("gpio/export");
		return fd;
	}
	len = snprintf(buf,sizeof(buf),"%d",gpio);
	write(fd,buf,len);
	close(fd);
	return 0;
}

int gpio_unexport(unsigned int gpio){
	int fd,len;
	char buf[64];
	fd = open("/sys/class/gpio/unexport",O_WRONLY);
	if(fd<0){
		perror("gpio/export");
		return fd;
	}
	len = snprintf(buf,sizeof(buf),"%d",gpio);
	write(fd,buf,len);
	close(fd);
	return 0;
}

int gpio_set_dir(unsigned int gpio,std::string dirStatus){
	int fd;
	char buf[64];
	snprintf(buf,sizeof(buf),"/sys/class/gpio/gpio%d/direction",gpio);
	fd = open(buf,O_WRONLY);
	if(fd<0){
		perror("gpio/direction");
		return fd;
	}
	if(dirStatus == "out")
		write(fd,"out",4);
	else	
		write(fd,"in",3);
}

int gpio_set_value(unsigned int gpio, int value) {
	int fd;
	char buf[64];
	snprintf(buf, sizeof(buf), "/sys/class/gpio/gpio%d/value", gpio);
	fd = open(buf, O_WRONLY);
	if (fd < 0) {
		perror("gpio/set-value");
		return fd;
	}
	if(value == 0)
		write(fd,"0",2);
	else	
		write(fd,"1",2);
	close(fd);
	return 0;
}


void setGPIO(unsigned int gpio, string status)
{
	std::cout<<status<<endl;
	int io;
 	gpio_export(gpio);
	gpio_set_dir(gpio,"out");
	FILE *fp = fopen("/dev/gpio","w+");
	if (fp ==NULL) {
		perror("gpio error");
		return;
	}
	char buf[1000] = "1234567";
	if (status == "on") {
		sprintf(buf,"%d %s",gpio,"1");
		//strcpy(buf, (to_string(gpio) + "1").c_str());
	}
	else {
		sprintf(buf,"%d %s",gpio,"0");
		//strcpy(buf, (to_string(gpio) + "0").c_str());
	}
	std::cout<<*buf;
	fwrite( buf,sizeof(buf), 1,fp);
	fclose(fp);
	return;
}
int getGPIO(unsigned int gpio)
{
	int io;
 	//gpio_export(gpio);
	//gpio_set_dir(gpio,"out");
	char buf[64];
	char buffer[1024];
	snprintf(buf, sizeof(buf), "/sys/class/gpio/gpio%d/value", gpio);
	int fd = open(buf,O_RDONLY);
	ssize_t bytesRead = read(fd,buffer,sizeof(buffer));
	return buffer[0]-'0';
}
#include <curl/curl.h>
size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* response)
{
    size_t totalSize = size * nmemb;
    response->append(static_cast<char*>(contents), totalSize);
    return totalSize;
}
int GetFormApi(){
	// Initialize CURL
    curl_global_init(CURL_GLOBAL_DEFAULT);

    // Create a CURL handle
    CURL* curl = curl_easy_init();
    if (curl)
    {
        std::string response;

        // Set the URL
        curl_easy_setopt(curl, CURLOPT_URL, "https://7a41-35-196-80-75.ngrok-free.app/GetTx2Task");

        // Set the write callback function
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);

        // Set the response data pointer
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

        // Perform the request
        CURLcode res = curl_easy_perform(curl);
        if (res == CURLE_OK)
        {
            // Print the response
            std::cout << "Response: " << response << std::endl;
	    return stoi(response);
        }
        else
        {
            // Print an error message
            std::cerr << "Request failed: " << curl_easy_strerror(res) << std::endl;
        }

        // Clean up
        curl_easy_cleanup(curl);
    }

    // Clean up global resources
    curl_global_cleanup();
    
    return 0;




}
#include <unistd.h>
int main(int argc, char *argv[]) {
	while(true){	        
	        sleep(1);	
	        int number = GetFormApi();
		if(number == -1)
			continue;
                // 將數字轉換為二進制字串
	        std::string binaryString = std::bitset<32>(number).to_string();   
		// 只保留後八位
      	        std::string eightBits = binaryString.substr(24, 8);   
		// 輸出結果
		std::cout << "Binary representation: " << eightBits << std::endl;
		for(int i=0;i<5;i++){
	        	setGPIO(255, ((eightBits[0]=='1')?"on":"off"));
			setGPIO(397, ((eightBits[1]=='1')?"on":"off"));
			setGPIO(481, ((eightBits[2]=='1')?"on":"off"));
			setGPIO(396, ((eightBits[3]=='1')?"on":"off"));
			setGPIO(466, ((eightBits[4]=='1')?"on":"off"));
			setGPIO(392, ((eightBits[5]=='1')?"on":"off"));
			setGPIO(254, ((eightBits[6]=='1')?"on":"off"));
			setGPIO(430, ((eightBits[7]=='1')?"on":"off"));
			setGPIO(398, ((eightBits[8]=='1')?"on":"off"));
		}
	}
	

		
	
}
```
## Makefile
```cpp=
obj-m := gpio.o

kernel_DIR := /usr/src/linux-headers-4.9.201-tegra-ubuntu18.04_aarch64/kernel-4.9

PWD := $(shell pwd)

all:
	make -C $(kernel_DIR) SUBDIRS=$(PWD)
clean:
	rm *.o *.ko *.mod.c
.PHONY:
	clean
```
## gpio.c
```cpp=
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <asm/uaccess.h>

#define MAJOR_NUM 60
#define MODULE_NAME "gpio"

static int iCount = 0;
static char userChar[100];

static ssize_t drv_read(struct file *filp, char *buf, size_t count, loff_t *ppos)
{
	printk("device read\n");
	return count;
}

static ssize_t drv_write(struct file *flip, const char *buf, size_t count, loff_t *ppos)
{
	printk("device write\n");
	printk("%d\n", iCount);
	printk("W_buf_size: %d\n", (int)count);
	copy_from_user(userChar, buf, count);
	userChar[count-1] = 0;
	int i=0;
	char gpio[10] = {0}; 
	char on_off[10]={0};
	for(i=0;i<sizeof(userChar);i++){
		if(userChar[i]==' ')
			break;
		gpio[i]=userChar[i];
	}
	
		
	int j=i+1;
	for(j=i+1;j<sizeof(userChar);j++){
		if(userChar[j]=='\0')
			break;
		on_off[j-i-1]=userChar[j];
	}
	printk("\nuserChar:%s",gpio);
	printk("\nuserChar:%s",on_off);
	printk("\nuserChar: %s\n", userChar);
	printk("\nuserChar: %d\n", (int)sizeof(userChar));
	struct file *fp;
	loff_t pos = 0;
	mm_segment_t old_fs;
	old_fs=get_fs();
	set_fs(get_ds());
	// export gpio number
	fp = filp_open("/sys/class/gpio/export",O_WRONLY,0);
	vfs_write(fp,gpio,strlen(gpio),&pos);
	filp_close(fp,NULL);
	// write led out/input
	char cmd[1000]={0};
	snprintf(cmd,sizeof(cmd),"/sys/class/gpio/gpio%s/direction",gpio);
	fp = filp_open(cmd,O_WRONLY,0);
	vfs_write(fp,"out",4,&pos);
	filp_close(fp,NULL);
	// write led status
	snprintf(cmd,sizeof(cmd),"/sys/class/gpio/gpio%s/value",gpio);
	fp = filp_open(cmd,O_WRONLY,0);
	if(on_off[0]=='1')
		vfs_write(fp,"1",2,&pos);
	else
		vfs_write(fp,"0",2,&pos);
	filp_close(fp,NULL);
	//restore envirnment
	set_fs(old_fs);
	iCount++;
	return count;
}

long drv_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
	printk("device ioctl\n");
	return 0;
}

static int drv_open(struct inode *inode, struct file *filp)
{
	printk("device open\n");
	return 0;
}

static int drv_release(struct inode *inode, struct file *filp)
{
	printk("device close\n");
	return 0;
}

struct file_operations drv_fops =
{
	read: drv_read,
	write: drv_write,
	unlocked_ioctl: drv_ioctl,
	open: drv_open,
	release: drv_release,
};

static int demo_init(void)
{
	if (register_chrdev(MAJOR_NUM, MODULE_NAME, &drv_fops) < 0)
	{
		printk("<1>%s: can't get major %d\n", MODULE_NAME, MAJOR_NUM);
		return (-EBUSY);
	}
	printk("<1>%s: started\n", MODULE_NAME);
	return 0;
}

static void demo_exit(void)
{
	unregister_chrdev(MAJOR_NUM, "gpio");
	printk("<1>%s: removed\n", MODULE_NAME);
}

module_init(demo_init);
module_exit(demo_exit);
MODULE_LICENSE("GPL");


```
## MIT2 
![](https://hackmd.io/_uploads/BkspnNTw2.png)
![](https://hackmd.io/_uploads/BkzkpNaDh.png)
