Manufaturação industrial
Internet das coisas industrial | Materiais industriais | Manutenção e reparo de equipamentos | Programação industrial |
home  MfgRobots >> Manufaturação industrial >  >> Manufacturing Technology >> Processo de manufatura

Arduino - Tirar uma foto - Carregar para o Google Drive

Componentes e suprimentos

Arduino Mega 2560
× 1
PHPoC WiFi Shield 2 para Arduino
× 1
Seeed Grove - Kit de câmera serial
× 1
Escudo de base Seeed Grove
× 1
Botão
× 1

Sobre este projeto


Se você é um iniciante, pode aprender sobre o Arduino aqui.





Demonstração





Como funciona


1 Faça login na conta do Google via OAuth 2.0 para dispositivos IoT para obter access_token.

O processo de login é descrito neste projeto no Hackster.

2. Quando o botão é pressionado, o Arduino obtém a imagem da câmera e carrega no Google Drive usando access_token por meio da API do Google Drive.

A API do Google Drive para upload de arquivos é descrita no documento do Google.





Como fazer

  • Crie um projeto do Google no Portal do desenvolvedor do Google e obtenha GOOGLE_CLIENT_ID e GOOGLE_CLIENT_SECRET
  • Substitua GOOGLE_CLIENT_ID e GOOGLE_CLIENT_SECRET no código Arduino
  • Carregue o arquivo login.php para PHPoC Shield. Veja as instruções
  • Compilar e fazer upload do código do Arduino via Arduino IDE
  • Ver ip_address do escudo PHPoC no Serial Monitor
  • Acesse a página de login no PHPoC Shield:http://ip_address/login.php e faça login em sua conta do Google
  • Pressione o botão para tirar a foto
  • Verifique seu Google Drive após dois segundos, você verá a foto tirada em seu Google Drive.





Outra plataforma de hardware


Fiz o mesmo projeto para outra plataforma de hardware aqui.





O melhor Arduino Starter Kit para iniciantes


Se você estiver procurando por um kit Arduino, consulte O melhor kit Arduino para iniciantes







Referências de função

  • Serial.begin ()
  • Serial.println ()
  • atraso ()
  • milis ()
  • para loop
  • while loop
  • se mais
  • loop ()
  • configuração ()
  • String.toInt ()
  • String.substring ()
  • String.indexOf ()
  • String.remove ()
  • String.equals ()

Código

  • ArduinoGoogleDrive
  • login.php
  • grove_camera.h
ArduinoGoogleDrive Arduino
Este é o código principal do Arduino.
 #include  #include  #include "grove_camera.h" // Substitua seu GOOGLE_CLIENT_ID e GOOGLE_CLIENT_SECRET aquiString GOOGLE_CLIENT_IDxxxxxx.googlexx String GOOGLE_CLIENT_SECRET ="xxxxxxxxxxxxxxxxxxxxxxxx"; PhpocServer websocket_server (80); String http_resp_hearder (PhpocClient &client) {String hearder =""; while (1) {if (client.available ()) {String line =client.readLine (); if (linha =="\ r \ n") quebra; outro ouvinte + =linha; } if (! client.connected ()) {client.stop (); pausa; }} return hearder;} String http_resp_body (PhpocClient &client) {String body =""; while (1) {if (client.available ()) {char c =client.read (); corpo + =c; } if (! client.connected ()) {client.stop (); pausa; }} return body;} String access_token =""; String refresh_token =""; long access_token_expire_at =0; void websocket_send (String msg) {char wbuf [256]; msg.toCharArray (wbuf, msg.length () + 1); websocket_server.write (wbuf, msg.length ());} void googleDeviceOAuthLogin () {cliente PhpocClient; // Etapa 1:Solicitar códigos de dispositivo e usuário if (client.connectSSL ("accounts.google.com", 443)) {Serial.println (F ("Conectado ao servidor")); Corpo da string =F ("client_id ="); corpo + =GOOGLE_CLIENT_ID; body + =F ("&scope =https://www.googleapis.com/auth/drive.file"); client.println (F ("POST / o / oauth2 / dispositivo / código HTTP / 1.1")); client.println (F ("Host:accounts.google.com")); client.println (F ("Conexão:fechar")); client.println (F ("Aceitar:* / *")); client.println (F ("Content-Type:application / x-www-form-urlencoded")); client.print (F ("Content-Length:")); client.println (body.length ()); client.println (); client.print (body); String response_hearder =http_resp_hearder (cliente); String response_body =http_resp_body (cliente); //Serial.println(response_hearder); //Serial.println(response_body); JSONVar body_json =JSON.parse (response_body); if (JSON.typeof (body_json) =="undefined") {Serial.println ("Análise de entrada falhou!"); Retorna; } // Etapa 2:lidar com a resposta do servidor de autorização String device_code =""; String user_code =""; long expires_in =0; intervalo interno =0; String verification_url =""; bool is_valid =true; if (body_json.hasOwnProperty ("device_code")) device_code =body_json ["device_code"]; else is_valid =false; if (body_json.hasOwnProperty ("user_code")) user_code =body_json ["user_code"]; else is_valid =false; if (body_json.hasOwnProperty ("expires_in")) expires_in =(longo) body_json ["expires_in"]; else is_valid =false; if (body_json.hasOwnProperty ("intervalo")) intervalo =(int) body_json ["intervalo"]; else is_valid =false; if (body_json.hasOwnProperty ("verification_url")) verification_url =body_json ["verification_url"]; else is_valid =false; if (is_valid) {// Etapa 3:Exibir o código do usuário Serial.print (F ("Próxima, visite")); Serial.print (verificação_url); Serial.print (F ("em seu desktop ou smartphone e digite este código:")); Serial.println (user_code); String msg; msg ="{\" provedor \ ":\" google \ ","; msg + ="\" ação \ ":\" LOGIN \ ","; msg + ="\" verification_url \ ":\" "+ verification_url +" \ ","; msg + ="\" user_code \ ":\" "+ user_code +" \ "}"; websocket_send (msg); // Etapa 5:Enquete do servidor de autorização int poll_max =expires_in / interval; corpo =F ("client_id ="); corpo + =GOOGLE_CLIENT_ID; corpo + =F ("&client_secret ="); corpo + =GOOGLE_CLIENT_SECRET; corpo + =F ("&código ="); corpo + =código_dispositivo; body + =F ("&grant_type =http://oauth.net/grant_type/device/1.0"); for (int poll_count =0; poll_count  debounceDelay) {if (reading! =buttonState) {buttonState =reading; if (buttonState ==HIGH) {return true; }}} lastButtonState =leitura; retornar falso;} void setup () {Serial.begin (115200); while (! Serial); Phpoc.begin (PF_LOG_SPI | PF_LOG_NET); websocket_server.beginWebSocket ("login"); Serial.print ("endereço do servidor WebSocket:"); Serial.println (Phpoc.localIP ()); pinMode (2, INPUT); cameraInit (CT_JPEG, PR_160x120, JR_640x480);} void loop () {cliente PhpocClient =websocket_server.available (); if (cliente) {String ws_str =client.readLine (); if (ws_str =="google \ r \ n") {googleDeviceOAuthLogin (); }} if (isButtonPressed (2)) {if (access_token! ="" &&access_token_expire_at> millis ()) cameraToGoogleDrive (); else Serial.println ("access_token é inválido, faça o login novamente"); }} 
