Mencoba seonsor yang ada pada Nano BLE Sense

Melanjutkan tulisan Mencoba Nano 33 BLE Sense saatnya mencoba sensor-sensor yang ada pada modul ini. Sensor yang ada adalah 3D accelerometer, 3D gyroscope, 3D magnetometer (LSM9DS1), MEMS Digital Microphone (MP34DT05), Digital Proximity, Ambient Light, RGB and Gesture (APDS9960), Tekanan Udara (LPS22HB), Suhu dan Kelambaban (HTS221) Chip sensornya kecil kecil sekali!

Arduino Nano 33 BLE Sense Harddware Overview

Langsung saja, untuk mencoba Microphone, bisa kita lihat di sample skecthnya. Pastikan Board sudah bisa terpilih, driver terpasang dan Port juga sudah benar, cek di tulisan Mencoba Nano 33 BLE Sense. Selanjutnya pilih di bagian example -> PDM ->PDMSerialPlotter

Program ini menggunakan mikrofon on-board untuk mendengarkan audio dan memplotnya pada plotter serial. Kita akan melakukan kompilasi yang sangat lambat, membutuhkan waktu sekitar 10 menit untuk mengkompilasi dan mengunggah program. Ini karena integrasi Mbed OS dengan Arduino IDE, semoga Komunitas Arduino bisa memberikan solusi untuk ini.

Hasil tampilan di serial plotter.

Sedangkan untuk mencoba sensor-sensor lain, perlu mengistall library sesuai dengan chip sensornya berikut:

Selanjutnya gunakan contoh sketch berikut:

#include <Arduino_LSM9DS1.h> //IMU
#include <Arduino_LPS22HB.h> //Tekanan 
#include <Arduino_HTS221.h> //Suhu dan kelembaban 
#include <Arduino_APDS9960.h> //Gerakan, cahaya dan proksimiti

void setup(){
  Serial.begin(9600);  

  if (!IMU.begin()) 
  { Serial.println("Chip IMU tidak ditemukan!"); while (1);}

  if (!BARO.begin())  
  { Serial.println("Chip Sensor Tekanan tidak ditemukan!"); while (1);}

  if (!HTS.begin()) 
  { Serial.println("Chip Sensor Suhu &amp; Kelembaban tidak ditemukan!"); while (1);}

  if (!APDS.begin())  
  { Serial.println("Chip Gesture, cahaya dan proksimiti tidak ditemukan!"); while (1);}
 }

float accel_x, accel_y, accel_z;
float gyro_x, gyro_y, gyro_z;
float mag_x, mag_y, mag_z;
float Pressure;
float Temperature, Humidity;
int Proximity;

void loop()
{
  //Accelerometer
  if (IMU.accelerationAvailable()) {
    IMU.readAcceleration(accel_x, accel_y, accel_z);
    Serial.print("Accelerometer = ");Serial.print(accel_x); Serial.print(", ");Serial.print(accel_y);Serial.print(", ");Serial.println(accel_z);
  }
delay (200);

  //Gyroscope 
  if (IMU.gyroscopeAvailable()) {
    IMU.readGyroscope(gyro_x, gyro_y, gyro_z);
    Serial.print("Gyroscope = ");Serial.print(gyro_x); Serial.print(", ");Serial.print(gyro_y);Serial.print(", ");Serial.println(gyro_z);
  }
delay (200);

  //Magnetometer 
  if (IMU.magneticFieldAvailable()) {
    IMU.readMagneticField(mag_x, mag_y, mag_z);
    Serial.print("Magnetometer = ");Serial.print(mag_x); Serial.print(", ");Serial.print(mag_y);Serial.print(", ");Serial.println(mag_z);
  }
delay (200);

  //Pressure 
  Pressure = BARO.readPressure();
  Serial.print("Tekanan= ");Serial.println(Pressure);
  delay (200);

  //Temperature 
  Temperature = HTS.readTemperature();
  Serial.print("Suhu= ");Serial.println(Temperature);
  delay (200);

  //Humidity 
  Humidity = HTS.readHumidity();
  Serial.print("Kelembaban= ");Serial.println(Humidity);
  delay (200);

  //Proximity 
  if (APDS.proximityAvailable()) {
    Proximity = APDS.readProximity();
    Serial.print("Proksimiti= ");Serial.println(Proximity); 
    }
  delay (200);

  Serial.println(); 
  delay(1000);
}

