---
# System prepended metadata

title: 7688 Duo 啦機破板每週任務

---

# 7688 Duo 啦機破板每週任務

> 如果看了這個還可以被當就可以吃屎了




# 12月07日 Score:100

## MCS_test.py
:::    spoiler
``` python
import requests

device_id = "ID"
device_key = "KEY"
data_channel = "gamepad"

url = "http://api.mediatek.com/mcs/v2/devices/" + device_id
url += "/datachannels/" + data_channel + "/datapoints.csv"

def game_pad():
    r = requests.get(url, headers = {"deviceKey" : device_key})
    data = r.content.split(',')[2:]
    print data
    high_low = data[0].split("|")[1]
    command = data[0].split("|")[0]
    return high_low,command

while True:
    high_low,command = game_pad()
    print(high_low)
    print command
    if high_low == "1":
        if command == "left":
            print "press left"
        elif command == "right":
            print "press right"
        elif command == "up":
            print "press up"
        elif command == "down":
            print "press down"
        elif command == "A":
            print "press A"
        elif command == "B":
            print "press B"
```
:::

## mearm.ino
:::    spoiler
``` cpp
#include <Servo.h>

Servo servo_gripper;
Servo servo_base;
Servo servo_updown;
Servo servo_frontback;

int degree_base      = 90;           //設定初始角度，請依照您的機械手臂做微調
int degree_updown    = 90;
int degree_frontback = 90;

void setup()
{
    Serial.begin(115200);
    Serial1.begin(57600);             //建立Arduino ATMega32U4與MT7688AN之間的連結
    servo_gripper.attach(12);          //將夾爪的伺服馬達的腳位指定給12號腳位
    servo_updown.attach(10);           //將升降的伺服馬達的腳位指定給10號腳位
    servo_frontback.attach(11);        //將前後的伺服馬達的腳位指定給11號腳位
    servo_base.attach(9);             //將平台的伺服馬達的腳位指定給9號腳位
}

void loop()
{
    if(Serial1.available())
    {
        int command = Serial1.read(); //讀取MT7688AN送來的指令
        if(command == 'o')            //如果是o的話，就打開夾爪
        {
            Serial.println("gripper open");
            servo_gripper.write(160);
        }
        else if(command == 'f')       //如果是f的話，就合起夾爪
        {
            Serial.println("gripper closed");
            servo_gripper.write(30);
        }
        else if(command == 'u')       //如果是u的話，就上升手臂
        {
            degree_updown = (++degree_updown > 180) ? 180 : degree_updown;
            Serial.print("degree_updown");
            Serial.println(degree_updown);
            servo_updown.write(degree_updown);
        }
        else if(command == 'd')       //如果是d的話，就下降手臂
        {
            degree_updown = (--degree_updown < 0) ? 0 : degree_updown;
            Serial.print("degree_updown");
            Serial.println(degree_updown);
            servo_updown.write(degree_updown);
        }
        else if(command == 'a')       //如果是a的話，就前伸手臂
        {
            degree_frontback = (++degree_frontback > 180) ? 180 : degree_frontback;
            Serial.print("degree_frontback: ");
            Serial.println(degree_frontback);
            servo_frontback.write(degree_frontback);
        }
        else if(command == 'b')       //如果是b的話，就後縮手臂
        {
            degree_frontback = (--degree_frontback < 0) ? 0 : degree_frontback;
            Serial.print("degree_frontback: ");
            Serial.println(degree_frontback);
            servo_frontback.write(degree_frontback);
        }
        else if(command == 'l')       //如果是l的話，就左轉平台
        {
            degree_base = (++degree_base > 180) ? 180 : degree_base;
            Serial.print("degree_base: ");
            Serial.println(degree_base);
            servo_base.write(degree_base);
        }
        else if(command == 'r')       //如果是r的話，就右轉平台
        {
            degree_base = (--degree_base < 0) ? 0 : degree_base;
            Serial.print("degree_base: ");
            Serial.println(degree_base);
            servo_base.write(degree_base);
        }
    }
}
```
:::

