My Daily Gist | Ferdinand Silva


Pure C Language In Arduino Uno (Sample Code 2)

 
/*
Compiling and uploading to Arduino Uno (Sample Code 2)
======================================================
avr-gcc -Os -mmcu=atmega328p -c test.c
avr-gcc -mmcu=atmega328p -o test.elf test.o
avr-objcopy -O ihex -R .eeprom test.elf test.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/cu.usbmodem1421 -b 115200 -U flash:w:test.hex
*/
#ifndef F_CPU
#define F_CPU 16000000UL //set frequency
#endif
#include <avr/io.h>
#include <util/delay.h>
#define MS_DELAY 2000 //2 seconds
int main() {
DDRB |= _BV(DDB1); //set pin 9 to output
DDRB |= _BV(DDB0); //set pin 8 to output
for(;;) {
PORTB |= _BV(PORTB1); //set pin 9 to high
PORTB &= ~_BV(PORTB0); //set pin 8 to low
_delay_ms(MS_DELAY); //delay
PORTB &= ~_BV(PORTB1); //set pin 9 to low
PORTB |= _BV(PORTB0); //set pin 8 to high
_delay_ms(MS_DELAY); //delay
}
return 0;
}
view raw test.c hosted with ❤ by GitHub

Pure C Language In Arduino Uno

 
/*
Compiling and uploading to Arduino Uno
======================================
avr-gcc -Os -mmcu=atmega328p -c test.c
avr-gcc -mmcu=atmega328p -o test.elf test.o
avr-objcopy -O ihex -R .eeprom test.elf test.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/cu.usbmodem1421 -b 115200 -U flash:w:test.hex
*/
#ifndef F_CPU
#define F_CPU 16000000UL //set frequency
#endif
#include <avr/io.h>
#include <util/delay.h>
#include <compat/deprecated.h>
#define MS_DELAY 2000 //2 seconds
int main() {
DDRB = 0xFF; //all pins of PORT-B are output pins
for(;;) {
sbi(PORTB, PB1); //set pin 9 to high
cbi(PORTB, PB0); //set pin 8 to low
_delay_ms(MS_DELAY); //delay
cbi(PORTB, PB1); //set pin 9 to low
sbi(PORTB, PB0); //set pin 8 to high
_delay_ms(MS_DELAY); //delay
}
return 0;
}
view raw test.c hosted with ❤ by GitHub

Connecting Android Device To HC-05 Bluetooth Module Sample Code (Java)

 
package com.ferdinandsilva.bluetoothtest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
/*
Permissions:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
*/
public Button button;
public EditText editText;
public BluetoothAdapter btAdapter;
public BluetoothDevice btDevice;
public BluetoothSocket btSocket;
public static final String SERVICE_ID = "00001101-0000-1000-8000-00805f9b34fb"; //SPP UUID
public static final String SERVICE_ADDRESS = "98:D3:31:FB:82:85"; // HC-05 BT ADDRESS
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
editText = (EditText) findViewById(R.id.editText);
btAdapter = BluetoothAdapter.getDefaultAdapter();
btDevice = btAdapter.getRemoteDevice(SERVICE_ADDRESS);
if(btAdapter == null) {
Toast.makeText(getApplicationContext(), "Bluetooth not available", Toast.LENGTH_LONG).show();
} else {
if(!btAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, 3);
} else {
ConnectThread connectThread = new ConnectThread(btDevice);
connectThread.start();
}
}
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(btSocket != null) {
try{
OutputStream out = btSocket.getOutputStream();
out.write((editText.getText().toString() + "\r\n").getBytes());
}catch(IOException e) {
}
}
}
});
}
private class ConnectThread extends Thread {
private final BluetoothSocket thisSocket;
private final BluetoothDevice thisDevice;
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
thisDevice = device;
try {
tmp = thisDevice.createRfcommSocketToServiceRecord(UUID.fromString(SERVICE_ID));
} catch (IOException e) {
Log.e("TEST", "Can't connect to service");
}
thisSocket = tmp;
}
public void run() {
// Cancel discovery because it otherwise slows down the connection.
btAdapter.cancelDiscovery();
try {
thisSocket.connect();
Log.d("TESTING", "Connected to shit");
} catch (IOException connectException) {
try {
thisSocket.close();
} catch (IOException closeException) {
Log.e("TEST", "Can't close socket");
}
return;
}
btSocket = thisSocket;
}
public void cancel() {
try {
thisSocket.close();
} catch (IOException e) {
Log.e("TEST", "Can't close socket");
}
}
}
}

