Distance detector

The distance detector with LED and buzzer

Tutorial for above is here.

Tried the first time and fried my usb-c, wasn’t reading that I needed to ground them… Now it works 🙂 Adjusted the frequency to a nicer sounding tone.

#define trigPin 7
#define echoPin 6
#define led 13
#define led2 12
#define led3 11
#define led4 10
#define led5 9
#define led6 8
#define buzzer 3

int sound = 5550;


void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  pinMode(led5, OUTPUT);
  pinMode(led6, OUTPUT);
  pinMode(buzzer, OUTPUT);
 
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW); 
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
 

  if (distance <= 30) {
    digitalWrite(led, HIGH);
    sound = 5550;
}
  else {
    digitalWrite(led,LOW);
  }
  if (distance < 25) {
      digitalWrite(led2, HIGH);
      sound = 9250;
}
  else {
      digitalWrite(led2, LOW);
  }
  if (distance < 20) {
      digitalWrite(led3, HIGH);
      sound = 11200;
} 
  else {
    digitalWrite(led3, LOW);
  }
  if (distance < 15) {
    digitalWrite(led4, HIGH);
    sound = 12500;
}
  else {
    digitalWrite(led4,LOW);
  }
  if (distance < 10) {
    digitalWrite(led5, HIGH);
    sound = 13500;
}
  else {
    digitalWrite(led5,LOW);
  }
  if (distance < 5) {
    digitalWrite(led6, HIGH);
    sound = 15000;
}
  else {
    digitalWrite(led6,LOW);
  }
 
  if (distance > 30 || distance <= 0){
    Serial.println("Out of range");
    noTone(buzzer);
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
    // tone( pin number, frequency in hertz, duration in milliseconds);
    tone(buzzer, sound);
   
  }
  delay(500);
}

Crash collision sensor

Having some time to myself to play with some new sensor, the circuit is pretty straight forward, waiting for my raspberry pi in the meantime..

Sensor
VCC >> 5V
GND >> GND
OUT >> pin 3

/* Crash Collision Sensor Detection Module
 *  
 */
int ledPin = 13;                // choose the pin for the LED
int inputPin = 3;               // connect sensor to input pin 3
int count = 0;

void setup() {
  Serial.begin(9600);           // Init the serial port
   
  pinMode(ledPin, OUTPUT);      // declare LED as output
  pinMode(inputPin, INPUT);     // declare Micro switch as input
}
 
void loop(){
  int val = digitalRead(inputPin);  // read input value
  if (val == HIGH) {                // check if the input is HIGH
    digitalWrite(ledPin, LOW);      // turn LED OFF
  } else {
    digitalWrite(ledPin, HIGH);     // turn LED ON
    count += 1;
    Serial.println(count);
    Serial.println("Switch Pressed!");
  }
  delay(80); // the higher the delay the less sensitive the switch
}

Random reads to keep

Companies that does vulnerability scanning

Encrypted Database and todos

From the discussions, when a company has a encrypted database(s)
– It needs to be backedup
– backups needs to be tested and verified using a snapshot on a separate vm instance
– if it was encrypted, the generated keys need to be saved
– there are ITCP audits that exists in large companies

Finding a needle in a haystack

Well, today I needed to debug an error on the server. I needed to search the logs to find what the error was. Finding the particular information that I needed was difficult simply because I wasn’t proficient in vim and linux commands, and, the log was more than 20GB of data..

As usual, I looked for my all-knowing friend google. One of the developers on stack overflow suggested using grep instead because searching large files using vim is slow. So I went to the folder containing the logs to grep the particular regex I was looking for into a text file.

cat myerrors.log | grep theRegexIWant >> outputMySearchResults.txt

From there, retrieve (copy) the id that is relevant to that particular error and search using vim. So heading back to the massive .log file

vim myerrors.log

# using vim to find the particular error
/myCopiedIdToFindTheError

Perhaps there is a better way, but at least I managed to find what I wanted from the logs. Probably truncating the logs to days or size is a better option. 😀

Jest, Puppeteer or ?Nightwatch

After using nightwatch we decided to switch to using jest and puppeteer for the many more apis and functionalities to support our wordpress plugin and chrome extension. A note here though that puppeteer only supports chrome/chromium. If you need to test cross browsers, nightwatch may be better with their browser drivers.

To setup jest and puppeteer. `—save-dev` or `-D` is saving to a dev dependency in package.json.

npm install --save-dev jest-puppeteer puppeteer jest