HAsil bisa dilihat di serial monitor

Mencoba Nano 33 BLE Sense

Papan Arduino NANO 33 BLE Sense dirancang untuk solusi hemat daya dan hemat biaya bagi pembuat piranti elektronika yang memiliki konektivitas Bluetooth Hemat Energi. Menggunakan modul NINA B306, terdiri dari chip mikrokontroler Cortex M4F besutan Nordik, yaitu nRF52480. Arduino NANO 33 BLE Sense sama dengan Arduino NANO 33 BLE namun dengan tambahan satu set sensor yang sangat populer untuk mempelajari Machine Learning sebagai bagian dari kecerdasan buatan atau Artificial Inteligence (AI).

Untuk menggunakan modul ini, perlu menambahkan pustaka (library) Arduino nRF528x mbed Core. Caranya dengan memilih menu Tools, kemudian Boards dan Boards Manager, seperti yang didokumentasikan di halaman Arduino Boards Manager.

Arduino NANO 33 BLE Sense adalah variasi perangkat keras dari Arduino NANO 33 BLE; kedua modul tersebut dikenali sebagai Arduino NANO 33 BLE dan ini normal.

menginstal Driver untuk Arduino NANO 33 BLE Sense.

Dengan nRF528x mbed core diinstal, saatnya melanjutkan dengan penginstalan driver.

Pada Windows, jika menginstal Core nRF528x mbed dengan benar, cukup hubungkan Arduino NANO 33 BLE Sense ke komputer dengan kabel USB. Windows akan memulai proses instalasi drivernya setelah papan dicolokkan.

Memulai contoh sketch: blink

Pilih jenis board yang benar

Pilih Port yang sesuai

Mikrokontroler pada Arduino NANO 33 BLE Sense berjalan pada 3.3V, yang berarti tidak boleh menggunakan lebih dari 3.3V ke pin Digital dan Analognya. Berhati-hatilah saat menghubungkan sensor dan aktuator untuk memastikan bahwa batas 3,3V ini tidak pernah terlampaui. Menghubungkan sinyal tegangan yang lebih tinggi, seperti 5V yang biasa digunakan dengan papan Arduino lainnya, akan merusak Sense Arduino NANO 33 BLE.

Tegangan kerja 5V sekarang hanya menjadi pilihan tambahan untuk berbagai modul, sedangkan tegangan 3,3V menjadi tegangan standar untuk IC elektronik.

Current Sense Resistor, Shunt Resistor

Here is a practical example of shunt resistor selection for an MPPT based solar charge controller circuit. The below circuit uses LT3652, an MPPT charge controller from Linear Technology (Analog devices). However, If we look carefully, the battery that will be charged through this circuit is the load.

Current Sense Shunt Resistor Design

The load is connected using a shunt resistor R6. The R6 will determine the charge current, which means the voltage drop of this R6 will remain constant in every case as V = I x R. The R will be constant, the V will be constant, the driver will change the charge current.

To select the shunt resistor, the following things will be required-

  1. The constant voltage that will be used by the driver IC LT3652
  2. The maximum charge current that is required to be delivered to the battery through the resistor.
  3. Since it is a charge controller tolerance could be 1%.

As per the LT3652 datasheet, the sense pin will use 100 mV (0.1V) sense voltage that will be constant. Also, the maximum charge current LT3652 supports is 2A. Thus, the Shunt Resistor value needs to be R = V / I or Shunt resistor value will be 0.1V / 2A = 0.05 Ohms or 50 mili-ohms.

The power rating of this resistor needs to be P = I2R or P = 22 x 0.05 = 0.2 Watt. The close value of the shunt resistor will be 50 mili-ohms, 1% rated, 0.25 Watt. But instead of 0.25 Watt, 0.375 Watt is the safe resistor wattage that can be used.