Simple IRC Bot (Go Programming Language Sample Code)

 
package main
import (
"fmt"
"net"
"bufio"
"strings"
"net/textproto"
)
func main() {
var server string = "irc.freenode.net"
var port string = "6667"
var ircNick string = "ferdinandsilva"
var ircChannel string = "ferdinandsilva"
conn, err := net.Dial("tcp", server + ":" + port)
if err != nil {
fmt.Println("Can't connect to ", server)
} else {
defer conn.Close()
reader := bufio.NewReader(conn)
tp := textproto.NewReader(reader)
needBreak := false
for {
if needBreak {
break
}
data, err := tp.ReadLine()
if err == nil {
fmt.Println(data)
switch {
case strings.Contains(data, "Checking Ident"):
fmt.Fprintf(conn, "NICK " + ircNick + "\r\n")
fmt.Fprintf(conn, "USER " + ircNick + " \"" + ircNick + ".com\" \"" + server + "\" :" + ircNick + " robot\r\n")
case strings.Contains(data, "This nickname is registered"):
fmt.Println("Nickname is registered, please change the ircNick value.")
needBreak = true
case strings.Contains(data, "Nickname is already in use"):
fmt.Println("Nickname is in use, please change the ircNick value.")
needBreak = true
case strings.Contains(data, "Erroneous Nickname"):
fmt.Println("Nickname is erroneous, please change the ircNick value.")
needBreak = true
case strings.Contains(data, "End of /MOTD command"):
fmt.Fprintf(conn, "JOIN #" + ircChannel + "\r\n")
case strings.Contains(data, "PING :"):
fmt.Fprintf(conn, strings.Replace(data, "PING", "PONG", 1) + "\r\n")
case strings.Contains(data, "JOIN #"):
fmt.Fprintf(conn, "PRIVMSG #" + ircChannel + " :Magandang araw sa'yo!!!\r\n")
}
} else {
fmt.Println("Disconnected to: ", server)
break
}
}
}
}
view raw main.go hosted with ❤ by GitHub

(Go Programming Language) Write To Raspberry Pi GPIO Pins

 
/*
Install the library
-------------------
go get github.com/six519/gpio
Sample usage
------------
Go to https://github.com/six519/gpio
*/
package gpio
import (
"fmt"
"os"
"strconv"
)
const OUTPUT string = "out"
const LOW string = "0"
const HIGH string = "1"
var export_path string = "/sys/class/gpio/export"
var gpio_path string = "/sys/class/gpio/gpio"
var unexport_path string = "/sys/class/gpio/unexport"
func writeInt(path string, val int) {
f, err := os.Create(path)
if err != nil {
fmt.Println("Can't open file " + path)
} else {
defer f.Close()
f.WriteString(strconv.Itoa(val))
}
}
func writeStr(path string, val string) {
f, err := os.Create(path)
if err != nil {
fmt.Println("Can't open file " + path)
} else {
defer f.Close()
f.WriteString(val)
}
}
func PinMode(pin int, mode string) {
writeInt(export_path, pin)
direction := gpio_path + strconv.Itoa(pin) + "/direction"
writeStr(direction, mode)
}
func DigitalWrite(pin int, val string) {
value := gpio_path + strconv.Itoa(pin) + "/value"
writeStr(value, val)
}
func CleanUp(pin int) {
writeInt(unexport_path, pin)
}
view raw gpio.go hosted with ❤ by GitHub