Arduino

From no name for this wiki
Jump to: navigation, search

Begriffe


BLE switch with pebble

ArduinoBLEPebbleSwitch

Bluetooth 220 V voltage switch

Picture of the project.

Control a household lamp with your smartphone.

Needed:


connecting blue tooth modem to arduino

Important thing is that your modem supports 5v for logic. Many boards are built for 3v. Only four wires needed:

  • Connect grd on arduino to grd on modem
  • Connect 5v of arduio to vcc on modem
  • Connect arduino digital pin 2 to tx on modem
  • Connect arduino digital pin 3 to rx on modem

Do not use pins on arduino that have a tx and rx printed on them. They are used to communicate with your pc while connected by usb.

connecting relay to your arduino

This is straight forward too:

  • Connect grd on arduino to grd on relay module.
  • Connect 5v of arduino to vcc on relay module.
  • Connect digital pin 13 to Ch1 or In1 on relay module.
  • Connect digital pin 12 to Ch2 or In2 on relay module.
  • e.c.t.

arduino code

Whenever a 41 (decimal) byte value is sent from smartphone, then the relay1 switches state. Whenever a 42 (decimal) byte value is sent from smartphone, then the relay2 switches state.

#include <SoftwareSerial.h>  
 

int relay1 = 13;
int relay2 = 12;
int bluetoothTx = 2;  
int bluetoothRx = 3;

int relay1on = 0;
int relay2on = 0;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

// the setup routine runs once when you press reset:
void setup() {     
  

  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  
  Serial.begin(9600);  // Begin the serial monitor§§§§9600bps

  bluetooth.begin(115200);  // The Bluetooth Mate defaults to 115200bps
}

// the loop routine runs over and over again forever:
void loop() {
  if(bluetooth.available())  // If the bluetooth sent any characters
  {
    byte btInput = bluetooth.read();
    Serial.print((char)btInput);  
    
    if(btInput == 41)
    {
      if(relay1on == 0)
      {
       digitalWrite(relay1, HIGH);
       bluetooth.print("A1 ON");
       relay1on = 1;
       
      }
      else
      {
        digitalWrite(relay1, LOW);
         bluetooth.print("A1 OFF");
         relay1on = 0;
      }
    }
    if(btInput == 42)
    {
      if(relay2on == 0)
      {
       digitalWrite(relay2, HIGH);
       bluetooth.print("A2 ON");
       relay2on = 1;
      }
      else
      {
        digitalWrite(relay2, LOW);
         bluetooth.print("A2 OFF");
         relay2on = 0;
      }
    }
    
  }

  if(Serial.available())  // If stuff was typed in the serial monitor, for testing purposes.
  {
    // Send any characters the Serial monitor prints to the bluetooth
    bluetooth.print((char)Serial.read());
  }
}

start a bt app on your smartphone

Maybe there is already a bt app in the app store. I wrote a very simple one myself.

Pair devices first (passcode for my sparkfun bt modem is 1234).

Then send a 41 (demical) byte. This is character 'a' to turn relay on or off.

android code

There are plenty of tutorials on the web.

http://developer.android.com/guide/topics/connectivity/bluetooth.html

Pair devices first. The bt modem is usually visible to other devices.

package ch.arduinobt;

public interface BlueToothListener {
	
	void bytesReceived(byte[] bytes);
	
	void connected(String deviceName);
	
	void connecting();
	
	void disconnected();
	
	void error(String error);
	
}
package ch.arduinobt;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;

public class BlueTooth {

	public static BlueTooth current = new BlueTooth();

	private final static int REQUEST_ENABLE_BT = 1;

	private Set<BluetoothDevice> pairedDevices;

	private BluetoothAdapter mBluetoothAdapter;

	private UUID MY_UUID = UUID
			.fromString("00001101-0000-1000-8000-00805F9B34FB");

	List<BlueToothListener> listeners = new ArrayList<BlueToothListener>();

	ConnectThread thread;

	private class ConnectThread extends Thread {

		private final BluetoothSocket mmSocket;
		private final BluetoothDevice mmDevice;

		public ConnectThread(BluetoothDevice device) {
			// Use a temporary object that is later assigned to mmSocket,
			// because mmSocket is final
			BluetoothSocket tmp = null;
			mmDevice = device;

			// Get a BluetoothSocket to connect with the given BluetoothDevice
			try {
				// MY_UUID is the app's UUID string, also used by the server
				// code
				tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
			} catch (IOException e) {
				error(e);
			}
			mmSocket = tmp;
		}