## mearm.py
:::    spoiler
``` python
# -*- coding: utf-8 -*-

import requests
import serial

s = serial.Serial("/dev/ttyS0", 57600)

device_id = "您的device id"          # 改成您的device id
device_key = "您的device key" # 改成您的device key
data_channel = "gamepad"        # 改成您遊戲手把的data channel id
data_channel2 = "gripper"       # 改成您開關控制的data channel id

num = 0

last_command2 = ""
url = "http://api.mediatek.com/mcs/v2/devices/" + device_id
url += "/datachannels/" + data_channel + "/datapoints.csv"

url2 = "http://api.mediatek.com/mcs/v2/devices/" + device_id
url2 += "/datachannels/" + data_channel2 + "/datapoints.csv"

def game_pad():  # 接受MCS gamepad資料通道的訊號 
    r = requests.get(url, headers = {"deviceKey" : device_key})
    data = r.content.split(',')[2:]
    return (data[0][0], data[0][-1])

def gripper():   # 接收MCS gripper資料通道的訊號
    r = requests.get(url2, headers = {"deviceKey" : device_key})
    return r.content[-1]

while True:      # 判斷接收到的訊號，並發送相對應的指令給Arduino端
    command = game_pad()
    command2 = gripper()
    if last_command2 == "":
        last_command2 = command2
    else:
        if last_command2 != command2:
            if command2 == "1":
                print "closed"
                s.write("f")
            elif command2 == "0":
                print "open"
                s.write("o")
            last_command2 = command2
        else:
            pass
            
    if command[1] == "1":
        if command[0] == "l":
            print "{} . press left".format(num)
            s.write("l")
            num = num + 1
        elif command[0] == "r":
            print "{} . press right".format(num)
            s.write("r")
            num = num + 1
        elif command[0] == "u":
            print "{} . press up".format(num)
            s.write("u")
            num = num + 1
        elif command[0] == "d":
            print "{} . press down".format(num)
            s.write("d")
            num = num + 1
        elif command[0] == "A":
            print "{} . press A".format(num)
            s.write("a")
            num = num + 1
        elif command[0] == "B":
            print "{} . press B".format(num)
            s.write("b")
            num = num + 1

```
:::

# 12月14日 Score:90 理論100 

林北輪胎線斷掉

500元破板要重燒


啦機破板聯發科品質不意外



## Mearm_1214.ino 

:::spoiler

```cpp
#include <Servo.h>

Servo servo_gripper;
Servo servo_base;
Servo servo_updown;
Servo servo_frontback;
Servo servo_car;

const int ena = 3;
const int In1 = 4;
const int In2 = 5;
const int enb = 8;
const int In3 = 6;      
const int In4 = 7;
int degree_base      = 90;           //設定初始角度，請依照您的機械手臂做微調
int degree_updown    = 90;
int degree_frontback = 90;

String Data = "";

void setup()
{
    Serial.begin(115200);
    Serial1.begin(57600);             //建立Arduino ATMega32U4與MT7688AN之間的連結
    servo_gripper.attach(12);          //將夾爪的伺服馬達的腳位指定給3號腳位
    servo_updown.attach(10);           //將升降的伺服馬達的腳位指定給5號腳位
    servo_frontback.attach(11);        //將前後的伺服馬達的腳位指定給6號腳位
    servo_base.attach(9); //將平台的伺服馬達的腳位指定給9號腳位
    pinMode(In1, OUTPUT);
    pinMode(In2, OUTPUT);
    pinMode(In3, OUTPUT);
    pinMode(In4, OUTPUT);
    pinMode(ena, OUTPUT);
    pinMode(enb, OUTPUT);
    digitalWrite(ena, HIGH);
    digitalWrite(enb, HIGH);  
}

void loop()
{
    if(Serial1.available())
    {
      while(Serial1.available()>0){
          Data += (char)(Serial1.read()); //讀取MT7688AN送來的指令
          delay(5); // 沒有delay會有異常
        }
        Serial.println(Data);
      if(Data.startsWith("gripper") == true)            
        {
            Data.replace("gripper ",""); //字串處理，看不懂就算了
            int angle = Data.toInt();
            Serial.print("gripper:");
            Serial.println(angle);
            servo_gripper.write(angle);
            Data = "";
            
        }
        else if(Data.startsWith("updown") == true)            
        {
            Data.replace("updown ","");
            int angle = Data.toInt();
            Serial.print("updown:");
            Serial.println(angle);
            servo_updown.write(angle);
            Data = "";
            
        }
        else if(Data.startsWith("frontback") == true)          
        {
            Data.replace("frontback ","");
            int angle = Data.toInt();
            Serial.print("frontback:");
            Serial.println(angle);
            servo_frontback.write(angle);
            Data = "";
            
        }
        else if(Data.startsWith("base") == true)            
        {
            Data.replace("base ","");
            int angle = Data.toInt();
            Serial.print("base:");
            Serial.println(angle);
            servo_base.write(angle);
            Data = "";
            
        }
        //車車
    if(Data=="l"){
      Serial.println("Car Left");
      mleft(1500);  
      mstop(500);
      Data = "";
      }
    if(Data=="r"){
      Serial.println("Car Right");
      mrigt(1500);  
      mstop(500);  
      Data = "";
      }
    if(Data=="d"){
      Serial.println("Car back");
      mback(2500);  
      mstop(500);
      Data = "";
      }
    if(Data=="u"){
      Serial.println("Car up");
      mfrnt(2500);  
      mstop(500); 
      Data = "";
      }
    Data = "";

        
    }
}


void mstop(int j){
  digitalWrite(In1, LOW);
  digitalWrite(In2, LOW);
  digitalWrite(In3, LOW);
  digitalWrite(In4, LOW);
  delay(j);
}
void mleft(int j){
  digitalWrite(In1, HIGH);
  digitalWrite(In2, LOW);
  digitalWrite(In3, LOW);
  digitalWrite(In4, HIGH);
  delay(j);
}
void mrigt(int j){
  digitalWrite(In1, LOW);
  digitalWrite(In2, HIGH);
  digitalWrite(In3, HIGH);
  digitalWrite(In4, LOW);
  delay(j);
}
void mback(int j){
  digitalWrite(In1, HIGH);
  digitalWrite(In2, LOW);
  digitalWrite(In3, HIGH);
  digitalWrite(In4, LOW);
  delay(j);
}
void mfrnt(int j){
  digitalWrite(In1, LOW);
  digitalWrite(In2, HIGH);
  digitalWrite(In3, LOW);
  digitalWrite(In4, HIGH);
  delay(j);
}

```
:::