Source: https://components101.com/articles/what-is-current-sense-resistors-types-specifications-and-selection

Menggunakan SharpDX untuk Joystick

Tambahkan paket NuGet SharpDX.DirectInput

using System;
using System.Threading;

using SharpDX.DirectInput;

namespace PanelRosita
{

    public enum ButtonState : int
    {
        Idle = -1,
        Released = 0,
        Pressed = 128
    }

    public class JoystickThread
    {
        public Thread thr;
        public bool conditionToExitReceived = false;
        public bool isJoystickDetected = false;

        public JoystickThread(string name)
        {

            // detecting joystick
            // Initialize DirectInput
            var directInput = new DirectInput();

            // Find a Joystick Guid
            var joystickGuid = Guid.Empty;

            var devInstance = new DeviceInstance();

            foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,
                        DeviceEnumerationFlags.AllDevices))
            {
                joystickGuid = deviceInstance.InstanceGuid;
                devInstance = deviceInstance;
            }

            // If Gamepad not found, look for a Joystick
            if (joystickGuid == Guid.Empty)
                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick,
                        DeviceEnumerationFlags.AllDevices))
                {
                    joystickGuid = deviceInstance.InstanceGuid;
                    devInstance = deviceInstance;
                }

            // If Joystick not found, throws an error
            if (joystickGuid == Guid.Empty)
            {
                Console.WriteLine("No joystick/Gamepad found.");
                conditionToExitReceived = true;
                throw new Exception("No joystick/Gamepad found.");
            }

            // Instantiate the joystick
            var joystick = new Joystick(directInput, joystickGuid);
            Console.WriteLine("Found Joystick/Gamepad with GUID: {0}", joystickGuid);


            thr = new Thread(() => RunThread(joystick) );
            thr.Name = name;
            thr.Start();
            isJoystickDetected = true;
        }

        // Enetring point for thread 
        void RunThread(Joystick joystick)
        {


            // Query all suported ForceFeedback effects
            Console.WriteLine("Effect:");
            var allEffects = joystick.GetEffects();
            foreach (var effectInfo in allEffects)
                Console.WriteLine("Effect available {0}", effectInfo.Name);

            // Set BufferSize in order to use buffered data.
            joystick.Properties.BufferSize = 128;

            // Acquire the joystick
            joystick.Acquire();

            try
            {
                while (true)
                {
                    if (conditionToExitReceived) // what im waiting for...
                    {
                        Console.WriteLine("Thread is finished");
                        break;
                    }
                    Thread.Sleep(10); // wait 1 second for something to happen.
                    doStuff(ref joystick);
                }
                //perform cleanup if there is any...

            }
            catch (ThreadAbortException ex)
            {
                Console.WriteLine("Thread " + thr.Name + " is aborted and the code is "
                                                 + ex.ExceptionState);
            }
        }

        private void doStuff(ref Joystick joystick)
        {

            try
            {
                joystick.Poll();


                var datas = joystick.GetBufferedData();
                foreach (var state in datas)
                {
                    JoystickButtonPressedEventArgs args = new JoystickButtonPressedEventArgs();
                    JoystickButtonPOVEventArgs povargs = new JoystickButtonPOVEventArgs();
                    args.Value = (ButtonState)state.Value;
                    args.ButtonOffset = state.RawOffset;
                    args.TimeStamp = DateTime.Now;

                    povargs.Value = state.Value;

                    if (state.Offset == JoystickOffset.Buttons0)
                    {
                        OnJoystickButton0(args);
                    }
                    if (state.Offset == JoystickOffset.PointOfViewControllers0)
                    {
                        OnJoystickPointOfViewControllers0(povargs);
                    }

                    if (state.Offset != JoystickOffset.X &amp;&amp; state.Offset != JoystickOffset.Y &amp;&amp; state.Offset != JoystickOffset.RotationZ)
                    {
                        Console.WriteLine("Joystick: " + state);
                    }
                }
            }
            catch (Exception ee)
            {
                OnJoystickDisconnected(ee.Message);
                conditionToExitReceived = true;
                Console.WriteLine("Joystick: " + ee);
                isJoystickDetected = false;
            }
        }

        public class JoystickButtonPressedEventArgs : EventArgs
        {
            public ButtonState Value { get; set; }
            public int ButtonOffset { get; set; }
            public DateTime TimeStamp { get; set; }
        }
        public class JoystickButtonPOVEventArgs : EventArgs
        {
            public int Value { get; set; }
            public int ButtonOffset { get; set; }
            public DateTime TimeStamp { get; set; }
        }

        public event EventHandler<String> OnDisconnected0;
        protected virtual void OnJoystickDisconnected(String e)
        {
            EventHandler<String> handler = OnDisconnected0;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        public event EventHandler<JoystickButtonPressedEventArgs> OnButton0;
        protected virtual void OnJoystickButton0(JoystickButtonPressedEventArgs e)
        {
            EventHandler<JoystickButtonPressedEventArgs> handler = OnButton0;
            if (handler != null)
            {
                handler(this, e);
            }
        }
        public event EventHandler<JoystickButtonPOVEventArgs> OnPointOfViewControllers0;
        protected virtual void OnJoystickPointOfViewControllers0(JoystickButtonPOVEventArgs e)
        {
            EventHandler<JoystickButtonPOVEventArgs> handler = OnPointOfViewControllers0;
            if (handler != null)
            {
                handler(this, e);
            }
        }




    }
}