login.php PHP
Este código de arquivo é carregado para PHPoC Shield. Ele fornece uma interface do usuário da web para o processo de login do Google
    PHPoC / <? Echo system ("uname -i")?>        
G o o g l e
Login para Arduino




grove_camera.h C / C ++
Biblioteca para a câmera Grove
 #define PIC_PKT_LEN 512 // comprimento de dados de cada leitura, não defina muito grande porque a ram é limitada # define CAM_ADDR 0 // Tipo de cor # define CT_GRAYSCALE_2 0x01 # define CT_GRAYSCALE_4 0x02 # define CT_GRAYSCALE_8 0x03 # define CT_COLOR_12 0x05 # define CT_COLOR_16 0x06 # define CT_JPEG 0x07 // Resolução de pré-visualização # define PR_80x60 0x01 # define PR_160x120 0x03 // Resolução de JPEG # define JR_80x64 0x01 # define JR_160x128 0x03 # define JR_320x240 0x0580 0x05x4te camera ); // addressunsigned int camera_packet_num; unsigned int camera_last_packet_len; void cameraClearRxBuf () {while (Serial.available ()) {Serial.read (); }} void cameraSendCmd (char cmd [], int cmd_len) {for (char i =0; i > 8) &0xff, 0}; enquanto (1) {cameraClearRxBuf (); cameraSendCmd (cmd3, 6); if (Serial.readBytes ((char *) resp, 6)! =6) continuar; if (resp [0] ==0xaa &&resp [1] ==(0x0e | camera_address) &&resp [2] ==0x06 &&resp [4] ==0 &&resp [5] ==0) break; }} long cameraGetPicture () {char cmd [] ={0xaa, 0x04 | camera_address, 0x01, 0x00, 0x00, 0x00}; unsigned char resp [6]; picTotalLen longo sem sinal =0; // comprimento da imagem while (1) {cameraClearRxBuf (); cameraSendCmd (cmd, 6); if (Serial.readBytes ((char *) resp, 6)! =6) continuar; if (resp [0] ==0xaa &&resp [1] ==(0x0e | camera_address) &&resp [2] ==0x04 &&resp [4] ==0 &&resp [5] ==0) {Serial.setTimeout (1000); if (Serial.readBytes ((char *) resp, 6)! =6) continuar; if (resp [0] ==0xaa &&resp [1] ==(0x0a | camera_address) &&resp [2] ==0x01) {picTotalLen =(resp [3]) | (resp [4] <<8) | (resp [5] <<16); pausa; }}} camera_packet_num =(picTotalLen) / (PIC_PKT_LEN - 6); camera_last_packet_len =PIC_PKT_LEN; if ((picTotalLen% (PIC_PKT_LEN-6))! =0) {camera_packet_num + =1; camera_last_packet_len =picTotalLen% (PIC_PKT_LEN - 6) + 6; } return picTotalLen;} long cameraGetPacket (unsigned int i, char * buf) {char cmd [] ={0xaa, 0x0e | camera_address, 0x00, 0x00, 0x00, 0x00}; Serial.setTimeout (100); if (i > 8) &0xff; cameraClearRxBuf (); cameraSendCmd (cmd, 6); int pkt_len; if (i <(camera_packet_num - 1)) pkt_len =PIC_PKT_LEN; else pkt_len =camera_last_packet_len; uint16_t cnt =Serial.readBytes ((char *) buf, pkt_len); return cnt; } else {cmd [4] =0xf0; cmd [5] =0xf0; cameraSendCmd (cmd, 6); } return "";} 

Esquemas


Processo de manufatura

  1. Arduino Spybot
  2. FlickMote
  3. TV B-Gone caseiro
  4. Relógio mestre
  5. Encontre-me
  6. Arduino Power
  7. Tech-TicTacToe
  8. Arduino Quadruped
  9. Dispositivos Bluetooth controlados por voz com OK Google
  10. Investimento do Google para impulsionar a adoção de dispositivos de segurança IoT