## Mearm_1214.py


:::spoiler
``` python
# -*- coding: utf-8 -*-

import requests
import serial

s = serial.Serial("/dev/ttyS0", 57600)

device_id = "DAcpNv9l"          # 改成您的device id
device_key = "ac00YU0lBAj7EHsC" # 改成您的device key
data_channel = "gamepad"        # 改成您遊戲手把的data channel id
data_channel2 = "gripper"       # 改成您開關控制的data channel id
data_channel3 = "base"
data_channel4 = "updown"
data_channel5 = "frontback"

num = 0

last_command2 = ""
url = "http://api.mediatek.com/mcs/v2/devices/" + device_id
url += "/datachannels/" + data_channel + "/datapoints.csv"

url2 = "http://api.mediatek.com/mcs/v2/devices/" + device_id
url2 += "/datachannels/" + data_channel2 + "/datapoints.csv"

url3 = "http://api.mediatek.com/mcs/v2/devices/" + device_id
url3 += "/datachannels/" + data_channel3 + "/datapoints.csv"

url4 = "http://api.mediatek.com/mcs/v2/devices/" + device_id
url4 += "/datachannels/" + data_channel4 + "/datapoints.csv"

url5 = "http://api.mediatek.com/mcs/v2/devices/" + device_id
url5 += "/datachannels/" + data_channel5 + "/datapoints.csv"

last_gripper = ""
last_base = ""
last_updown = ""
last_frontback = ""

def game_pad():  # 接受MCS game_pad資料通道的訊號 
    r = requests.get(url, headers = {"deviceKey" : device_key})
    data = r.content.split(',')[2:]
    return (data[0][0], data[0][-1])

def gripper():   # 接收MCS gripper資料通道的訊號
    r = requests.get(url2, headers = {"deviceKey" : device_key})
    data = r.content.split(',')[2:]
    data_0 = data[0]
    grip = "gripper %s"%(data_0) #字串處理
    return grip

def base():   # 接收MCS base資料通道的訊號
    r = requests.get(url3, headers = {"deviceKey" : device_key})
    data = r.content.split(',')[2:]
    data_0 = data[0]
    grip = "base %s"%(data_0) #字串處理
    return grip

def updown():   # 接收MCS updown資料通道的訊號
    r = requests.get(url4, headers = {"deviceKey" : device_key})
    data = r.content.split(',')[2:]
    data_0 = data[0]
    grip = "updown %s"%(data_0) #字串處理
    return grip

def frontback():   # 接收MCS frontback資料通道的訊號
    r = requests.get(url5, headers = {"deviceKey" : device_key})
    data = r.content.split(',')[2:]
    data_0 = data[0]
    grip = "frontback %s"%(data_0) #字串處理
    return grip

while True:      # 判斷接收到的訊號，並發送相對應的指令給Arduino端
    command = game_pad()
    grip = gripper()
    base1 = base()
    updown1 = updown()
    frontback1 = frontback()
    
    #基本上下面就是判斷值有沒有變，變了再傳資料
    if last_gripper == "":
        last_gripper = grip
        print(grip)
        s.write(grip)
    else:
        if last_gripper != grip:
            print(grip)
            s.write(grip)
            last_gripper = grip
            
    if last_base == "":
        last_base = base1
        print(base1)
        s.write(base1)
    else:
        if last_base != base1:
            print(base1)
            s.write(base1)
            last_base = base1
            
    if last_updown == "":
        last_updown = updown1
        print(updown1)
        s.write(updown1)
    else:
        if last_updown != updown1:
            print(updown1)
            s.write(updown1)
            last_updown = updown1
            
    if last_frontback == "":
        last_frontback = frontback1
        print(frontback1)
        s.write(frontback1)
    else:
        if last_frontback != frontback1:
            print(frontback1)
            s.write(frontback1)
            last_frontback = frontback1

    #控制自走車
    if command[1] == "1":
        if command[0] == "l":
            print "{} . press left".format(num)
            s.write("l")
            num = num + 1
        elif command[0] == "r":
            print "{} . press right".format(num)
            s.write("r")
            num = num + 1
        elif command[0] == "u":
            print "{} . press up".format(num)
            s.write("u")
            num = num + 1
        elif command[0] == "d":
            print "{} . press down".format(num)
            s.write("d")
            num = num + 1
        elif command[0] == "A":
            print "{} . press A".format(num)
            s.write("a")
            num = num + 1
        elif command[0] == "B":
            print "{} . press B".format(num)
            s.write("b")
            num = num + 1
```
:::

