This is the circuit that i made: the request is a button that when i push it switch on the rgb led with 3 potentiometers:
This is the code that i've written:
// C++ code
int analogPin = A0;
int potVal = 0;
int button = 0;
void setup()
{
pinMode(13, INPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
pinMode(9, OUTPUT);
Serial.begin(9600);
}
void loop()
{
potVal= analogRead(analogPin); //reads the potentiometer fro, 0-1023
button = digitalRead(2); // reads the button
if (button == HIGH)
{
analogWrite(11, 230); //0 -255
analogWrite(10, 100);
analogWrite(9, 13);
delay(potVal);
analogWrite(11, 80); //0 -255
analogWrite(10, 100);
analogWrite(9, 13);
delay(potVal);
analogWrite(11, 20); //0 -255
analogWrite(10, 200);
analogWrite(9, 13);
delay(potVal);
Serial.print("Pushbutton = ");
Serial.println(button);
Serial.print("Delay = ");
Serial.println(potVal);
}
else
{
analogWrite(11, 0);
analogWrite(10, 0);
analogWrite(9, 0);
Serial.print("Pushbutton = ");
Serial.println(button);
Serial.print("Delay = ");
Serial.println(potVal);
}
}
However I continue to have problems with it and I have no idea why. I've tried to follow all the links but how can I manage these 3 potentiometers? Thanks in advance!
Related
I am trying to make an application that connects to the arduino using the HC 05 module with three ultrasonic sensors. I was able to connect to the application and receive information from a particular sensor. But when I display the distance information of each sensor it is displayed in one text view (I would like three) but I have no idea what I could change in my code. Thanks in advance for your answer. Below I put the code in sequence: from arduino ideas, android studio app, android studio thread
int LtriggerPin = 13;
int LechoPin = 12;
int RtriggerPin = 11;
int RechoPin = 10;
int CtriggerPin = 9;
int CechoPin = 8;
int info = 0;
int state = 0;
void setup() {
Serial1.begin(9600);
pinMode(LtriggerPin, OUTPUT);
pinMode(LechoPin, INPUT);
pinMode(RtriggerPin, OUTPUT);
pinMode(RechoPin, INPUT);
pinMode(CtriggerPin, OUTPUT);
pinMode(CechoPin, INPUT);
}
void loop(){
sensor();
}
void sensor() {
int durationL, distanceL;
int durationR, distanceR;
int durationC, distanceC;
digitalWrite(LtriggerPin, HIGH);
delay(10);
digitalWrite(LtriggerPin, LOW);
durationL = pulseIn(LechoPin, HIGH);
distanceL = (durationL/2) / 29.1;
digitalWrite(RtriggerPin, HIGH);
delay(10);
digitalWrite(RtriggerPin, LOW);
durationR = pulseIn(RechoPin, HIGH);
distanceR = (durationR/2) / 29.1;
digitalWrite(CtriggerPin, HIGH);
delay(10);
digitalWrite(CtriggerPin, LOW);
durationC = pulseIn(CechoPin, HIGH);
distanceC = (durationC/2) / 29.1;
Serial1.print("Left Sensor ");
Serial1.print((String) distanceL + " cm" );
delay(500);
Serial1.println(" ");
Serial1.print("Right Sensor ");
Serial1.print((String) distanceR + " cm" );
delay(500);
Serial1.println(" ");
Serial1.print("Center Sensor ");
Serial1.print((String) distanceC + " cm" );
delay(500);
Serial1.println(" ");
Serial1.println(" ");
Serial1.println(" ");
}
//android thread
#Override
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.available();
if(bytes != 0) {
buffer = new byte[1024];
SystemClock.sleep(100); //pause and wait for rest of data. Adjust this depending on your sending speed.
bytes = mmInStream.available(); // how many bytes are ready to be read?
bytes = mmInStream.read(buffer, 0, bytes); // record how many bytes we actually read
hesler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget(); // Send the obtained bytes to the UI activity
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public void write(String input) {
byte[] bytes = input.getBytes();
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
public void cancel() {
try {
sok.close();
} catch (IOException e) { }
}
// android Handler
handler = new Handler(Looper.getMainLooper()){
#Override
public void handleMessage(Message msg){
if(msg.what == MESSAGE_READ){
String readMessageL = null;
readMessageL = new String((byte[]) msg.obj, StandardCharsets.UTF_8);
TvC.setText(readMessageL);
}
if(msg.what == CONNECTING_STATUS){
char[] sConnected;
if(msg.arg1 == 1)
Tv3.setText(getString(R.string.BTConnected) + msg.obj);
else
Tv3.setText(getString(R.string.BTconnFail));
}
}
};
I am using Raspberry pi3 and DHT11 sensor for temperature monitoring project.
I have following pin positions
VCC to pin no : 2
Ground to pin no : 6
Output to GPIO : BCM22 i.e pin no 15
Code that I have used:
public class WeatherStationActivity extends Activity {
private Handler mHandler = new Handler();
private TextView mTxtStatus;
private PeripheralManagerService service = new PeripheralManagerService();
private Gpio tempGpio;
private int i = 0;
int[] dht11_dat = {0, 0, 0, 0, 0};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("Weather station", "Started Weather Station");
setContentView(R.layout.activity_main);
mTxtStatus = (TextView) findViewById(R.id.txtStatus);
try {
tempGpio = service.openGpio("BCM22");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (i == 10) {
handler.removeCallbacks(this);
} else {
getTemp();
handler.postDelayed(this, 5000);
}
i++;
}
}, 5000);
} catch (Exception e) {
e.printStackTrace();
}
}
private void getTemp() {
boolean laststate = false;
try {
laststate = tempGpio.getValue();
} catch (IOException e) {
e.printStackTrace();
}
int j = 0;
final int MAXTIMINGS = 85;
dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;
try {
tempGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
// tempGpio.setActiveType(Gpio.ACTIVE_LOW);
tempGpio.setValue(false);
// Thread.sleep(18);
TimeUnit.MILLISECONDS.sleep(18);
// tempGpio.setActiveType(Gpio.ACTIVE_HIGH);
// tempGpio.setActiveType(Gpio.ACTIVE_HIGH);
tempGpio.setValue(true);
TimeUnit.MICROSECONDS.sleep(40);
tempGpio.setDirection(Gpio.DIRECTION_IN);
/* tempGpio.setActiveType(Gpio.ACTIVE_HIGH);
tempGpio.setValue(true);*/
// tempGpio.setValue(true);
StringBuilder value = new StringBuilder();
for (int i = 0; i < MAXTIMINGS; i++) {
int counter = 0;
while (tempGpio.getValue() == laststate) {
counter++;
TimeUnit.MICROSECONDS.sleep(1);
if (counter == 255) {
break;
}
}
laststate = tempGpio.getValue();
mTxtStatus.append("\nLast State of Sensor " + laststate);
if (counter == 255) {
break;
}
//* ignore first 3 transitions *//*
if ((i >= 4) && (i % 2 == 0)) {
//* shove each bit into the storage bytes *//*
dht11_dat[j / 8] <<= 1;
if (counter > 16) {
dht11_dat[j / 8] |= 1;
}
j++;
}
}
// check we read 40 bits (8bit x 5 ) + verify checksum in the last
// byte
if ((j >= 40) && checkParity()) {
value.append(dht11_dat[2]).append(".").append(dht11_dat[3]);
Log.i("Logger", "temperature value readed: " + value.toString());
mTxtStatus.append("\nTemp " + value.toString());
} else {
mTxtStatus.append("\nNothing is working ");
Log.i("Logger", "Nothing is working ");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
private boolean checkParity() {
return dht11_dat[4] == (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3] & 0xFF);
}
}
Above code is giving me "Nothing is working" as output.
Any suggestion where I might be doing wrong?
You can't read data from DHT11 using Raspberry Pi 3 with Android Things because duration of DHT11 response pulses is from 26-28 us to 70 us, but max frequency of RP3 with AT GPIO is around 3kHz, which means around 300 us pulse duration. Take a look at answers to this question.
so i am trying to convert an image into a string/hexadecimal array (containing pixel color values) and send it over bluetooth to my arduino controller. I have converted the image to hex array but am unable to send it over bluetooth.
Following is the image to hex-conversion block:
public void getPixelValue (View v){
Bitmap bm = ((BitmapDrawable) imgView.getDrawable()).getBitmap();
boolean hasDrawable = (bm != null);
if(hasDrawable)
{
picw = bm.getWidth();
pich = bm.getHeight();
int[] pix = new int[picw * pich];
bm.getPixels(pix, 0, picw, 0, 0, picw, pich);
int R, G, B,Y;
colorArray = new String[picw][pich];
for (int i = 0; i < picw; i++)
{
for (int j = 0; j < pich; j++)
{
int pixel = bm.getPixel(i,j);
R = Color.red(pixel);
G = Color.green(pixel);
B = Color.blue(pixel);
StringBuilder builder = new StringBuilder();
builder.append("0x");
builder.append(Integer.toHexString(R));
builder.append(Integer.toHexString(G));
builder.append(Integer.toHexString(B));
colorArray[i][j] = builder.toString();
}
}
}
else
{
Toast.makeText(this, "No Image loaded", Toast.LENGTH_SHORT).show();
}
}
Kindly guide on how to send it over bluetooth so that i receive the array as it is on the arduino (nano) side.
This here is the method i am using to send simple text/characters. I type the string, in a textbox, i want to read on the serial monitor (arduino side).
public void sendText (View v) {
try
{
String msg = txtBox.getText().toString();
msg += "\n";
mmOutputStream.write(msg.getBytes());
Toast.makeText(this, "Data Sent", Toast.LENGTH_LONG).show();
}
catch (IOException ex) { }
}
This block works perfectly so i know that the bluetooth pairing and connection is OK. Next, i want to send the string/hex array i have obtained from the 'getpixelvalue' function.
I found a question posted for reading of USB data for FTDI devices.
Transferring data USB
I used this code for prolific device, and the usb can be detected, etc except that the the conn.bulkTransfer() gives a -1.
private class UsbRunnable implements Runnable {
private final UsbDevice mDevice;
UsbRunnable(UsbDevice dev) {
mDevice = dev;
}
public void run() {//here the main USB functionality is implemented
UsbDeviceConnection conn = mUsbManager.openDevice(mDevice);
if (!conn.claimInterface(mDevice.getInterface(1), true)) {
l("in run(), no connection");
return;
}
l("in run(), connection");
conn.controlTransfer(0x40, 0, 0, 0, null, 0, 0);// reset
// mConnection.controlTransfer(0×40,
// 0, 1, 0, null, 0,
// 0);//clear Rx
conn.controlTransfer(0x40, 0, 2, 0, null, 0, 0);// clear Tx
conn.controlTransfer(0x40, 0x02, 0x0000, 0, null, 0, 0);// flow
// control
// none
conn.controlTransfer(0x40, 0x03, 0xC04E, 0, null, 0, 0);// baudrate
// 38400
conn.controlTransfer(0x40, 0x04, 0x0008, 0, null, 0, 0);// data bit
// 8, parity
// none,
// stop bit
// 1, tx off
UsbEndpoint epIN = null;
UsbEndpoint epOUT = null;
byte counter=0;
//conn.bulkTransfer(epOUT, new byte[]{msData}, 1, 0);
UsbInterface usbIf = mDevice.getInterface(0);
for (int i = 0; i < usbIf.getEndpointCount(); i++) {
l("EP: "
+ String.format("0x%02X", usbIf.getEndpoint(i)
.getAddress()));
l("Type:"+usbIf.getEndpoint(i).getType());
if (usbIf.getEndpoint(i).getType() == UsbConstants.USB_ENDPOINT_XFER_INT) {
l("Bulk Endpoint");
l("direction: "+usbIf.getEndpoint(i).getDirection());
if (usbIf.getEndpoint(i).getDirection() == UsbConstants.USB_DIR_IN)
epIN = usbIf.getEndpoint(i);
}
else l("no bulk");
l("epIN: "+epIN.toString());
}
for (;;) {// this is the main loop for transferring
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// This is where it is meant to receive
byte[] buffer = new byte[38400];
StringBuilder str = new StringBuilder();
l("bulk transfer thing: " + conn.bulkTransfer(epIN, buffer, 38400, 1000));
if (conn.bulkTransfer(epIN, buffer, 38400, 1000) > 0 ) {
l("bulk transfer is success");
for (int i = 2; i < 64; i++) {
if (buffer[i] != 0) {
str.append((char) buffer[i]);
} else {
l(str);
break;
}
}
}
// this shows the complete string
l(str);
if (mStop) {
mConnectionHandler.onUsbStopped();
return;
}
l("sent " + counter);
counter++;
counter = (byte) (counter % 16);
}
}
}
// END MAIN LOOP
private BroadcastReceiver mPermissionReceiver = new PermissionReceiver(
new IPermissionListener() {
public void onPermissionDenied(UsbDevice d) {
l("Permission denied on " + d.getDeviceId());
}
});
private static interface IPermissionListener {
void onPermissionDenied(UsbDevice d);
}
public final static String TAG = "USBController";
private void l(Object msg) {
Log.d(TAG, ">==< " + msg.toString() + " >==<");
}
private void e(Object msg) {
Log.e(TAG, ">==< " + msg.toString() + " >==<");
}
Can anyone tell me what changes I need to make? Thank you in advance.
There are several issues.
I assume that the commented out line is where you're having problems. You may want to reformat your code indentation and supply more information. In any case, assuming that your issue is occurring here:
byte counter=0;
//conn.bulkTransfer(epOUT, new byte[]{msData}, 1, 0);
The immediate problem that I see - epOut, the endpoint to which you are sending data is null. So of course it will fail. You're sending data to nothing. I followed the link that you posted to the example code that you copied, they have a line showing:
epOUT = usbIf.getEndpoint(i);
I would strongly suggest at the very least, you first make sure you understand the original code or have it working in your own program before you start making changes. DON'T just copy the above line of code to "fix" your problem.
I am trying to send and receive data over USB, my device, the Acer Iconia A500 has everything needed to connect to the device and everything, that is fine and works properly, but when I try sending and receiving data it doesn't behave as expected. This is my code
for( ; ; ) { //this is the main loop for transferring
String get = "$getPos";
byte[] getBytes = get.getBytes();
conn.bulkTransfer( epOUT, getBytes, getBytes.length, 500 );
try {
Thread.sleep( 500 );
byte[] buffer = new byte[4096];
conn.bulkTransfer( epIN, buffer, 4096, 500 );
StringBuilder byStr = new StringBuilder();
for( int i = 0; i < buffer.length; i++ ) {
if( buffer[i] != 0 ) {
byStr.append( buffer[i] + ", " );
}
}
l( byStr );
}
catch( InterruptedException e ) {
e.printStackTrace();
}
if( mStop ) {
mStopped = true;
return;
}
l( "sent " + counter );
counter++;
counter = (byte)( counter % 16 );
}
Its meant to return an Array of bytes about 80 characters long but it only returns two bytes back which are 1 and 96, if there was a error on the USB devices end it would still return a few more then two. Is my code even close to correct? I based it of the USB to serial article by serverbox.
I was trying to send data over the wrong baud rate.
Here's the code that works. Posting it for everyone who is using FTDI devices and needs help.
private Runnable mLoop = new Runnable() {
#Override
public void run() {
UsbDevice dev = sDevice;
if (dev == null)
return;
UsbManager usbm = (UsbManager) getSystemService(USB_SERVICE);
UsbDeviceConnection conn = usbm.openDevice(dev);
l("Interface Count: " + dev.getInterfaceCount());
l("Using "
+ String.format("%04X:%04X", sDevice.getVendorId(),
sDevice.getProductId()));
if (!conn.claimInterface(dev.getInterface(0), true))
return;
conn.controlTransfer(0x40, 0, 0, 0, null, 0, 0);// reset
// mConnection.controlTransfer(0×40,
// 0, 1, 0, null, 0,
// 0);//clear Rx
conn.controlTransfer(0x40, 0, 2, 0, null, 0, 0);// clear Tx
conn.controlTransfer(0x40, 0x02, 0x0000, 0, null, 0, 0);// flow
// control
// none
conn.controlTransfer(0x40, 0x03, 0x0034, 0, null, 0, 0);// baudrate
// 57600
conn.controlTransfer(0x40, 0x04, 0x0008, 0, null, 0, 0);// data bit
// 8, parity
// none,
// stop bit
// 1, tx off
UsbEndpoint epIN = null;
UsbEndpoint epOUT = null;
byte counter = 0;
UsbInterface usbIf = dev.getInterface(0);
for (int i = 0; i < usbIf.getEndpointCount(); i++) {
l("EP: "
+ String.format("0x%02X", usbIf.getEndpoint(i)
.getAddress()));
if (usbIf.getEndpoint(i).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
l("Bulk Endpoint");
if (usbIf.getEndpoint(i).getDirection() == UsbConstants.USB_DIR_IN)
epIN = usbIf.getEndpoint(i);
else
epOUT = usbIf.getEndpoint(i);
} else {
l("Not Bulk");
}
}
for (;;) {// this is the main loop for transferring
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String get = "$fDump G" + "\n";
l("Sending: " + get);
byte[] by = get.getBytes();
// This is where it sends
l("out " + conn.bulkTransfer(epOUT, by, by.length, 500));
// This is where it is meant to receive
byte[] buffer = new byte[4096];
StringBuilder str = new StringBuilder();
if (conn.bulkTransfer(epIN, buffer, 4096, 500) >= 0) {
for (int i = 2; i < 4096; i++) {
if (buffer[i] != 0) {
str.append((char) buffer[i]);
} else {
l(str);
break;
}
}
}
// this shows the complete string
l(str);
if (mStop) {
mStopped = true;
return;
}
l("sent " + counter);
counter++;
counter = (byte) (counter % 16);
}
}
};