		public void run() {

			// Cancel discovery because it will slow down the connection
			mBluetoothAdapter.cancelDiscovery();

			try {
				// Connect the device through the socket. This will block
				// until it succeeds or throws an exception
				mmSocket.connect();

				// Listeners
				for (BlueToothListener listener : listeners) {
					listener.connected(mmDevice.getName());
				}

			} catch (IOException connectException) {

				error(connectException);

				// Unable to connect; close the socket and get out
				try {
					mmSocket.close();
				} catch (IOException closeException) {

				}
				return;
			}

			// Do work to manage the connection (in a separate thread)
			try {
				manageConnectedSocket(mmSocket);
			} catch (Exception e) {
				e.printStackTrace();
			}
			finally
			{
				
			}
		}

		/** Will cancel an in-progress connection, and close the socket */
		public void cancel() {
			if (mmSocket != null) {
				try {
					mmSocket.close();
				} catch (IOException e) {
				}
			}
		}

		/* Call this from the main activity to send data to the remote device */
		public void write(byte[] bytes) throws IOException {
			mmSocket.getOutputStream().write(bytes);			
		}
	}

	public void addBtListener(BlueToothListener listener) {
		listeners.add(listener);
	}

	public void removeBtListener(BlueToothListener listener) {
		listeners.remove(listener);
	}

	public void startSocket(String deviceName) {
		for(BlueToothListener listener : listeners)
		{
			listener.connecting();
		}
		cancel();
		BluetoothDevice device = null;
		for (BluetoothDevice dev : pairedDevices) {
			String name = dev.getName();
			if (name.equalsIgnoreCase(deviceName)) {
				device = dev;
				break;
			}
		}
		if (device != null) {
			thread = new ConnectThread(device);
			thread.start();
		} else {
			error(new IOException("BT device not found"));
		}
	}

	private void error(Exception ex) {
		String message = ex.getMessage();
		for (BlueToothListener listener : listeners) {
			listener.error(message);
		}
	}

	public void cancel() {
		if (thread != null) {
			thread.cancel();
		}
	}

	/* Call this from the main activity to send data to the remote device */
	public void write(byte[] bytes) throws IOException {
		if (thread != null) {
			thread.write(bytes);
		}
		else
		{
			throw new RuntimeException("not conneted to bt device");
		}
	}

	private void manageConnectedSocket(BluetoothSocket socket) throws Exception {

		byte[] buffer = new byte[1024]; // buffer store for the stream
		int bytes; // bytes returned from read()

		while (true) {
			bytes = socket.getInputStream().read(buffer);
			if (bytes > 0) {
				sendBytesToReceivers(buffer, bytes);
			}
		}
	}

	private void sendBytesToReceivers(byte[] buffer, int length) {
		byte[] toSend = new byte[length];
		System.arraycopy(buffer, 0, toSend, 0, length);

		for (BlueToothListener listener : listeners) {
			listener.bytesReceived(toSend);
		}
	}

	public List<String> getBoundDevices() {
		List<String> deviceNames = new ArrayList<String>();
		try {
			mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
			if (mBluetoothAdapter == null) {
				throw new RuntimeException("Does not support bt");
			}

			if (!mBluetoothAdapter.isEnabled()) {
				BlueToothNotEnabledException exception = new BlueToothNotEnabledException();
				throw exception;
			}
			pairedDevices = mBluetoothAdapter.getBondedDevices();

			// If there are paired devices
			if (pairedDevices.size() > 0) {
				// Loop through paired devices
				for (BluetoothDevice device : pairedDevices) {
					String name = device.getName();
					deviceNames.add(name);
				}
			}
		} catch (Exception ex) {
			error(ex);
		}

		return deviceNames;
	}
}