Penggunaan

       JoystickThread jt;
       private void Form1_Load(object sender, EventArgs e)
        {
            ConnectingToJoystick(FindingJoystick());
        }


        private void ErrorBox(string v)
        {
            MessageBox.Show(v,Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
        }

        private void ConnectingToJoystick(bool joystickDetected)
        {
            if (joystickDetected)
            {
                try
                {
                    jt = new JoystickThread("JoyStick");
                    if (jt.isJoystickDetected)
                    {
                        //add all event here
                        jt.OnButton0 += Jt_OnButton0;
                        jt.OnDisconnected0 += Jt_OnDisconnected0;
                        jt.OnPointOfViewControllers0 += Jt_OnPointOfViewControllers0;
                        jt.isJoystickDetected = true;
                    }
                    else {
                        ErrorBox("Joystick tidak terdeteksi atau tidak kompatibel");
                    }
                }
                catch (Exception ee)
                {
                    ErrorBox("Joystick:" + ee.Message);
                }
            }
        }


        private static bool FindingJoystick()
        {
            Boolean joystickDetected = false;

            // Initialize DirectInput
            var directInput = new DirectInput();

            while (!joystickDetected)
            {

                var devInstance = new DeviceInstance();

                // Find a Joystick Guid
                var joystickGuid = Guid.Empty;

                foreach (var deviceInstance in directInput.GetDevices(DeviceType.Gamepad,
                            DeviceEnumerationFlags.AllDevices))
                {
                    joystickGuid = deviceInstance.InstanceGuid;
                    devInstance = deviceInstance;
                }

                // If Gamepad not found, look for a Joystick
                if (joystickGuid == Guid.Empty)
                    foreach (var deviceInstance in directInput.GetDevices(DeviceType.Joystick,
                            DeviceEnumerationFlags.AllDevices))
                    {
                        joystickGuid = deviceInstance.InstanceGuid;
                        devInstance = deviceInstance;
                    }

                // If Joystick not found, throws an error
                if (joystickGuid == Guid.Empty)
                {
                    Console.WriteLine("No joystick/Gamepad found.");
                    DialogResult rst = MessageBox.Show("Joystick tidak ditemukan atau tidak terhubung. Hubungkan joystick dan klik RETRY, atau klik CANCEL untuk tidak menggunakan joystick.", Application.ProductName, MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);
                    if (rst == DialogResult.Cancel)
                    {
                        return joystickDetected;
                    }
                }
                else
                {
                    joystickDetected = true;
                }
            }
            return joystickDetected;
        }

       private void Jt_OnDisconnected0(object sender, string e)
        {
            //stop robot

            //Finding joystick
            DialogResult rst = MessageBox.Show("No Joystick found. Please Connect the joystick.", Application.ProductName, MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);
            if (rst == DialogResult.Retry)
            {
                ConnectingToJoystick(FindingJoystick());
            }
        }

        private void Jt_OnPointOfViewControllers0(object sender, JoystickThread.JoystickButtonPOVEventArgs e)
        {
            MessageBox.Show("POV value: "+e.Value.ToString());
        }

        private void Jt_OnButton0(object sender, JoystickThread.JoystickButtonPressedEventArgs e)
        {
            String state = "";
            if (e.Value == ButtonState.Pressed)
                state = "Pencet";
            else
                state = "Lepas";

            //Invoke state to button1
            //button1.Invoke(new Action(() => button1.Text = state));

        }


        //Add event on FormClosing to release object
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (jt != null)
            {
                //force to abort
                //jt.thr.Abort("aborted from Main");

                //ask thread to exit polling
                jt.conditionToExitReceived = true;
                
                // Waiting for a thread to terminate. 
                jt.thr.Join();
                Console.WriteLine(jt.thr.Name + " is terminate");
            }
        }