# 1221.py
:::    success
``` python=
import requests
import socket
import threading
import logging
import mraa
import serial

# change this to the values from MCS web console
DEVICE_INFO = {
    'device_id' : 'DAcpNv9l',
    'device_key' : 'ac00YU0lBAj7EHsC'
}

# change 'INFO' to 'WARNING' to filter info messages
logging.basicConfig(level='INFO')
s = serial.Serial("/dev/ttyS0", 57600)
heartBeatTask = None

def establishCommandChannel():
    # Query command server's IP & port
    connectionAPI = 'https://api.mediatek.com/mcs/v2/devices/%(device_id)s/connections.csv'
    r = requests.get(connectionAPI % DEVICE_INFO,
                 headers = {'deviceKey' : DEVICE_INFO['device_key'],
                            'Content-Type' : 'text/csv'})
    logging.info("Command Channel IP,port=" + r.text)
    (ip, port) = r.text.split(',')

    # Connect to command server
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((ip, int(port)))
    s.settimeout(None)

    # Heartbeat for command server to keep the channel alive
    def sendHeartBeat(commandChannel):
        keepAliveMessage = '%(device_id)s,%(device_key)s,0' % DEVICE_INFO
        commandChannel.sendall(keepAliveMessage)
        logging.info("beat:%s" % keepAliveMessage)

    def heartBeat(commandChannel):
        sendHeartBeat(commandChannel)
        # Re-start the timer periodically
        global heartBeatTask
        heartBeatTask = threading.Timer(40, heartBeat, [commandChannel]).start()

    heartBeat(s)
    return s

def waitAndExecuteCommand(commandChannel):
    while True:
        command = commandChannel.recv(1024)
        logging.info("recv:" + command)
        # command can be a response of heart beat or an update of the LED_Control,
        # so we split by ',' and drop device id and device key and check length
        fields = command.split(',')[2:]

        if len(fields) > 1:
            timeStamp, dataChannelId, commandString = fields
            if dataChannelId == 'gamepad':
                # check the value - it's either 0 or 1
                cmd = commandString.split('|')
                print(cmd)
                s.write(cmd[0])
            if dataChannelId == 'base':
                # check the value - it's either 0 or 1
                print('base '+commandString)
                s.write('base '+commandString)
            if dataChannelId == 'updown':
                # check the value - it's either 0 or 1
                print('updown '+commandString)
                s.write('updown '+commandString)
            if dataChannelId == 'frontback':
                # check the value - it's either 0 or 1
                print('frontback '+commandString)
                s.write('frontback '+commandString)
            if dataChannelId == 'gripper':
                # check the value - it's either 0 or 1
                print('gripper '+commandString)
                s.write('gripper '+commandString)

pin = None


if __name__ == '__main__':
    channel = establishCommandChannel()
    waitAndExecuteCommand(channel)
```
:::