package ch.arduinobt;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	private final static int BYTES_RECEIVED = 98543;
	private final static int BT_CONNECTED = 39719;
	private final static int BT_DISCONNECTED = 39720;
	private final static int BT_CONNECTING = 39721;
	private final static int BT_ERROR = 12388;
	
	
	Handler mHandler;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		//Start Button
		final Button button = (Button) findViewById(R.id.buttonSelectDevice);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	startSelectBtDevice();
            }
        });
        
        
        //Send Button
        final Button sendButton = (Button) findViewById(R.id.button1);
        sendButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	sendBytes();
            }
        });
        
        //GUI Message Handler
        mHandler = new Handler(){
        	 @Override
        	 public void handleMessage(Message msg) {
        		 switch (msg.what) {
        		 	case BYTES_RECEIVED:
        		 		byte[] bytes = (byte[]) msg.obj;
        		 		bytesReceived(bytes);
        		 		break;
        		 	case BT_CONNECTED:
        		 		String deviceName = (String) msg.obj;
        		 		connected(deviceName);
        		 		break;
        		 	case BT_ERROR:
        		 		String errorMsg = (String) msg.obj;
        		 		error(errorMsg);
        		 		break;  
        		 	case BT_DISCONNECTED:
        		 		disconnected();
        		 		break;
        		 	case BT_CONNECTING:
        		 		connecting();
        		 		break;        		 		
        		 }        		         		
        	 }
        	};
        
        //BT Listener
        BlueTooth.current.addBtListener(new BlueToothListener() {
			
			@Override
			public void bytesReceived(byte[] bytes) {
				
				mHandler.obtainMessage(BYTES_RECEIVED, 0, 0, bytes)
                .sendToTarget();
			}

			@Override
			public void connected(String deviceName) {
				mHandler.obtainMessage(BT_CONNECTED, 0, 0, deviceName)
                .sendToTarget();				
			}

			@Override
			public void error(String error) {
				mHandler.obtainMessage(BT_ERROR, 0, 0, error)
                .sendToTarget();	
			}

			@Override
			public void disconnected() {
				mHandler.obtainMessage(BT_DISCONNECTED, 0, 0)
                .sendToTarget();					
			}

			@Override
			public void connecting() {
				mHandler.obtainMessage(BT_CONNECTING, 0, 0)
                .sendToTarget();	
				
			}	
			
			
			
		});
        	
	}
	
	private void sendBytes()
	{
		final TextView sendTextView = (TextView) findViewById(R.id.editTextSend);
		String text = sendTextView.getText().toString();
		Integer i = 0;
		byte b;
		try{
			i = Integer.parseInt(text);			
			b = intToByteArray(i)[3];
		}
		catch(Exception ex)
		{
			Toast.makeText(this, "Can not convert to byte", Toast.LENGTH_LONG).show();
			return;
		}
		try {
			BlueTooth.current.write(new byte[]{b});
		} 
		catch(Exception e)
		{
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
		}
		sendTextView.setText("");
	}
	
	private void bytesReceived(byte[] bytes)
	{
		StringBuffer buffer = new StringBuffer();
		for(byte b : bytes)
		{
			int i =  (int)b & 0xff;;			
			Integer ii = i;
			buffer.append(ii.toString());
			buffer.append(" ");
		}
		final TextView textView = (TextView) findViewById(R.id.textViewReceived);
		String text = textView.getText().toString();
		if(text.length() > 0)
		{
			text = buffer.toString() + " " + text;
		}
		else
		{
			text = buffer.toString();
		}
		textView.setText(text);
	}
	
	private void connected(String deviceName)
	{
		final TextView devNameTextView = (TextView) findViewById(R.id.textViewConnectedDevice);
		devNameTextView.setText(deviceName);
		Toast.makeText(this, deviceName, Toast.LENGTH_SHORT).show();
		final Button sendButton = (Button) findViewById(R.id.button1);
		sendButton.setEnabled(true);
	}
	
	private void disconnected()
	{
		final TextView devNameTextView = (TextView) findViewById(R.id.textViewConnectedDevice);
		devNameTextView.setText("disconnected");
		Toast.makeText(this, "Disconnected", Toast.LENGTH_SHORT).show();
		final Button sendButton = (Button) findViewById(R.id.button1);
		sendButton.setEnabled(false);
	}
	
	private void connecting()
	{
		final TextView devNameTextView = (TextView) findViewById(R.id.textViewConnectedDevice);
		devNameTextView.setText("connecting ..., please wait");		
	}
	
	private void error(String errorMessage)
	{
		Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
	}	
	
	private void startSelectBtDevice()
	{
		BlueTooth.current.cancel();
		Intent intent = new Intent(this, SelectBTDevciceActivity.class);
		startActivity(intent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	public void onDestroy() {		
		super.onDestroy();	     
		BlueTooth.current.cancel();
	}	
	
	@Override
	public void onPause()
	{
		super.onDestroy();	     		
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
	}
	
	public static byte[] intToByteArray(int value) {
        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            int offset = (b.length - 1 - i) * 8;
            b[i] = (byte) ((value >>> offset) & 0xFF);
        }
        return b;
    }
	
}


package ch.arduinobt;

import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

public class SelectBTDevciceActivity extends Activity {

	
	StableArrayAdapter adapter;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_select_btdevcice);
		
		
		final ListView listview = (ListView) findViewById(R.id.listViewBtDevices);
		
		try {						
			List<String> btDeviceNames = BlueTooth.current.getBoundDevices();
			adapter = new StableArrayAdapter(this, android.R.layout.simple_list_item_1, btDeviceNames);
			listview.setAdapter(adapter);
			    
			listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, final View view,
						int position, long id) {	
					final String device = (String) parent.getItemAtPosition(position);
					selectBtDevice(device);
				}
			});			
		}
		catch(Exception e)
		{
			Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
		}
		
		
		
	}
	
	private void selectBtDevice(String device)
	{
		BlueTooth.current.startSocket(device);
		finish();		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.select_btdevcice, menu);
		return true;
	}

}