Printer POS USB menggunakan PHP

<?php  
$tmpdir = sys_get_temp_dir();   # ambil direktori temporary untuk simpan file.
$file =  tempnam($tmpdir, 'ctk');  # nama file temporary yang akan dicetak (Windows, samba)

$handle = fopen($file, 'w');


//Printer parameter (ESC POS Command)
$initialized = chr(27).chr(64);

$justify = Chr(27) . Chr(97);
$left = Chr(0); $center = Chr(1);$right = Chr(2);

$fontwidth = Chr(27).Chr(87);
$doublewidth = Chr(1); $normalwidth = Chr(0);

$LF = Chr(10);

//Start making data
$Data  = $initialized;
$Data .= $fontwidth.$doublewidth;
$Data .= $justify.$center;
$Data .= "NAMA TOKO"."\n";
$Data .= $fontwidth.$normalwidth;
$Data .= "Alamat Toko"."\n";
$Data .= $LF.$LF;

//Write data to temporary file
fwrite($handle, $Data);
fclose($handle);

//WIN: send temporary file to nerwork shared printer (share your printer)
//LINUX: send data directly to device
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'){ //Win
    copy($file, "//localhost/POS-58");  # Shared Printer as POS-58
}else if (strtoupper(substr(PHP_OS, 0, 3)) === 'LIN'){ //Linux    
    $device = "/dev/usb/lp0";           # Print at lp0, find it using lsusb! Use udev for managing user access
    if (is_writable($device)) {
        $fp =fopen($device, "w");
        if($fp) {
            fwrite($fp, $Data);
            fclose($fp);
        }
    }
}

unlink($file);
//echo $Data;

?>

Cara mencetak ke printer POS menggunakan PHP. Skrip ini mencontohkan jika menggunakan Windows maupun Linux.

Untuk menggunakan Windows maupun Linux, printer dibuat menjadi akses bersama (shared printer) terlebih dahulu lalu beri nama, misalnya: POS-58. Pastikan bisa diakses di //ALAMAT_IP/NAMA_PRINTER. Untuk skrip ini, menggunakan //localhost/POS-58 Untuk di Windows, buka di Control Panel, pastikan printer yang di-share sudah tersedia dan online.

Sedangkan jika menggunakan Linux, cari nama device dengan perintah:

ls /dev/usb

alamat device printer akan diawali dengan lpx, dimana x bisa 0,1,2 atau angka yang lain. Bagaimana bisa memastikan mana alamat device yang benar? gunakan perintah berikut:

echo "Test Printer" >> /dev/usb/lp0 

Jika printer bisa mencetak, berarti alamat printer adalah benar, yaitu /dev/usb/lp0 jika salah ganti angka 0 dengan angka 1 atau 2 atau angka lain hingga printer bisa mencetak. Pada skrip ini, alamat device perinter adalah /dev/usb/lp0

Penerima Waktu Tunda WiFi