for simplicity, in package.json, add jest config. Alternatively, jest can have its own jest.config.js

“scripts": { 
“test”:”jest" 
}, 
"jest": { 
"preset": "jest-puppeteer" 
}, 

I’ve also install ndb, a useful debugger for jest and puppeteer

npm install —D ndb 

and in your package.json, scripts can include

“scripts”: { "test:debug": "npx ndb jest” } 

also to add linting for jest

npm install @types/jest 

create a simple sum.js and sum.test.js to test jest https://jestjs.io/docs/en/getting-started

to run the test,

npm run test

create also a simple google.test.js to test puppeteer with jest. `describe` `it` `expect` are jest while `browser` `page` are automatically handled by puppeteer, there is no need to add its dependency here. 

Read jest with puppeteer documents  https://jestjs.io/docs/en/puppeteer

Read puppeteer documents https://github.com/GoogleChrome/puppeteer

describe('Google', () => { 
beforeAll(async () => { 
await page.goto('https://google.com'); 
}); 
it('should be titled "Google"', async () => { 
await expect(page.title()).resolves.toMatch('Google'); 
}); }); 

run

npm run test 

Ubuntu auto script

So I was pretty tired of updating every single server I was messing around with for experimental purpose so I decided to create an auto scripting for the usual ‘apt update && apt upgrade’ command

Go to your server

ssh root@example.com

Go to the folder where Cron exists. Cron is a time-based scheduler that allows daily, weekly, monthly and custom scripting. https://help.ubuntu.com/community/AutoWeeklyUpdateHowTo

cd /etc/cron.weekly

If I wanted it to run the updates and upgrades on a daily basis, it would be ‘cron.daily’. So in the directory where you wish to schedule your auto script, create a file using any editor of your choice (vim for me)

vim auto_update

In the file add

apt update && apt upgrade -y 
apt autoclean 
apt autoremove

A note though that upgrade might sometimes cause stuff to break, so a heads up here.

‘apt autoclean‘ → cleans obsolete packages,
‘apt autoremove‘ → removes orphaned packages which are not longer needed from the system

Now, to make the file executable in order for cron to be able to run it. In the directory where the script is, run,

chmod 755 auto_update 

Some other stuff you can do is to find files in example directory with size >+30GB and execute remove

find ~/example -type f -size +30000M -exec rm {} \;

Arduino Touch sensor, Ultrasonic sensor, Heartbeat sensor

Touch sensor

https://create.arduino.cc/projecthub/Arca_Ege/how-to-use-a-touch-sensor-81b7f4

The circuit from sensor > arduino
VCC Pin > 5V
GND > GND
OUT > Pin 2
LED pin (short leg (anode) to ground, long leg to Pin 13)

int in = 2; 
int out = 13;  
int state = HIGH;  
int r;           
int p = LOW;    
long time = 0;       
long debounce = 200;
   
void setup()
{
  pinMode(in, INPUT);
  pinMode(out, OUTPUT);
}
void loop()
{
  r = digitalRead(in);
  if (r == HIGH && p == LOW && millis() - time > debounce) {
    if (state == HIGH)
      state = LOW;
    else 
      state = HIGH;
    time = millis();    
  }
  digitalWrite(out, state);
  p = r;
}

Ultrasonic sensor

https://howtomechatronics.com/tutorials/arduino/ultrasonic-sensor-hc-sr04/
https://randomnerdtutorials.com/complete-guide-for-ultrasonic-sensor-hc-sr04/

The circuit from sensor > arduino
+5 > 5V
Trigger > pin 7
Echo > pin 6
GND > GND

const int trigPin = 7; // Trigger Pin of Ultrasonic Sensor
const int echoPin = 6; // Echo Pin of Ultrasonic Sensor

void setup() {
   Serial.begin(9600); // Starting Serial Terminal
}

void loop() {
   long duration, inches, cm;
   pinMode(trigPin, OUTPUT);
   digitalWrite(trigPin, LOW);
   delayMicroseconds(2);
   digitalWrite(trigPin, HIGH);
   delayMicroseconds(10);
   digitalWrite(trigPin, LOW);
   pinMode(echoPin, INPUT);
   duration = pulseIn(echoPin, HIGH);
   inches = microsecondsToInches(duration);
   cm = microsecondsToCentimeters(duration);
   Serial.print(inches);
   Serial.print("in, ");
   Serial.print(cm);
   Serial.print("cm");
   Serial.println();
   delay(100);
}

long microsecondsToInches(long microseconds) {
   return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds) {
   return microseconds / 29 / 2;
}

Pulse/ Heartbeat Sensor

https://www.hackster.io/Johan_Ha/from-ky-039-to-heart-rate-0abfca — The author converted the signal from the sensor into human-readable beats per minute.

The circuit from sensor > arduino
Signal (S pin) > A0
5V ( + middle pin) > 5V
GND (- pin) > GND

Note: place your finger between the IR led and the light transistor of the sensor. Make sure they are contain in a dark environment to remove noise reflecting from artificial lights. (The reason why the SpO2 probe have opaque protective covers?)

#define samp_siz 4
#define rise_threshold 4

// Pulse Monitor Test Script
int sensorPin = 0;

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

void loop ()
{
    float reads[samp_siz], sum;
    long int now, ptr;
    float last, reader, start;
    float first, second, third, before, print_value;
    bool rising;
    int rise_count;
    int n;
    long int last_beat;

    for (int i = 0; i < samp_siz; i++)
      reads[i] = 0;
    sum = 0;
    ptr = 0;

    while(1)
    {
      // calculate an average of the sensor
      // during a 20 ms period (this will eliminate
      // the 50 Hz noise caused by electric light
      n = 0;
      start = millis();
      reader = 0.;
      do
      {
        reader += analogRead (sensorPin);
        n++;
        now = millis();
      }
      while (now < start + 20);  
      reader /= n;  // we got an average
      
      // Add the newest measurement to an array
      // and subtract the oldest measurement from the array
      // to maintain a sum of last measurements
      sum -= reads[ptr];
      sum += reader;
      reads[ptr] = reader;
      last = sum / samp_siz;
      // now last holds the average of the values in the array

      // check for a rising curve (= a heart beat)
      if (last > before)
      {
        rise_count++;
        if (!rising && rise_count > rise_threshold)
        {
          // Ok, we have detected a rising curve, which implies a heartbeat.
          // Record the time since last beat, keep track of the two previous
          // times (first, second, third) to get a weighed average.
          // The rising flag prevents us from detecting the same rise more than once.
          rising = true;
          first = millis() - last_beat;
          last_beat = millis();

          // Calculate the weighed average of heartbeat rate
          // according to the three last beats
          print_value = 60000. / (0.4 * first + 0.3 * second + 0.3 * third);
          Serial.print(print_value);
          Serial.print('\n');
          third = second;
          second = first;
        }
      }
      else
      {
        // Ok, the curve is falling
        rising = false;
        rise_count = 0;
      }
      before = last;
      ptr++;
      ptr %= samp_siz;
    }
}

wootS! My first electronic setup with Arduino Uno and DHT 11 Temperature and Humidity Sensor

yeppp! My first project, after waiting approximately 10 days for delivery from China! Bought all the requisites, in twos, and with different sellers, because I was afraid the shipment will break some components or that the particular shipment from the seller is defective. I’m paranoid that way. Heh.

DHT 11 or DHT 22 (3 pins) to Arduino Uno

+out > 5V
middle pin > pin 2
-out > gnd

In your Arduino code, make sure you include library adafruit and DHT sensor for it to work

#include <DHT.h>
#define DHTPIN 2     // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22   // DHT 22 or DHT 11 change DHT accordingly
DHT dht(DHTPIN, DHTTYPE);


void setup() {
  Serial.begin(9600);
  Serial.println(F("DHT22 test!"));

  dht.begin();
}


void loop() {
  // Wait a few seconds between measurements.
  delay(2000);

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);
  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    return;
  }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print(F("Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print(F("°C "));
  Serial.print(f);
  Serial.print(F("°F  Heat index: "));
  Serial.print(hic);
  Serial.print(F("°C "));
  Serial.print(hif);
  Serial.println(F("°F"));
}

And how I setup my basic env on a new macOS when the previous one died.

Open Terminal in MacGo to home brew —> download brew sh (Package manager for MacOS)
brew install git —> https://medium.com/@katopz/how-to-upgrade-git-ff00ea12be18

brew cask search iterm2
brew cask install iterm2
brew cask install spectacle // functionality
brew cask install visual-studio-code // code editor
brew search vim
brew install vim
brew search nvm 
brew install nvm
brew install postgres

after installing nvm follow instruction on screen

mkdir ~/.nvm

check bash profile

vim ~/.bashprofilevim // program that runs iterm

I probably need to do some editing to make it readable… but for now personal notes. 😀