2025年3月9日日曜日

Johnny5/uno(pir,piezo,lm35,hcsr04,servo,motor,aqm0802,bme280)

復旧方法!

node_moduleが怪しげになってうごかんくなった 以下の手順で成功

node20にして失敗しだしたのでnode18にもどして (どうやったかというと

https://nyan-kyun.verse.jp/wordpress/2024/09/25/git-sourcetree03/#google_vignetteを

参考に nvm でヴァージョン指定!)

https://qiita.com/kamiro/items/b509e30fa62279a82bbcの5の方法で復旧できた

https://qiita.com/pyon_kiti_jp/items/6a751779f4baf165896bでnvm固定!

-------------------hcsr04 他-pir ,piezo,lm35---------------

pirはあっさりうごいた...ふかぼりいずれ必要 lm35は表示がはやすぎ。。。深堀必要

piezoもあっさり動いた ただ以下のコードで最初のpiezo.playのみ実行される

あとのはreplにコピペで動いた  なおプラマイがあるのがアクティブ、ないのがパッシブ

var five = require("johnny-five"), board = new five.Board(); board.on("ready", function() { // Creates a piezo object and defines the pin to be used for the signal var piezo = new five.Piezo(3); // Injects the piezo into the repl board.repl.inject({ piezo: piezo }); // Plays a song piezo.play({ // song is composed by an array of pairs of notes and beats // The first argument is the note (null means "no note") // The second argument is the length of time (beat) of the note (or non-note) song: [ ["C4", 1 / 4], ["D4", 1 / 4], ["F4", 1 / 4], ["D4", 1 / 4], ["A4", 1 / 4], [null, 1 / 4], ["A4", 1], ["G4", 1], [null, 1 / 2], ["C4", 1 / 4], ["D4", 1 / 4], ["F4", 1 / 4], ["D4", 1 / 4], ["G4", 1 / 4], [null, 1 / 4], ["G4", 1], ["F4", 1], [null, 1 / 2] ], tempo: 100 }); // Plays the same song with a string representation piezo.play({ // song is composed by a string of notes // a default beat is set, and the default octave is used // any invalid note is read as "no note" song: "C D F D A - A A A A G G G G - - C D F D G - G G G G F F F F - -", beats: 1 / 4, tempo: 100 }); });

超音波::

https://denshibu.blog.fc2.com/blog-entry-114.html?sp を参考にPingFirmata.inoをunoへ

インストするのがキモ!

var five = require("johnny-five");

var board = new five.Board();

board.on("ready", function() {

  // Proximityオブジェクトを作成

  var proximity = new five.Proximity({

                      controller: "HCSR04",

                      pin: 7,

       freq:  10000

                    });

  // データを取得して距離を表示

  proximity.on("data", function() {


    console.log("Proximity: ");


    console.log("  cm  : ", this.cm);


    console.log("  in  : ", this.in);


    console.log("-----------------");


  });


  // 「change」イベント:障害物が変更されたときに発生する


  proximity.on("change", function() {


    console.log("The obstruction has moved.");


  });


});

-----------------------------led blink------------------------------------------

https://johnny-five.io/examples/ :: miscelaneous examples

https://qiita.com/masato/items/9dad71eca295088e14e5 :: 補遺

{ "name": "johnny-five-start", "version": "0.0.1", "private": true, "dependencies": { "johnny-five": "0.8.48" }, "scripts": {"start": "node app.js"} }

上記のpackage.jsonでnpm startできた、ちなみにctl-c x 2でexitできた!

ただしapp.jsはled1.jsを参考に以下とした

const{Board,Led} = require("johnny-five");

 const board = new Board();

board.on("ready", function() {

  const led = new Led(12);

  led.blink(1000);

});

---------led1.js-----------------------------------------

const { Board, Led } = require("johnny-five");

const board = new Board();

board.on("ready", () => {

  const led = new Led(12);

  led.on();

  board.on("exit", () => {

    led.off();

  });

});

node led1.jsでLedOn、ctl-c x 2でLedOff!

--------------servo1.js--------------------

 servo :: https://dev.classmethod.jp/articles/genuino-101johnny-five-servo/ 

var five = require('johnny-five');

// Genuino が接続されているポート番号 ( `/dev/tty*` (Mac/Linux) or `COM*` (Windows) )

var board = new five.Board();

board.on('ready', function() {

  var servo = new five.Servo({

    'pin' : 10

  });

  this.repl.inject({

    'servo' : servo

  });

 servo.sweep({

  'range'    : [45, 135],

  'interval' : 10000

});

});

----------------dcmotor using drv8833---------------
https://qiita.com/yoshi_iwa/items/95a0cd833508652c1dfb にあるコードで成功
{port:...}をとりpwm 3,dir 4 (arduino unoのピン仕様にて)に変更して成功
ただl298n moduleのほうが説明詳しそう
--------------------lcd using aqm0802---------------------------------------
https://l-w-i.net/t/arduino/lcd_001.txt :: aqm0802成功 3.3v!
// AQM0802A-RN-GBW - I2C接続小型液晶 8文字x2行
//   1. VDD(3.3Vに接続)
//   2. RESET  (*)未使用
//   3. SCL(クロック)
//   4. SDA(データ)
//   5. GND

var five = require("johnny-five");
var board = new five.Board();

var LCD_ADR = 0x3E;  // コントローラIC ST7032iのI2Cアドレス(固定)
var clm_list = [     // 送信コマンドを変えることで表示行を変える
  0x80,  // 0行目表示
  0xc0   // 1行目表示
];

//
// 関数定義
//

// LCD制御
var lcd_cmd = function(cmd) {
  board.io.i2cWrite(LCD_ADR, 0x00, cmd);
}

// データ送信
var lcd_data = function(lcd_data) {
  board.io.i2cWrite(LCD_ADR, 0x40, lcd_data);
}

// 出力位置指定(行, 列)
var lcd_setCursor = function(row, clm){
  lcd_cmd(clm_list[row] + clm);
}

// LCDクリア
var lcd_clear = function() {
  lcd_cmd(0x01);
}

// LCD初期化
// (*)コントラストは好みに応じて微調整するとよい
var lcd_init = function() {
  board.io.i2cConfig();

  lcd_cmd(0x38);  // 画面サイズ指定(8文字 x 2行)
  lcd_cmd(0x39);  // 拡張コマンド設定
  lcd_cmd(0x14);  // 内部OSC周波数
  lcd_cmd(0x7A);  // コントラスト
  lcd_cmd(0x56);  // 電源(3V)/アイコンOFF/コントラスト
  lcd_cmd(0x6A);  // フォロワー操作
  lcd_cmd(0x38);  // 拡張コマンド設定終了
  lcd_cmd(0x0C);  // 表示ON
  lcd_clear();    // LCDクリア
}

//
// メイン
//
board.on("ready", function() {
  // LCD出力
  var lcd_print = function(msg) {
    for(var i = 0; i < msg.length; i++) {
      lcd_data(msg.charCodeAt(i));  // 1文字出力
    }
  }

  lcd_init();           // LCD初期化
  lcd_clear();          // LCDクリア
  lcd_setCursor(0, 0);  // カーソル位置(行, 列)
  lcd_print("I Love");  // 表示文字列
  lcd_setCursor(1, 0);
  lcd_print("Arduino!");
});
-------------------button---piezo---------普通にできた----------------
https://johnny-five.io/examples/button/
https://johnny-five.io/examples/piezo/
------------------------bme280----------------------
arduinoUnoの3.3vでbme280駆動できた !
https://qiita.com/7L4QOI/items/41358541af5b1abf719c 成功!
var five = require("johnny-five"); var board = new five.Board(); board.on('ready', function () { var bme280 = new five.IMU({ controller: "BME280", address: 0x76, // optional ここ重要 }); bme280.on("data", function(e,data) { if( this.barometer.pressure >90 ){ //気圧の初回値が変なので、異常値は読み飛ばす これも重要 console.log(" celsius(摂氏) : ", this.temperature.celsius); console.log(" pressure(hPa) : ", this.barometer.pressure *10); console.log(" relative humidity: ", this.hygrometer.relativeHumidity); console.log("--------------------------------------"); process.exit(); //終了 これで単発処理となる! } }); })
--------------------------

2025年3月4日火曜日

Mqtt sub pub / dcm pwm :: ラズピコW

-------------------mqtt------------

https://mqttx.app/web-client はウエブソケット版に変更されてもはや1883は使えん!

https://github.com/micropython/\

micropython-lib/blob/master/micropython/umqtt.simple/umqtt/simple.py 

をumqtt.pyでインストした

ーーーーーーーサブスクライブ例ーーーーーーーーーーーーーーーーーーー

subscribe codeでLEDオンオフ成功! https://mqttx.app/web_clientを開く

user名は適当でいいのでログインしてCONNECT 

最初に{"message":"on"}などが入っていたらplaintext設定確認後に

"on"と書き直してpublishでled on,"off"lをpublishでled offに成功した

from machine import Pin

import time

from umqtt import MQTTClient

import ubinascii

import machine

import micropython

import network

import gc


#led alive check

led_pin = Pin(15, Pin.OUT)

led_pin.value(1)

time.sleep(5)

led_pin.value(0)


gc.collect()


ssid = 'HUAWEI@nova@lite@3+'

password = '99991111'

mqtt_server = 'broker.emqx.io'  #Replace with your MQTT Broker IP


client_id = ubinascii.hexlify(machine.unique_id()) 

#ユニークな名でログインのため

topic_sub = b'rpi_pico_w/test_sub' 

# なかったら作る(publish欄で?再調査!)


station = network.WLAN(network.STA_IF)

station.active(True)

station.connect(ssid, password)

while station.isconnected() == False:

  pass

print('Connection successful')

print(station.ifconfig())


def sub_cb(topic, msg): #このcb(callback)でやりたい仕事を仕分ける

  print ('Received Message %s from topic %s' %(msg, topic))

  if msg==b'"on"':

    led_pin.value(1)

  elif msg==b'"off"':

    led_pin.value(0)


def connect_and_subscribe():

  global client_id, mqtt_server, topic_sub

  client = MQTTClient(client_id, mqtt_server)

  client.set_callback(sub_cb)

  client.connect()

  client.subscribe(topic_sub)

  print('Connected to %s MQTT broker, subscribed to %s topic' % \

 (mqtt_server, topic_sub))

  return client


def restart_and_reconnect():

  print('Failed to connect to MQTT broker. Reconnecting...')

  time.sleep(10)

  machine.reset()


try:

  client = connect_and_subscribe()

except OSError as e:    # もしこれ起こったら

  restart_and_reconnect() # 上記でmachine.resetがかかるのでOK

  

while True:

  try:

       new_msg = client.check_msg() #ここは再調査

       time.sleep(10)

  except OSError as e:    # もしこれ起こったら

    restart_and_reconnect()  # 上記でmachine.resetがかかるのでOK

ーーーーー以下はパブリッシュ例ーーーーーーーーーーーーーーーーーーーーーー

https://mqttx.app/web-client#/recent_connections/32a3a13e-7aef-4224-8ddc-6226007aa6caでtest/topic1をつくる

https://mqttx.app/web-clienthttps://tech-and-investment.com/raspberrypi-picow-6-mqtt/ にある以下のコードに成功


import time
import network
from umqtt import MQTTClient
import machine
from picozero import pico_temp_sensor,

import sys

#
# Wi-Fi ルーターのSSIDとパスワードです。
# お使いの設定に書き換えてください。
#
ssid = 'NAME OF YOUR WIFI NETWORK'
password = 'YOUR SECRET PASSWORD'

#
#  Wi-Fiに接続する関数です
#
def connect():
    #Connect to WLAN
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
        
    wlan.connect(ssid, password)
    while wlan.isconnected() == False:
        print('Waiting for connection...')
        time.sleep(1)
    ip = wlan.ifconfig()[0]
    print(f'Connected on {ip}')
    return ip

#
# 受信(Subscribe)したメッセージを表示する関数です
#
def printMessage(topic, message):
    
    # 受信データはbytes型なのでUTF-8の文字列に変換してから表示します
    print("topic:" + topic.decode("utf-8") )
    print("message:" + message.decode("utf-8") )

#
# メインの処理部です
#

# ブローカーのIPやトピック名を定義します。
mqttBroker = '192.168.10.9'
myId = 'esu'
topic= b'test/topic1'

# MQTTのオブジェクト(変数)を定義します
client = MQTTClient(myId, mqttBroker, keepalive=3600)

# 受信(Subscribe)した時に呼ぶ関数を設定します
client.set_callback(printMessage)

# Wi-Fiに接続します
connect()

try:
    # ブローカーに接続します
    client.connect()
    # Subscribeするトピックを登録します。(注:接続前はエラー)
    client.subscribe(topic)
    
except:
    # ブローカーへの接続に失敗した場合は、プログラムを終了します
    print("Could not connect to mqtt server.")
    sys.exit()
    
print("mqqtt connect done ")

#
# 温度センサの情報を3秒ごとにPublishします
#
while True:
    # Pico W 本体の温度情報を取得します
    temp =  pico_temp_sensor.temp

    # 送信(Publish)用のメッセージに温度を代入します
    msg = " \"temp\":" + str(temp)

    # 送信(Publish)します。
    client.publish(topic, msg)

    # ブローカーからのPublishをチェックします。
    client.check_msg()
    # test/topic1に"on"を書くとmessage:onとでる!
    time.sleep(3)

------------------------  pwm --------------------------------------------------

# https://hellobreak.net/raspberry-pi-pico-dc-motor/

from machine import Pin,PWM  # 入出力とアナログ入出力、PWM制御用モジュールを準備

import time                        # タイマーモジュールを準備


led = Pin("LED", Pin.OUT)  # 本体LEDピンをledとして出力に設定

from machine import PWM, Pin

import utime


IN1 = PWM(Pin(0))

IN2 = PWM(Pin(1))

IN1.freq(100)

IN2.freq(100)


max_duty =  32512


# 65025 too big for 4.5v supply to drv8833


while True:

    print("for")

    # 正転

    IN2.duty_u16(0)

    for i in range(50, 100):

        IN1.duty_u16(int(max_duty*i*0.01))

        utime.sleep(0.1)

    print("stop")    

    # ブレーキ

    IN1.duty_u16(max_duty)

    IN2.duty_u16(max_duty)

    utime.sleep(2)

    print("rev")

    # 逆転

    IN1.duty_u16(0)

    for i in range(50, 100):

        IN2.duty_u16(int(max_duty*i*0.01))

        utime.sleep(0.1)

    print("stop2")

    # 停止

    IN1.duty_u16(0)

    IN2.duty_u16(0)

    utime.sleep(2)

2025年3月2日日曜日

Raspberry pi Python :: subprocess / gmail of image or text

 

import subprocess
 
cmd = "ls -l"
subprocess.call(cmd.split())

上記のCMDを任意のシェル命令に変更可能(libcameraetc)

-----------------------image gmail-----------------------------------------------------

https://mychma.com/python-gmail/334/#google_vignette が画像をおくる版

ーーーーーーーーtext gmailーーーーーーーーーーーーーーーーーーーーーーーーー

https://note.com/noa813/n/nde0116fcb03f のとうりにapp pwd作成して成功

my_gmail_account.py is below ::

#ご自身のgmailアドレス account = "********@gmail.com" #アプリパスワード(16桁) password = "****************"

gmail_send.py is below ::

import smtplib, ssl

from email.mime.text import MIMEText

#上で作成したpyファイルから、account情報を読み込みます

import my_gmail_account as gmail


# 送信先のアドレスを登録します

send_address = "*****@gmail.com"


# メインの関数になります

def send_test_email():

  msg = make_mime_text(

    mail_to = send_address,

    subject = "テスト送信",

    body = "Pythonでのメール送信です"

  )

  send_gmail(msg)


# 件名、送信先アドレス、本文を渡す関数です

def make_mime_text(mail_to, subject, body):

  msg = MIMEText(body, "html")

  msg["Subject"] = subject

  msg["To"] = mail_to

  msg["From"] = gmail.account

  return msg


# smtp経由でメール送信する関数です

def send_gmail(msg):

  server = smtplib.SMTP_SSL(

    "smtp.gmail.com", 465,

    context = ssl.create_default_context())

  server.set_debuglevel(0)

  server.login(gmail.account, gmail.password)

  server.send_message(msg)


# うまくいったら”OK”と表示させます

if __name__ == "__main__":

  send_test_email()

  print("ok")