Konfigurasi ESP-01S Relay, GPIO0 di Pull-up, dan Enable dihubungkan ke 3V3. Sedangkan untuk memprogram, tambahkan jumper GPIO0 dan GND pada USB-SERIAL. Hubungkan jumper ini untuk memprogram ESP01
#ifdef ESP32
#include <esp_now.h>
#include <WiFi.h>
#else
#include <espnow.h>
#include <ESP8266WiFi.h>
#define ESP_OK 0
#endif

#define lampPin 0

bool lampON = false;
bool lock = false;


// struktur untuk pengiriman data harus sama dengan struktur pada penerima
typedef struct struct_message {
  int id;     //id pengirim, lock counter
  int x;      //on interval counter
  int y;      //motion (>0)
} struct_message;

struct_message myData;

// Membuat struktur untuk tiap board
struct_message board1;

struct_message boardsStruct[3] = {board1};

volatile int counter = 0;
int max_counter = 0;
int lock_counter = 1;

// callback saat data diterima
#ifdef ESP32
void OnDataRecv(const uint8_t * mac_addr, const uint8_t *incomingData, int len)
#else
void OnDataRecv(uint8_t * mac_addr, uint8_t *incomingData, uint8_t len)
#endif
{
  char macStr[18];
  Serial.print("Paket diterima dari: ");
  snprintf(macStr, sizeof(macStr), "%02x:%02x:%02x:%02x:%02x:%02x",
           mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);
  Serial.println(macStr);
  memcpy(&amp;myData, incomingData, sizeof(myData));
  Serial.printf("Board ID %u: %u bytes\n", myData.id, len);
  // Update the structures with the new incoming data
  boardsStruct[myData.id - 1].x = myData.x;
  boardsStruct[myData.id - 1].y = myData.y;
  Serial.printf("x value: %d \n", boardsStruct[myData.id - 1].x);
  Serial.printf("y value: %d \n", boardsStruct[myData.id - 1].y);
  Serial.println();

  if (!lock) counter = 0;

}


void setup() {
  Serial.begin(74880);
  Serial.println();
  Serial.print("ESP Board MAC Address:  ");
  Serial.println(WiFi.macAddress());

  WiFi.mode(WIFI_STA);

  //Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }

  //daftrakan callback
  esp_now_register_recv_cb(OnDataRecv);

  pinMode(lampPin, OUTPUT);
  Serial.println("Turn Off lamp");
  digitalWrite(lampPin, LOW);
  lampON = false;
}


void loop() {
  // Mengakses data dari setiap board
  //Serial.println(boardsStruct[0].x,DEC);
  //delay(1000);

  //update counter
  if (boardsStruct[0].x > 0)
    max_counter = boardsStruct[0].x;

  if (boardsStruct[0].id > 0)
    lock_counter = boardsStruct[0].id;

  //get motion information and restart counter?
  if (boardsStruct[0].y > 0 &amp;&amp; counter == 0) {
    if (!lampON) {
      Serial.println("Turn On lamp");
        digitalWrite(lampPin, HIGH);

      lampON = true;
    }
  }


  //stop counter turn off lamp
  if (counter >= max_counter &amp;&amp; lampON) {
    Serial.println("Turn Off lamp");
  digitalWrite(lampPin, LOW);
    lampON = false;
    lock = true;
    Serial.println("Lock");
    delay(lock_counter * 1000);
    Serial.println("Release");
    lock = false;
  }

  if (lampON) {
    counter++;
    Serial.print(max_counter - counter);
    delay(1000);
  }

}

Memulai Percobaan ESP-CAM

ESP-CAM memiliki LED pada pin GPIO33. LED ini akan kita gunakan untuk percobaan mati nyala kedip kedip.

Kode Blink pada Arduino

#define LED_BUILTIN 33    //LED ada di GPIO33

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   
  delay(1000);                       
  digitalWrite(LED_BUILTIN, LOW);    
  delay(1000);                       
}

Konfigurasi pilihan Board

Hubungkan USB-Serial atau dapat pula menggunakan Arduino (TX-TX, RX-RX)

Hubungkan GND dengan GPIO0 dan tekan reset.

Jika sudah berhasil Upload, lepas hubungan GND dengan GPIO0 (Kabel abu-abu) dan tekan reset.