Arduino-Code:
#include <SoftwareSerial.h>
#include <Crc16.h>
#include <EEPROM.h>
#include <WTV020SD16P.h>
Crc16 crc;
SoftwareSerial BTSerial(8, 7);
uint8_t configs[18] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
uint8_t configsbuf[18] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int ledpin = 3;
int bwmPin = 2;
int resetPin = 10; // The pin number of the reset pin.
int clockPin = 6; // The pin number of the clock pin.
int dataPin = 12; // The pin number of the data pin.
int busyPin = 11; // The pin number of the busy pin.
WTV020SD16P WTV020SD16P(clockPin, dataPin, busyPin, resetPin);
unsigned short crcrx = 0;
boolean shot = true;
String inputString = ""; //Serial Buffer
boolean stringComplete = false; //Serial Helper
boolean block = false;
boolean receiveconfig = 0;
int minlight = 0;
int maxlight = 0;
String worker = "";
unsigned long previousMillis = millis();
unsigned long previousbwmMillis = millis();
unsigned long previoussoundMillis = millis();
int lastbwmstate = LOW;
unsigned long lastlow = millis();
boolean lowtime = LOW;
int fract = 0;
int fractdelay = 0;
int itlast = 0;
int itcnt = 0;
//sound
int soundstart = 0;
//delay
int it = 0;
unsigned int fordelay = 0;
int delayer = 0;
int steps = 0;
unsigned long currentMillis = millis();
int randermin = 0;
int randermax = 0;
int busyPinstate = LOW;
unsigned long lastserial = millis();
int bwmstate = LOW;
void setup() {
pinMode(13, OUTPUT);
digitalWrite(13, HIGH);
Serial.begin(57600);
BTSerial.begin(9600); //BTserial
inputString.reserve(100);
pinMode(ledpin, OUTPUT);
pinMode(bwmPin, INPUT);
pinMode(busyPin, INPUT);
analogWrite(ledpin, 255);
load_config();
delay(1000);
WTV020SD16P.reset();
delay(1000);
bwmstate = digitalRead(bwmPin);
if (bwmstate == HIGH)
{
Serial.println("HIGH");
minlight = configs[0];
maxlight = configs[1];
fract = configs[2] ;/// 4;
fractdelay = configs[3];
} else {
minlight = configs[4];
maxlight = configs[5];
fract = configs[6];// / 4;
fractdelay = configs[7];
}
}
boolean firststart = true;
void loop() {
MyserialEvent();
serialmenu();
busyPinstate = digitalRead(busyPin);
bwmstate = digitalRead(bwmPin);
if (bwmstate == HIGH)
lastlow = currentMillis;
unsigned long temp = configs[14] * 1000;
if ( currentMillis - lastlow >= temp)
{
lowtime = HIGH;
} else {}
currentMillis = millis();
if (configs[12] == 1) {
blinking();
} else analogWrite(ledpin, 0 );
if (configs[13] != 0 && configs[12] != 0 )
soundcheck();
if (bwmstate != lastbwmstate) {
lastbwmstate = bwmstate;
Serial.println("toggle");
}
}
int bwmsteps = 0;
boolean clearinput = false;
unsigned long lastcall = 0; int i = 0;
int lastbwm = LOW;
boolean startsound = true;
unsigned long lastsound = millis();
unsigned long delaysound = millis();
unsigned long lastloww = millis();
boolean lowwtime = LOW;
boolean ledstate = LOW;
int lastledstate = LOW;
void soundcheck() {
if ( currentMillis - lastsound >= (configs[10] * 2000) && configs[8] != 0 && lowtime)
{
if ( bwmstate == HIGH && lastbwmstate == LOW ) {
lastbwmstate = HIGH;
startsound = true;
delaysound = currentMillis;
Serial.println("SOUNDTIME");
}
if ( startsound && currentMillis - delaysound >= configs[11] * 2000 && startsound )
{
Serial.println("Sound");
delay(200);
WTV020SD16P.setVolume(configs[8]);
delay(300);
WTV020SD16P.asyncPlayVoice(configs[9]);
startsound = false;
lastsound = currentMillis;
delaysound = currentMillis;
lastlow = currentMillis;
lowtime = LOW;
}
}
}
void MyserialEvent() {
if (millis() - lastserial > 1000)
{
inputString = "";
stringComplete = false;
lastserial = millis();
}
while (BTSerial.available()) {
char inChar = (char)BTSerial.read();
inputString += inChar;
if (inChar == '\n') {
stringComplete = true;
worker = inputString;
inputString = "";
}
}
}
void serialmenu() {
if (stringComplete)
{
Serial.println(worker);
if (worker == "XXCHECKXX\r\n")
{
String temp = "";
stringComplete = false;
block = true;
for (int i = 0; i < 17; i++)
{
temp = temp + configs[ i];
if (i != 17)
temp = temp + ",";
}
uint16_t value = 0;
byte buf[temp.length() + 1];
temp.getBytes(buf, sizeof(buf));
value = calc_crc(buf, sizeof(buf) - 1, 0xffff);
temp = temp + ",";
temp = temp + value;
temp = temp + "\r\n";
Serial.println(temp);
BTSerial.print(temp);
block = false;
} else if (worker == "XXSETXX\r\n")
{
worker = "";
receiveconfig = true;
inputString = "";
stringComplete = false;
block = true;
} else if (receiveconfig == true && stringComplete) {
block = true;
Serial.println(worker);
int lastcomma = worker.lastIndexOf(",");
String rxcrc = worker.substring(0, lastcomma);
String rxval = worker.substring(lastcomma, -2);
uint16_t rxvalue = 0;
byte buff[rxcrc.length() + 1];
rxcrc.getBytes(buff, sizeof(buff));
rxvalue = calc_crc(buff, sizeof(buff) - 1 , 0xffff);
char buf[worker.length() + 1];
worker.toCharArray(buf, sizeof(buf));
int i = 0;
char *ptr;
ptr = strtok(buf, ",");
while (ptr != NULL) {
if (i < 16) {
String tmpstr = ptr;
uint8_t tempint = tmpstr.toInt();
configsbuf[i] = tempint;
i++;
} else {
String tmpstr = ptr;
crcrx = (unsigned short)tmpstr.toInt();
}
ptr = strtok(NULL, ",");
}
//Serial.println(crcrx);
//Serial.println(rxvalue);
if (crcrx == rxvalue) {
memcpy( configs, configsbuf, 18 );
if (bwmstate == HIGH || busyPinstate == HIGH)
{ minlight = configs[0];
maxlight = configs[1];
fract = configs[2] ;
fractdelay = configs[3];
} else {
minlight = configs[4];
maxlight = configs[5];
fract = configs[6] ;
fractdelay = configs[7];
}
if (fract == 0)
fract = 1;
if (fractdelay == 0)
fractdelay = 1;
it = random(minlight, maxlight);
fordelay = fract;
delayer = fractdelay;
} else {
}
block = false;
receiveconfig = false;
worker = "";
stringComplete = false;
} else if (worker == "XXSAVEXX\r\n")
{
save_config();
worker = "";
stringComplete = false;
}
else if (worker == "XXSTARTXX\r\n")
{
WTV020SD16P.setVolume(configs[8]);
delay(200);
WTV020SD16P.asyncPlayVoice(configs[9]);
worker = "";
stringComplete = false;
} else {
clearinput = true;
stringComplete = false;
}
}
}
void save_config() {
for (int i = 0 ; i < 17; i++)
EEPROM.update(i, configs[i]);
}
void load_config() {
for (int i = 0 ; i < 17; i++)
configs[i] = EEPROM.read(i);
}
boolean first = false;
int oldbwmstate = LOW;
void blinking() {
if (bwmstate == HIGH && lowtime) {
ledstate = HIGH;
lastloww = currentMillis;
}
if ( currentMillis - lastloww >= (configs[15] * 1000))
{
ledstate = LOW;
}
switch (steps) {
case 0:
if (lastledstate != ledstate)
if (ledstate )
{
minlight = configs[0];
maxlight = configs[1];
fract = configs[2] ;/// 4;
fractdelay = configs[3];
} else {
minlight = configs[4];
maxlight = configs[5];
fract = configs[6];// / 4;
fractdelay = configs[7];
}
if (lastledstate != ledstate) {
it = random(minlight, maxlight);
//it = random(minlight, maxlight);
lastledstate = ledstate;
}
if (fract == 0)
fract = 1;
if (fractdelay == 0)
fractdelay = 1;
fordelay = fractdelay;
delayer = fractdelay;
steps = 1;
break;
case 1:
analogWrite(ledpin, it );
if (currentMillis - previousMillis >= fordelay) {
previousMillis = currentMillis;
it = it + fract ;
}
if (it > randermax)
{
steps = 2;
randermin = random(minlight, it);
if ( (it - randermin) < fract)
it = it + fract;
}
break;
case 2:
analogWrite(ledpin, it );
if (currentMillis - previousMillis >= fordelay ) {
previousMillis = currentMillis; it = it - fract ;
}
if (it < randermin) {
steps = 0;
randermax = random(it, maxlight);
if ( (randermax - it) < fract) {
if (it < fract)
it = 0;
else
it = it - fract;
}
}
break;
case 3:
steps = 0;
break;
default:
steps = 0;
break;
}
}
uint16_t calc_crc(unsigned char *msg, int n, uint16_t init)
{
uint16_t x = init;
while (n--)
{
x = crc_xmodem_update(x, (uint16_t) * msg++);
}
return (x);
}
uint16_t crc_xmodem_update (uint16_t crc, uint8_t data)
{
int i;
crc = crc ^ ((uint16_t)data << 8);
for (i = 0; i < 8; i++)
{
if (crc & 0x8000)
crc = (crc << 1) ^ 0x1021; //(polynomial = 0x1021)
else
crc <<= 1;
}
return crc;
}
Android- MainActivity:
package com.mybag.philm.mybag;
import java.lang.String;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener, CompoundButton.OnCheckedChangeListener {
private static final String LOG_TAG = "BLUETOOTH";
private static String mac_adresse; // MAC Adresse des Bluetooth Adapters
private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Variablen
private BluetoothAdapter adapter = null;
private BluetoothSocket socket = null;
private OutputStream stream_out = null;
private InputStream stream_in = null;
private boolean is_connected = false;
private SeekBar bar1;
private SeekBar bar2;
private SeekBar bar3;
private SeekBar bar4;
private SeekBar bar5;
private SeekBar bar6;
private SeekBar bar7;
private SeekBar bar8;
private SeekBar bar9;
private SeekBar bar10;
private SeekBar bar11;
private SeekBar bar12;
private SeekBar bar13;
private SeekBar bar14;
private Switch switch1;
private Switch switch2;
private boolean isparsedfirest = false;
private long lastupdate = 0;
public int[] optionvalues = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,};
private View myview = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter == null || !adapter.isEnabled()) {
Toast.makeText(this, "Bitte Bluetooth aktivieren",
Toast.LENGTH_LONG).show();
Log.d(LOG_TAG,
"onCreate: Bluetooth Fehler: Deaktiviert oder nicht vorhanden");
finish();
return;
} else
Log.d(LOG_TAG, "onCreate: Bluetooth-Adapter ist bereit");
bar1 = (SeekBar) findViewById(R.id.seekBar1);
bar2 = (SeekBar) findViewById(R.id.seekBar2);
bar3 = (SeekBar) findViewById(R.id.seekBar3);
bar4 = (SeekBar) findViewById(R.id.seekBar4);
bar5 = (SeekBar) findViewById(R.id.seekBar5);
bar6 = (SeekBar) findViewById(R.id.seekBar6);
bar7 = (SeekBar) findViewById(R.id.seekBar7);
bar8 = (SeekBar) findViewById(R.id.seekBar8);
bar7 = (SeekBar) findViewById(R.id.seekBar7);
bar8 = (SeekBar) findViewById(R.id.seekBar8);
bar9 = (SeekBar) findViewById(R.id.seekBar9);
bar10 = (SeekBar) findViewById(R.id.seekBar10);
bar11 = (SeekBar) findViewById(R.id.seekBar11);
bar12 = (SeekBar) findViewById(R.id.seekBar12);
bar13 = (SeekBar) findViewById(R.id.seekBar13);
bar14 = (SeekBar) findViewById(R.id.seekBar14);
switch1 = (Switch) findViewById(R.id.switch1);
switch2 = (Switch) findViewById(R.id.switch2);
bar1.setOnSeekBarChangeListener(this);
bar2.setOnSeekBarChangeListener(this);
bar3.setOnSeekBarChangeListener(this);
bar4.setOnSeekBarChangeListener(this);
bar5.setOnSeekBarChangeListener(this);
bar6.setOnSeekBarChangeListener(this);
bar7.setOnSeekBarChangeListener(this);
bar8.setOnSeekBarChangeListener(this);
bar9.setOnSeekBarChangeListener(this);
bar10.setOnSeekBarChangeListener(this);
bar11.setOnSeekBarChangeListener(this);
bar12.setOnSeekBarChangeListener(this);
bar13.setOnSeekBarChangeListener(this);
bar14.setOnSeekBarChangeListener(this);
switch1.setOnCheckedChangeListener(this);
switch2.setOnCheckedChangeListener(this);
verbinden(myview);
while (!socket.isConnected()) {
}
while(!check(myview)){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
}
public boolean parsenow = false;
public void start(View v) {
senden("XXSTARTXX\r\n");
}
public boolean check(View v) {
//parsenow = false;
try {
senden("XXCHECKXX\r\n");
String temptext = "";
temptext = empfangen();
temptext = temptext.replaceAll("(\r\n)", "");
String temp = "";
String[] separated = temptext.split(",");
Log.d(LOG_TAG,
"Empfangen: " + temptext);
Log.d(LOG_TAG,
"Arraylength: " + separated.length);
int indexlast = temptext.lastIndexOf(',');
temp = temptext.substring(0, indexlast);
int lastcrc = GenerateChecksumCRC16(temp.getBytes());
if (lastcrc == Integer.parseInt(separated[ 18 ])) {
for (int c = 0; c < 17; c++) {
optionvalues[ c ] = Integer.parseInt(separated[ c ]);
Log.d(LOG_TAG, c + " : " + optionvalues[ c ]);
}
String soundstemp = "";
if (lastcrc == Integer.parseInt(separated[ 18 ])) {
parsenow = true;
isparsedfirest = true;
}
Log.d(LOG_TAG,
"CRC-Hier: " + lastcrc + " CRC-Ardu: " + separated[ 18 ]);
bar1.setMax(255);
bar1.setProgress(optionvalues[ 0 ]);
bar2.setMax(255);
bar2.setProgress(optionvalues[ 1 ]);
bar3.setMax(255);
bar3.setProgress(optionvalues[ 2 ]);
bar4.setMax(255);
bar4.setProgress(optionvalues[ 3 ]);
bar5.setMax(255);
bar5.setProgress(optionvalues[ 4 ]);
bar6.setMax(255);
bar6.setProgress(optionvalues[ 5 ]);
bar7.setMax(255);
bar7.setProgress(optionvalues[ 6 ]);
bar8.setMax(255);
bar8.setProgress(optionvalues[ 7 ]);
bar9.setMax(8);
bar9.setProgress(optionvalues[ 8 ]);
bar10.setMax(10);
bar10.setProgress(optionvalues[ 9 ]);
bar11.setMax(255);
bar11.setProgress(optionvalues[ 10 ]);
bar12.setMax(255);
bar12.setProgress(optionvalues[ 11 ]);
bar13.setMax(255);
bar13.setProgress(optionvalues[ 14 ]);
bar14.setMax(255);
bar14.setProgress(optionvalues[ 15 ]);
switch1.setChecked(optionvalues[ 12 ] != 0 ? true : false);
switch2.setChecked(optionvalues[ 13 ] != 0 ? true : false);
}
return true;
} catch (Exception e) {
e.printStackTrace();
Log.d(LOG_TAG, "TEEEEEEEEEEASSSSSSSSSTTTTTTT " + mac_adresse);
}
return false;
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device)
throws IOException {
if (Build.VERSION.SDK_INT >= 10) {
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[]{UUID.class});
return (BluetoothSocket) m.invoke(device, uuid);
} catch (Exception e) {
Log.e(LOG_TAG, "Could not create Insecure RFComm Connection", e);
}
}
return device.createRfcommSocketToServiceRecord(uuid);
}
public void verbinden(View v) {
mac_adresse = "00:BA:55:57:9B:70";//"AB:DA:B2:56:34:02";////"AB:DA:B2:56:34:02";//"AB:D7:A3:56:34:02";
Log.d(LOG_TAG, "Verbinde mit " + mac_adresse);
BluetoothDevice remote_device = adapter.getRemoteDevice(mac_adresse);
// Socket erstellen
try {
socket = remote_device.createInsecureRfcommSocketToServiceRecord(uuid);
Log.d(LOG_TAG, "Socket erstellt");
} catch (Exception e) {
Log.e(LOG_TAG, "Socket Erstellung fehlgeschlagen: " + e.toString());
}
adapter.cancelDiscovery();
// Socket verbinden
try {
socket.connect();
Log.d(LOG_TAG, "Socket verbunden");
is_connected = true;
} catch (IOException e) {
is_connected = false;
Log.e(LOG_TAG, "Socket kann nicht verbinden: " + e.toString());
}
// Socket beenden, falls nicht verbunden werden konnte
if (!is_connected) {
try {
socket.close();
} catch (Exception e) {
Log.e(LOG_TAG,
"Socket kann nicht beendet werden: " + e.toString());
}
}
// Outputstream erstellen:
try {
stream_out = socket.getOutputStream();
Log.d(LOG_TAG, "OutputStream erstellt");
} catch (IOException e) {
Log.e(LOG_TAG, "OutputStream Fehler: " + e.toString());
is_connected = false;
}
// Inputstream erstellen
try {
stream_in = socket.getInputStream();
Log.d(LOG_TAG, "InputStream erstellt");
} catch (IOException e) {
Log.e(LOG_TAG, "InputStream Fehler: " + e.toString());
is_connected = false;
}
if (is_connected) {
Toast.makeText(this, "Verbunden mit " + mac_adresse,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Verbindungsfehler mit " + mac_adresse,
Toast.LENGTH_LONG).show();
}
}
public void senden(String send) {
String message = send;
byte[] msgBuffer = message.getBytes();
if (is_connected) {
Log.d(LOG_TAG, "Sende Nachricht: " + message);
try {
stream_out.write(msgBuffer);
} catch (IOException e) {
Log.e(LOG_TAG,
"Bluetest: Exception beim Senden: " + e.toString());
}
}
}
public String empfangen() throws IOException {
String msg = "";
try {
long lastwait = System.currentTimeMillis();
while (System.currentTimeMillis() - lastwait < 500) {
if (stream_in.available() > 0) {
char last = (char) stream_in.read();
msg += last;
lastwait = System.currentTimeMillis();
if (last == '\n') {
break;
}
}
}
} catch (Exception e) {
Log.e(LOG_TAG, "Fehler beim Empfangen: " + e.toString());
}
int tempav = stream_in.available();
return msg;
}
public void trennen(View v) {
if (is_connected && stream_out != null) {
is_connected = false;
Log.d(LOG_TAG, "Trennen: Beende Verbindung");
try {
stream_out.flush();
socket.close();
} catch (IOException e) {
Log.e(LOG_TAG,
"Fehler beim beenden des Streams und schliessen des Sockets: "
+ e.toString());
}
} else
Log.d(LOG_TAG, "Trennen: Keine Verbindung zum beenden");
}
public void save(View v) {
senden("XXSAVEXX\r\n");
}
public void sync(View v) {
setdata();
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(LOG_TAG, "onDestroy. Trenne Verbindung, falls vorhanden");
trennen(null);
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
public void setdata() {
if (isparsedfirest && System.currentTimeMillis() - lastupdate > 500) {
optionvalues[ 0 ] = bar1.getProgress();
optionvalues[ 1 ] = bar2.getProgress();
optionvalues[ 2 ] = bar3.getProgress();
optionvalues[ 3 ] = bar4.getProgress();
optionvalues[ 4 ] = bar5.getProgress();
optionvalues[ 5 ] = bar6.getProgress();
optionvalues[ 6 ] = bar7.getProgress();
optionvalues[ 7 ] = bar8.getProgress();
optionvalues[ 8 ] = bar9.getProgress();
optionvalues[ 9 ] = bar10.getProgress();
optionvalues[ 10 ] = bar11.getProgress();
optionvalues[ 11 ] = bar12.getProgress();
optionvalues[ 12 ] = switch1.isChecked() ? 1 : 0;
optionvalues[ 13 ] = switch2.isChecked() ? 1 : 0;
optionvalues[ 14 ] = bar13.getProgress();
optionvalues[ 15 ] = bar14.getProgress();
String temptext = "";
temptext = "";
for (int b = 0; b <= 17; b++) {
if (b != 0) {
temptext += ",";
}
temptext += optionvalues[ b ];
}
int tempcrc = GenerateChecksumCRC16(temptext.getBytes());
temptext += ",";
temptext += tempcrc;
senden("XXSETXX\r\n");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d(LOG_TAG,
"sende:: " + temptext);
senden(String.format("%s\r\n", temptext));
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
setdata();
}
@Override
public void onResume() {
super.onResume();
check(myview);
}
static public int GenerateChecksumCRC16(byte bytes[]) {
int crc = 0xFFFF;
int temp;
int crc_byte;
for (int byte_index = 0; byte_index < bytes.length; byte_index++) {
crc_byte = bytes[ byte_index ];
for (int bit_index = 0; bit_index < 8; bit_index++) {
temp = ((crc >> 15)) ^ ((crc_byte >> 7));
crc <<= 1;
crc &= 0xFFFF;
if (temp > 0) {
crc ^= 0x1021;
crc &= 0xFFFF;
}
crc_byte <<= 1;
crc_byte &= 0xFF;
}
}
return crc;
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
} setdata();
}
}