Stepper Motor Control Example
Now let’s take a look at the second example, controlling a stepper motor. At the top of the screen we have the same components for the Bluetooth connection as the previous example. Next we have a Canvas component which is used for drawing and inserting images. I inserted two transparent images which I previously drew. The first one is an image of a gauge which will be fixed in place and the second one is an image of a pointer which will be rotating. Next we have a Check button for switching between Manual and Auto or continuously running mode and a button for changing the rotation direction. At the button we have a slider for changing the rotation speed of the stepper motor.
Here are the blocks and the Arduino code behind this example. So, in the Blocks editor again we have the same blocks for the Bluetooth connection as the previous example.
Now for rotating the pointer image we use the ImageSprite function “.PointInDirection” which rotates the image from 0° position to the X and Y coordinates where the Canvas has been touched. At the same time we set the rotated ImageSprite heading to the text label above. After that we call custom made procedure, or function which is actually a 10m seconds delay.
Lastly we send the heading value as a Text to the Arduino using the “SendText” Bluetooth function. This value will be accepted by the Arduino and it will rotate the stepper motor accordingly.
Next is the the CheckBox block. So if the CheckBox is checked we will send the text “Auto” to the Arduino which will activate stepper motor to rotate continuously. While we are in this mode if we press the “Reverse” button, we will send the text “Reverse” to the Arduino which will change the rotation direction of the motor. Also, while we are in this mode, we can change the speed of rotation. If we change the position of the slider, the current value of the slider position will be send to the Arduino which will change the rotation speed of the stepper. If we uncheck the CheckBox we will get back into the manual mode. Here’s the demonstration of the example.
Here’s a download file of the above MIT App Inventor project, as well as the two images used in the project:
Here’s the Arduino code of the second example:
/* Stepper Motor Control via HC-05 Bluetooth Module * * by Dejan Nedelkovski, www.HowToMechatronics.com * */ // Defining variables const int stepPin = 7; const int dirPin = 6; String state = ""; int currentHeading=0; int currentAngle=0; int lastAngle=0; int angle=0; int rotate=0; int runContinuously=0; String mode = "Manual"; boolean dirRotation = HIGH; int rotSpeed = 1500; void setup() { // Sets the two pins as Outputs pinMode(stepPin,OUTPUT); pinMode(dirPin,OUTPUT); Serial.begin(38400); // Default communication rate of the Bluetooth module } void loop() { delayMicroseconds(1); if(Serial.available() > 0){ // Checks whether data is comming from the serial port state = Serial.readString(); // Reads the data from the serial port } // When Auto Button is pressed if (mode == "Auto") { if (state == "Reverse") { delay(10); if (dirRotation == HIGH) { dirRotation = LOW; } else { dirRotation = HIGH; } digitalWrite(dirPin,dirRotation); delay(10); state = ""; } rotSpeed = state.toInt(); if (rotSpeed >= 300 && rotSpeed <= 3000) { digitalWrite(stepPin,HIGH); delayMicroseconds(rotSpeed); digitalWrite(stepPin,LOW); delayMicroseconds(rotSpeed); } else { digitalWrite(stepPin,HIGH); delayMicroseconds(1500); digitalWrite(stepPin,LOW); delayMicroseconds(1500); } if (state == "Manual"){ mode = state; } } // When Program is in Manual mode else if (mode == "Manual"){ currentHeading = state.toInt(); //Serial.println(angle); //Serial.println(state); if (currentHeading < 0 ){ currentHeading = 360+currentHeading; } currentAngle = map(currentHeading,0,359,0,200); digitalWrite(dirPin,HIGH); // Enables the motor to move in a particular direction // Makes 200 pulses for making one full cycle rotation if (currentAngle != lastAngle){ if(currentAngle > lastAngle){ rotate = currentAngle - lastAngle; for(int x = 0; x < rotate; x++) { digitalWrite(stepPin,HIGH); delayMicroseconds(500); digitalWrite(stepPin,LOW); delayMicroseconds(500); } } if(currentAngle < lastAngle){ rotate = lastAngle - currentAngle; digitalWrite(dirPin,LOW); //Changes the rotations direction for(int x = 0; x < rotate; x++) { digitalWrite(stepPin,HIGH); delayMicroseconds(500); digitalWrite(stepPin,LOW); delayMicroseconds(500); } } } lastAngle = currentAngle; if (state == "Auto"){ mode = state; } } }
Code language: Arduino (arduino)
Building the App – Example 1
Now we are ready to build the first example. We will start with the layout of the program. First we will add some HorizontalArrangements from the layout Palette and set their properties like the height, the width and the alignment to match our program desired look. Then from the UserInterface Palette we will add a ListPicker and attach an image to it. The ListPicker will be used for selecting the Bluetooth device to which our smartphone will connect.
Next we will add another HorizontalArrangements in which we will place a Label. This label will indicate whether the smartphone is connected or not to the Bluetooth module and that’s why we will set the initial text of this label to “Not Connected”. The next label will be used for displaying the status of the LED, whether is turned off or on. The initial state will be “LED: OFF”. Next we will add the two buttons, ‘Turn On’ and ‘Turn Off’ for controlling the LED. At this point it is good to rename the components so that we can easier recognize and use them in the Blocks editor later. What’s left now is to add the BluetoothClient which is a Non-visible component as well as a clock which will be used for the real time indication of the connection status.
Blocks Editor
Now in the Blocks editor we are ready to give life to our program. From the left side we got all the blocks and function related to the previously added components.
We will start with the BluetoothList ListPicker. From there first we will add the ‘BeforePicking’ block and attach to it the ‘set Bluetooth Elements’ block. Then from the BluetoothClient blocks we will add the ‘BluetoothClient AddressesAndNames’ block. What this set of blocks will do is set a list of Bluetooth devices which are already paired with our phone so when we will click on the ListPicker “Connect Button” the list of all paired devices will show up.
Next we have to set what will happen after we will pick or select our particular Bluetooth module. From the BluetoothClient block we will add the ‘call BluetoothClient .Connect address’ block and add the block ‘BluetoothList Selection’ to it, which means that our phone will connect to the Bluetooth address that we have previously selected.
Next from the Clock blocks we will add the “.Timer” block. Within this block we will make the real time indication whether the phone is connected or not to the Bluetooth module using the “set Text” block of the label named “Connected”.
Next we need to give life to the two buttons. So when the “TurnOn_Button” will be clicked we will use the Bluetooth client function “Send1ByteNumber” to send a number to the Arduino Bluetooth module. In our case that’s the number 49 which corresponds to the character ‘1’ according to the ASCII table and that will turn on the LED. Right after that we will use the “ReceiveText” BluetoothClient function to receive the incoming String which is send back from the Arduino to the phone. This String is set to the “LED_Status” Label.
The same procedure goes for the “TurnOff_Button” where the sending number should be changed to 48 which corresponds to character ‘0’. What’s left now is to download and install the program on our smartphone. We can do that from the “Build” menu by either saving it to our computer and then transfer to our phone or scan a QR code for online download of the program. Here’s the demonstration of the example.
Here’s a download file of the above MIT App Inventor project:
Introduction: Using MIT App Inventor to Control Arduino – the Basics
We all have a smartphone. Now, with that statement of the obvious, let me ask you this. Why is your Arduino hardly ever connected to your smartphone. Bluetooth costs about $8 to implement on an arduino. The main issue is that some people get hung-up on the issue of programming bluetooth, so they just keep the usb cord. So here is the absolutely most basic things you need to use bluetooth with android and arduino.
This tutorial will go through the bare minimum you need to create an connection between a custom android app you make with MIT App Inventor and the Arduino.
All code and references provided are based on the code from the LittleArm Arduino robot arm.
I provide 15 tutorial links about App Inventor communicating with Arduino Uno. The tutorials start with a Bluetooth connection and they are developed ending with a monitor for 2 potentiometers, leds, buttons and small supervisory using procedure blocks, canvas, etc
Tutorial 1/15: connecting with bluetooth
Tutorial 2/15: Led ON / OFF
Tutorial 3/15: Led ON / OFF – Changing Button Color
Tutorial 4/15: Led ON/OFF – Using a single button on App Inventor
Tutorial 5/15: Slider changes LED intensity
Tutorial 6/15: Joining Slider / Button in App Inventor and Leds Arduino
Tutorial 7/15: Checking Status of an Arduino Pushbutton (button) in App Inventor
Tutorial 8/15: Monitoring 02 Potentiometers
Tutorial 9/15: now monitoring the status of 02 Potentiometers and 01 Pushbutton
Tutorial 10/15: Complete Project – Bt, Pot, Button, Slider, Leds
Tutorial 11/15: 8Leds 8 Buttons – Mode1
Tutorial 12/15: 8Leds 8 Buttons – Mode1: Using Procedure Block
Tutorial 13/15: Small Supervisory using Canvas – Part 1
Tutorial 14/15 : small supervisory using Canvas – Part 2
Tutorial 15/15: two ways to install the HC-05 module on Arduino and communicate to AppInventor
I am trying to use the app inventor with an iPhone and and Arduino. I used code I learned in a workshop for Android phones and it doesn’t work with the iPhone.
A recent post gave this as an answer to the same question, but I don’t understand how to use the answer: “Use ElementsFromString property in the designer rather than the ListData property.”
Are there any tutorials you can suggest to help me use it with the iPhone and Arduino?
Welcome Elene.
The Android users use Bluetooth to communicate with an Arduino . I don’t think an ios version of App Inventor can do that yet. Android users use extensions to accomplish that goal. The ios version of App Inventor currently cannot use extensions.
Some users use the Web component to talk to their arduinos. See Search results for ‘arduino Web ‘ – MIT App Inventor Community.
Is this using App Inventor Blocks?
Ultimately it will depend on the Arduino you are using. At the moment, App Inventor for iOS does not have the BluetoothClient, BluetoothLE (currently an extension), or Serial components implemented, which are common ways to connect to Arduinos. If you have an Arduino Yun (or another Wifi shield), you should be able to use the Web component to communicate with it.
Of the three unavailable connection methods, BluetoothLE is the mostly likely to be implemented in the short term as we are producing new curricula around BluetoothLE and the micro:bit, and we want to ensure that this will be a good experience for both Android and iOS users.
1 Like
Yes. They used the app inventor with the HM-10 Bluetooth module, the Arduino Uno, and an android phone.
Does this mean that the App inventor will work with the HM-10 Bluetooth module, Arduino uno and iPhones in the future?
I would need to see an example project to better assess that.
Introduction: Arduino AND Bluetooth HC-05 Connecting Easily
Hello Every body , This is my first artical on Instructable.com , I’m so happy for that , and I will start by How to connect arduino with bluetooth , I suffered a lot of problems when I try to connect it as the website and instructable artical did , So i decided To share my experience with YouThe bluetooth module I will use today is HC-05 which is so familiar and cheap ,Most tutorial on The website Connect the bluetooth with default Rx and Tx on the arduino Board , I faced a lot of problem and bluetooth didn’t work will .But arduino support something Called Software Serial , which allow You to change any arduino board pin to serial pinhttp://arduino.cc/en/Reference/SoftwareSerialso After reading this article you will be able to:1) Connect arduino Board with PC By Bluetooth , to send and receive data .2)Connect arduino Board with Any android device .so you can send your information , Like Sensors reading , from arduino to PC Or android device , and you can build your Home automation system by bluetooth , and controlling your robot wirelessly
Step 3: Arduino Code
this program below allow us to control LED connected to D13 To blink on/off , by press # 1 from PC Keyboard the LED blink on , and if we press 0 LED blink off !
To send the Control commands from Computer to arduino , Go to the tera term , Run it , and choose Serial , and select the bluetooth Serial from the list as Shown on the picture .
The code below :
// This program shown how to control arduino from PC Via Bluetooth
// Connect …
// arduino>>bluetooth
// D11 >>> Rx
// D10 >>> Tx
//Written By Mohannad Rawashdeh
//for http://www.genotronex.com/
// you will need arduino 1.0.1 or higher to run this sketch
#include
// import the serial library
SoftwareSerial Genotronex(10, 11); // RX, TX
int ledpin=13; // led on D13 will show blink on / off
int BluetoothData; // the data given from Computer
void setup() {
// put your setup code here, to run once:
Genotronex.begin(9600);
Genotronex.println(“Bluetooth On please press 1 or 0 blink LED ..”);
pinMode(ledpin,OUTPUT);
void loop() {
// put your main code here, to run repeatedly:
if (Genotronex.available()){
BluetoothData=Genotronex.read();
if(BluetoothData==’1′){ // if number 1 pressed ….
digitalWrite(ledpin,1);
Genotronex.println(“LED On D13 ON ! “);
if (BluetoothData==’0′){// if number 0 pressed ….
digitalWrite(ledpin,0);
Genotronex.println(“LED On D13 Off ! “);
delay(100);// prepare for next data …
After uploading This sketch go to tera term and press 0 or 1 and see the results
This Video show the results of this code .
Step 5: App Inventor: Create a ListPicker
Create a listpicker so that you can use to find and select the bluetooth devices that are paired with the smartphone.
When the listpicker is open, then a selection should trigger some event. In this case, a Bluetooth connection to the device listed. (Ignore the last three green blocks those are specific “trees” in the forest that you don’t have to have.)
Step 2: Connect Arduino With PC
We now want to send or receive Data between arduino and computer , first we need to make a Communication link to Definition arduino Board to the computer .We will need a software called Tera Term to show the data received or what we want to send through it .You can download Tera Term or any terminal emulator software , you can download Tera term from this link :http://hp.vector.co.jp/authors/VA002416/ttermv14.zipTo make a link between your Arduino and bluetooth , do the following :1) Go to the bluetooth icon , right click and select Add a Device2) Search for new device , Our bluetooth module will appear as HC-05 , and add it3) The pairing code will be 1234 .4)after make a pairing , we can now program the arduino and upload a sketch to send or receive data from Computer.
Step 2: Arduino Code
Some people think that that when you replace the cord with bluetooth that you have to change your code. THEY ARE WRONG. Relax, if your code works with the USB cord than you do not have to change a thing. As I said, bluetooth is basically the same thing as USB in code syntax. The Arduino’s Serial.read is just fine with the same code.
Here is the code that is used with the LittleArm Arduino robot Arm.
//////Other Intiations here
void setup(){ Serial.begin(9600); baseServo.attach(5); // attaches the servo on pin 5 to the servo object shoulderServo.attach(4); elbowServo.attach(3); gripperServo.attach(2); Serial.setTimeout(50); //ensures the the arduino does not read serial for too long Serial.println(“started”); baseServo.write(90); //intial positions of servos shoulderServo.write(100); elbowServo.write(110); ready = 0; }//primary arduino loopvoid loop() { if (Serial.available()){ ready = 1; desiredAngle.base = Serial.parseInt(); desiredAngle.shoulder = Serial.parseInt(); desiredAngle.elbow = Serial.parseInt(); desiredGrip = Serial.parseInt(); desiredDelay = Serial.parseInt();
if(Serial.read() == ‘\n’){ // if the last byte is ‘d’ then stop reading and execute command ‘d’ stands for ‘done’ Serial.flush(); //clear all other commands piled in the buffer Serial.print(‘d’); //send completion of the command } }
This snippet of code is the read and return code. Notice that it reads information from the Serial port just as if there were a usb cable connected. There is no need to initiate ports for the Bluetooth, they are naturally activated.
Step 1: The Bluetooth Module
The most common bluetooth module today is the HC-06 or HC-05. It costs about 7-10 dollars online. Look at the image below to see how to hook it to the Arduino.
That is pretty easy right? Just four jumper wires and you now have wireless serial connectivity to your arduino. Now, if you have a program where you have been sending commands to the arduino with the Serial Monitor you can now do that wirelessly with a bluetooth device. (Note: You can upload programs to the arduino via bluetooth, but that is significantly more complicated than what we want to achieve here.)
Overview
For this tutorial we have two examples. The first example is controlling a simple LED and the second one is controlling a Stepper Motor using smartphone. In my previous tutorial we already learned how to make the Bluetooth communication between the Arduino Board and the Smartphone using the HC-05 Bluetooth module and explained the Arduino code needed for the first example.
Step 5: Receiving Data From Arduino
The last arduino Sketch that i wrote , used to send commands from PC Or android device to android , Now in this program i will use arduino to Calculate the time since the start of the program in second , and send it Via bluetooth to any pairing device .the code below// This program shown how to control arduino from PC Via Bluetooth// Connect …// arduino>>bluetooth// D11 >>> Rx// D10 >>> Tx//Written By Mohannad Rawashdeh//for http://www.genotronex.com/// you will need arduino 1.0.1 or higher to run this sketch#include
// import the serial librarySoftwareSerial Genotronex(10, 11); // RX, TXint ledpin=13; // led on D13 will show blink on / offlong previousMillis = 0; // will store last time LED was updated// the follow variables is a long because the time, measured in miliseconds,// will quickly become a bigger number than can be stored in an int.long interval = 1000; // interval at which to blink (milliseconds)int ledState = LOW; // ledState used to set the LEDlong Counter=0; // counter will increase every 1 secondvoid setup() {// put your setup code here, to run once:Genotronex.begin(9600);Genotronex.println(“Bluetooth On please wait….”);pinMode(ledpin,OUTPUT);}void loop() {// put your main code here, to run repeatedly:unsigned long currentMillis = millis();if(currentMillis – previousMillis > interval) {// save the last time you blinked the LEDpreviousMillis = currentMillis;Counter+=1;Genotronex.println(Counter);// if the LED is off turn it on and vice-versa:if (ledState == LOW)ledState = HIGH;elseledState = LOW;// set the LED with the ledState of the variable:digitalWrite(ledpin, ledState);}}at the end , You can visit the orginal artical in arabic language on my websitehttp://www.genotronex.com/Hope my first artical here is useful to you , thank you for your time ,
Hello friends,
In this topic I am going to show some examples of Arduino UNO with the Bluetooth HC-06 module.
I will start with simple examples and later I will put some more complicated codes.
Hello friends,
In this topic I am going to show some examples of Arduino UNO with the Bluetooth HC-06 module.
I will start with simple examples and later I will put some more complicated codes.
1.- App sends simple char. Arduino on-off LED12 and LED13.
p9A0i_bluetooth_caracter.aia (2.4 KB)
// Juan A. Villalpando // http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm #define Pin12 12 #define Pin13 13 char caracter; void setup() { Serial.begin(9600); pinMode(Pin12, OUTPUT); pinMode(Pin13, OUTPUT); } void loop() { if(Serial.available()) { caracter = Serial.read(); if(caracter == 'a'){ digitalWrite(Pin12, HIGH);} if(caracter == 'b'){ digitalWrite(Pin12, LOW);} if(caracter == 'c'){ digitalWrite(Pin13, HIGH);} if(caracter == 'd'){ digitalWrite(Pin13, LOW);} } }
Instead of using LEDs you can put Relays.
2A.- App sends text. Arduino on-off LED12 and LED13. Serial Monitor. With asterisk.
p9A0i_bluetooth_texto.aia (2.6 KB)
// Juan A. Villalpando // http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm #define Pin12 12 #define Pin13 13 char caracter; String palabra; void setup() { Serial.begin(9600); pinMode(Pin12, OUTPUT); pinMode(Pin13, OUTPUT); } void loop() { if(Serial.available()) { caracter = Serial.read(); palabra = palabra + caracter; if(caracter == '*') { palabra = palabra.substring(0, palabra.length() - 1); // Delete last char * Serial.println(palabra); if (palabra == "on12"){digitalWrite(Pin12, HIGH);} if (palabra == "off12"){digitalWrite(Pin12, LOW);} if (palabra == "on13"){digitalWrite(Pin13, HIGH);} if (palabra == "off13"){digitalWrite(Pin13, LOW);} palabra = ""; delay(100); } } }
oooooooooooooooo0000000000000000ooooooooooooooooooo
2B.- App sends text. Arduino on-off LED12 and LED13. Serial Monitor. Without asterisk.
p9A0i_bluetooth_texto_2.aia (2.6 KB)
// Juan A. Villalpando // http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm #define Pin12 12 #define Pin13 13 char caracter; String palabra; void setup() { Serial.begin(9600); pinMode(Pin12, OUTPUT); pinMode(Pin13, OUTPUT); } void loop() { if(Serial.available()) { caracter = Serial.read(); palabra = palabra + caracter; Serial.println(palabra); if (palabra.indexOf("on12")>= 0){digitalWrite(Pin12, HIGH); palabra = "";} if (palabra.indexOf("off12")>= 0){digitalWrite(Pin12, LOW); palabra = "";} if (palabra.indexOf("on13")>= 0){digitalWrite(Pin13, HIGH); palabra = "";} if (palabra.indexOf("off13")>= 0){digitalWrite(Pin13, LOW); palabra = "";} delay(100); } }
3.- App sends several information at the same time.
In this example we will use the same App as in the previous example.
Suppose we want to send two information at the same time, for example we want to turn on LED12 and turn off LED13.
We write in the TextBox: on12, off13 [the asterisk will be added automatically at the end of this text]
The Arduino code will check if the text sent contains the string: on12, off12, on13, off13
To check if a substring is in a text we use indexOf: if(palabra.indexOf(“on12”)>= 0)
We can also put the text in another order: off13, on12
// Juan A. Villalpando // http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm #define Pin12 12 #define Pin13 13 char caracter; String palabra; void setup() { Serial.begin(9600); pinMode(Pin12, OUTPUT); pinMode(Pin13, OUTPUT); } void loop() { if(Serial.available()) { caracter = Serial.read(); palabra = palabra + caracter; if(caracter == '*') { palabra = palabra.substring(0, palabra.length() - 1); // Delete last char * Serial.println(palabra); if(palabra.indexOf("on12")>= 0){digitalWrite(Pin12, HIGH);} if(palabra.indexOf("off12")>= 0){digitalWrite(Pin12, LOW);} if(palabra.indexOf("on13")>= 0){digitalWrite(Pin13, HIGH);} if(palabra.indexOf("off13")>= 0){digitalWrite(Pin13, LOW);} palabra = ""; delay(100); } } }
4.- App sends three values separated by comma. Arduino receives them and separates them.
In this example we will use the same App as in the previous example.
We assume that the App wants to send these numbers separated by commas to the Arduino: 126,3,58
An asterisk will be added indicating end of message. [126,3,58*]
In this case it is necessary to indicate the end of the message (example with asterisk) since we can send any number.
Arduino will receive that text and separate it by the comma.
Check Serial Monitor.
// Juan A. Villalpando // http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm char caracter; String palabra; String red; String green; String blue; int ind1; int ind2; int ind3; void setup() { Serial.begin(9600); } void loop() { if(Serial.available()) { caracter = Serial.read(); palabra = palabra + caracter; if(caracter == '*') { palabra = palabra.substring(0, palabra.length() - 1); // Delete last char * Serial.println(palabra); ind1 = palabra.indexOf(','); red = palabra.substring(0, ind1); ind2 = palabra.indexOf(',', ind1+1 ); green = palabra.substring(ind1+1, ind2); ind3 = palabra.indexOf(',', ind2+1 ); blue = palabra.substring(ind2+1); Serial.print("red = "); Serial.println(red); Serial.print("green = "); Serial.println(green); Serial.print("blue = "); Serial.println(blue); Serial.println(); palabra = ""; delay(10); } } }
ooooooooooooooo000000o000000oooooooooooooooAnother way to split the data in with this getValue function:
Serial.println(palabra); red = getValue(palabra,',',0); green = getValue(palabra,',',1); blue = getValue(palabra,',',2); (...) ///////////////// Function Split by char //////////////// String getValue(String data, char separator, int index) { int found = 0; int strIndex[] = {0, -1}; int maxIndex = data.length()-1; for(int i=0; i<=maxIndex && found<=index; i++){ if(data.charAt(i)==separator || i==maxIndex){ found++; strIndex[0] = strIndex[1]+1; strIndex[1] = (i == maxIndex) ? i+1 : i; } } return found>index ? data.substring(strIndex[0], strIndex[1]) : ""; }
5.- App requests temperature and humidity to the Arduino. The Arduino sends values.
p9A0i_bluetooth_temperatura.aia (3.3 KB)
When Click in tempe_humidity Button, App sends the character “D”.Arduino concatenates the temperature and humidity Strings separated by a comma:37,80
App ReceiveText 37,80 converts it to a list and separates the values.
Note: the DelimiterByte must have the value 10. [10 is ASCII New Line, LF. Arduino \n]
In this Arduino code I do not use the sensor or the I2C LCD to simplify its content.Here you can see the code with the sensor and the I2C LCD
// Juan A. Villalpando // http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm char caracter; int temperature = 0; int humidity = 0; String tempera_humidity; void setup() { Serial.begin(9600); } void loop() { temperature = random(20,40); humidity = random(50,95); delay(500); if(Serial.available()) { caracter = Serial.read(); if(caracter == 'T'){Serial.println(temperature);} if(caracter == 'H'){Serial.println(humidity);} if(caracter == 'D'){ tempera_humidity = (String) temperature + "," + (String) humidity; Serial.println(tempera_humidity); } } }
6.- App checks status 2 PushButtons.
p9A0i_bluetooth_pulsadores.aia (3.4 KB)
// Juan A. Villalpando // http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm char caracter; #define push7 7 // PushButton 7. #define push8 8 // PushButton 8. String status_push7; String status_push8; String status; void setup() { Serial.begin(9600); pinMode(push7, INPUT); pinMode(push8, INPUT); } void loop() { delay(50); if(Serial.available()) { caracter = Serial.read(); if (digitalRead(push7) == HIGH) {status_push7 = "Push7 ON";} else {status_push7 = "Push7 OFF";} if (digitalRead(push8) == HIGH) {status_push8 = "Push8 ON";} else {status_push8 = "Push8 OFF";} status = status_push7 + "," + status_push8; if(caracter == '7'){Serial.println(status_push7);} if(caracter == '8'){Serial.println(status_push8);} if(caracter == 'D'){Serial.println(status);} } }
7.- App gets the value of two potentiometers.
p9A0i_bluetooth_potenciometro.aia (3.3 KB)
// Juan A. Villalpando // http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm int value_pot0; int value_pot1; String value; void setup() { Serial.begin(9600); } void loop() { value_pot0 = analogRead(A0); value_pot1 = analogRead(A1); value = (String) value_pot0 + "," + (String) value_pot1; Serial.println(value); delay(200); // It should be slower than the Clock Interval. }
8.- App receives data from Arduino. Clock.Interval. Arduino delay. Buffer.
p9A0i_bluetooth_aleatorio.aia (2.9 KB)
a)Clock.Interval = 300Arduino delay = 200
App cannot process the information because the Clock “is slower” than the Arduino.The buffer is being filled, values that arrive and have not yet been processed.
When the Buffer reaches a certain value, for example 120, you remove power to the Arduino. What happens with buffer?
b) Change Clock.IntervalClock.Interval = 100Arduino delay = 200
Therefore, Clock.Interval < delay Arduino
// Juan A. Villalpando // http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm int aleatorio; void setup() { Serial.begin(9600); } void loop() { aleatorio = random(0,100); Serial.println(aleatorio); delay(200); // Clock.Interval < delay Arduino }
9.- A potentiometer in Arduino sends values to the App. Dynamic graph. Shift left.
p9A0i_bluetooth_dinamico.aia (8.1 KB)
// Juan A. Villalpando // http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm int value_pot0; void setup() { Serial.begin(9600); } void loop() { value_pot0 = analogRead(A0); Serial.println(value_pot0); delay(100); // It should be slower than the Clock Interval. }
10.- Three LEDS on-off according to a sequence saved in a file.
p9A0i_bluetooth_secuencia3LED.aia (5.0 KB)
In file rutina2.csv this content:
Levels of: LED11 – LED12 – LED13 – Time in seconds of this combination.
App sends 1-1-0-2*
Arduino set LEDs on, on, off
and wait 2 seconds.
then Arduino sends to App “send_me_next”
When App receives “send_me_next”
App “send_next” combination: 1-0-0-2*
// Juan A. Villalpando // http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm char caracter; String palabra; int LED11 = 11; int LED12 = 12; int LED13 = 13; int valor11; int valor12; int valor13; int Tiempo = 1000000; unsigned long currentMillis; unsigned long previousMillis = currentMillis; int k1; int k2; int k3; int k4; void setup() { Serial.begin(9600); pinMode(LED11, OUTPUT); pinMode(LED12, OUTPUT); pinMode(LED13, OUTPUT); } void loop() { if(Serial.available()) { caracter = Serial.read(); palabra = palabra + caracter; Serial.println(palabra); if(caracter == '*') { palabra = palabra.substring(0, palabra.length() - 1); // Delete last char * k1 = palabra.indexOf('-'); valor11 = palabra.substring(0, k1).toInt(); k2 = palabra.indexOf('-', k1+1); valor12 = palabra.substring(k1+1, k2).toInt(); k3 = palabra.indexOf('-', k2+1); valor13 = palabra.substring(k2+1, k3).toInt(); k4 = palabra.indexOf('-', k3+1); Tiempo = 1000 * palabra.substring(k3+1, k4).toInt(); palabra = ""; digitalWrite(LED11, valor11); digitalWrite(LED12, valor12); digitalWrite(LED13, valor13); } previousMillis = currentMillis; } // =>Fin del available tiempo(); } // =>Fin del loop void tiempo() { currentMillis = millis(); if (currentMillis >= (previousMillis + Tiempo)) { previousMillis = currentMillis; Serial.println("send_me_next"); // Envíame el siguiente. } }
11.- Virtual Screen with two VerticalArrangement.
p9A0i_bluetooth_virtual.aia (4.1 KB)
// Juan A. Villalpando // http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm #define LED13 13 byte StatusLED13; void setup() { Serial.begin(9600); pinMode(LED13, OUTPUT); } void loop() { if(Serial.available()) { int dato = Serial.read(); if(dato == 153){digitalWrite(LED13, HIGH);} if(dato == 168){digitalWrite(LED13, LOW);} if(dato == 221){ StatusLED13 = digitalRead(LED13); Serial.print(StatusLED13); // Sends 48 or 49 } } }
12.- App moves two Servos by Sliders.
p9A0i_bluetooth_servos.aia (3.2 KB)
// Juan A. Villalpando // http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm #include
Servo servo3; Servo servo5; const int pwmPin3 = 3; // Servo3 pin3 PWM const int pwmPin5 = 5; // Servo5 pin5 PWM char caracter; String palabra; String angulo_1; String angulo_2; int k1; void setup() { Serial.begin(9600); pinMode (pwmPin3, OUTPUT); pinMode (pwmPin5, OUTPUT); servo3.attach(pwmPin3); servo5.attach(pwmPin5); } void loop() { if(Serial.available()) { caracter = Serial.read(); palabra = palabra + caracter; if (caracter == '*') { Serial.println(palabra); palabra = palabra.substring(0, palabra.length() - 1); // Delete last char * k1 = palabra.indexOf(','); angulo_1 = palabra.substring(0, k1); angulo_2 = palabra.substring(k1+1, -1); servo3.write(angulo_1.toInt()); servo5.write(angulo_2.toInt()); palabra = ""; } } } // => Fin Loop
Note: if you use more than 2 servos you will need to power them with an external power source. Video: Each servo needs about 400 mA.
13.- App moves a Stepper motor.
p9A0i_bluetooth_pasopaso.aia (3.1 KB)
In a servo you order:set 34ºset 12ºset 96º, it is not necessary to know the previous position.
In a stepper motor, you order:set 20 step clockwiseset 80 step anticlockwise, it is necessary to know the previous position to place it in a new position.
I will use: Stepper motor 28BYJ-48 ULN2003
It is convenient to power this motor through an external source, in this experimental example I will feed it with the 5 V of Arduino.
// Juan A. Villalpando // http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm #include
#define STEPS 64 // Secuencia 1-3-2-4 Stepper motor(STEPS, 8, 10, 9, 11); char caracter; void setup() { Serial.begin(9600); motor.setSpeed(200); } void loop() { if( Serial.available() ) { caracter = Serial.read(); Serial.print(caracter); if(caracter == '1'){motor.step(60);} if(caracter == '2'){motor.step(-60);} if(caracter == '3'){motor.step(510);} if(caracter == '4'){motor.step(-510);} if(caracter == '5'){motor.step(1020);} if(caracter == '6'){motor.step(-1020);} if(caracter == '7'){motor.step(2040);} if(caracter == '8'){motor.step(-2040);} if(caracter == 'A'){motor.step(100);} if(caracter == 'B'){motor.step(-100);} } }
14. Where do we connect the Bluetooth module in Arduino UNO?
p9A0i_bluetooth_Serial.aia (2.9 KB)
Terminals 0 (RX) and 1 (TX) are used by Arduino as the default Serial RX/TX. Use it to upload sketch, Serial Monitor, Bluetooth. So when we are going to upload a sketch for Bluetooth we must disconnect the RX cable from the Arduino.
We can use other terminals to connect the Bluetooth module, for example 10 and 11, in this case we need the “SoftwareSerial” library. Now when we upload a sketch it is not necessary to remove the RX cable.
– CODE FOR MODULE IN default RX/TX pin 0 and 1 of Arduino.
// Juan A. Villalpando // http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm #define Pin13 13 char caracter; void setup() { Serial.begin(9600); pinMode(Pin13, OUTPUT); } void loop() { if(Serial.available()) { caracter = Serial.read(); if(caracter == 'a'){ digitalWrite(Pin13, HIGH);} if(caracter == 'b'){ digitalWrite(Pin13, LOW);} Serial.println(caracter); } }
– CODE FOR MODULE IN pin10 and pin11 with SoftwareSerial library.
// Juan A. Villalpando // http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm #include
SoftwareSerial I2CBT(10,11); // El TX del módulo BT va al pin10 del Arduino // El RX del módulo BT va al pin11 del Arduino #define Pin13 13 char caracter; void setup() { I2CBT.begin(9600); // To read and write Bluetooth Serial.begin(9600); // To print in Serial Monitor pinMode(Pin13, OUTPUT); } void loop() { if(I2CBT.available()) { caracter = I2CBT.read(); if(caracter == 'a'){ digitalWrite(Pin13, HIGH);} if(caracter == 'b'){ digitalWrite(Pin13, LOW);} Serial.println(caracter); // Serial Monitor I2CBT.println(caracter); // return Bluetooth // I2CBT.write(caracter); // return Bluetooth } }
15.- Send text file from Server to Client and from Client to Server. Message Mobile to Mobile by Bluetooth.
p9A0i_BT_Server_File.aia (3.3 KB)
p9A0i_BT_Client_File.aia (3.4 KB)
– Blocks Server.
– Blocks Client.
16.- Send Image file from Server to Client and from Client to Server.
This example is only experimental, there are problems with file size, clock interval, conversion … Try.
p9A0i_BT_Server_Image.aia (41.9 KB)
p9A0i_BT_Client_Image.aia (55.6 KB)
– Blocks Server.
– Blocks Client.
17.- Write number with KeyPad in Arduino and sends to App by Bluetooth. LCD I2C.
p9A0i_bluetooth_teclado.aia (1.8 MB)
// Juan A. Villalpando // http://kio4.com/appinventor/9BA_bluetooth_teclado_LCD.htm #include
#include
// Pantalla LCD #includeLiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); String clave = ""; String clave_old = ""; const byte ROWS = 4; const byte COLS = 4; char keys[ROWS][COLS] = { {'1', '2', '3', 'A'}, {'4', '5', '6', 'B'}, {'7', '8', '9', 'C'}, {'*', '0', '#', 'D'} }; byte rowPins[ROWS] = {0, 1, 2, 3}; byte colPins[COLS] = {4, 5, 6, 7}; int i2caddress = 0x20; // Module I2C Keyboard. Keypad_I2C kpd = Keypad_I2C( makeKeymap(keys), rowPins, colPins, ROWS, COLS, i2caddress); void setup() { Serial.begin(9600); kpd.begin(); lcd.begin(16,2);// Columnas y filas de LCD. } void loop() { char key = kpd.getKey(); clave = clave + (String) key; if (key == '#') { clave = clave.substring(0, clave.length() - 1); // Delete last char # lcd.clear(); lcd.setCursor(0,0); lcd.print(clave); lcd.setCursor(0,1); lcd.print(clave_old); clave_old = clave; Serial.println(clave); clave = ""; } delay(100); }
18.- Poor man’s circuit.
// Juan A. Villalpando // http://kio4.com/appinventor/9BA_bluetooth_teclado_LCD.htm char key = 0; String clave = ""; void setup() { Serial.begin(9600); } void loop() { if (Serial.available() > 0) { key = Serial.read(); clave = clave + key; if (key == '#') { Serial.print(clave); // Example sends: 123# clave = ""; } } }
19.- Arduino Interrupts sends data to App.
p9A01_bluetooth_interrupt.aia (2.3 KB)
Arduino UNO has two pins for interruptions (pin2 and pin3). ESP32 has 32 interrupt pins).
Arduino interrupts: https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
When pin2 RISING causes an interrupt and calls function on_13
When pin3 RISING causes an interrupt and calls function off_13
// Juan A. Villalpando // http://kio4.com/appinventor/9A0_Resumen_Bluetooth.htm #define LED13 13 void setup() { Serial.begin(9600); attachInterrupt(digitalPinToInterrupt(2), on_13, RISING); attachInterrupt(digitalPinToInterrupt(3), off_13, RISING); pinMode(LED13, OUTPUT); } void loop() { // } // Interruptions ISR. void on_13() // When pin2 RISING... { digitalWrite(LED13, HIGH); Serial.print(1); } void off_13() // When pin3 RISING... { digitalWrite(LED13, LOW); Serial.print(0); }
In this Arduino Tutorial we will learn how to build custom Android applications for controlling Arduino using the MIT App Inventor online application. You can watch the following video or read the written tutorial below.
Step 6: Send Data to Arduino
Assuming that the connection is successful the light on the HC-06 bluetooth module will become solid. That is good, your device can now talk to the arduino. So to send something to the arduino, just select the type of data you want to send. Is it numbers, letters, bits, bytes, etc. Then select the .SendXXXX operation from the bluetooth menu in AppInventor and stick your data in. In this case for the LittleArm we use .SendText because we have text characters, in this case commas, in the data. If it was numerical we would use SendNumbers and so on.
You may notice that the function that the send command is inside of, is linked to one of the slider bars in the app. This means that the the Send is linked to an “event.” i.e. when the slider is moved it automatically calls this function. Not to bad, right?
MIT App Inventor
From the MIT App Inventor website we need to log in into the online building application by clicking the “Create apps!” button. In order to log in we need to have a Gmail account. Once we are logged in now we can create our first project. Here’s how the design window looks and now we can start building our application.
But before do that, we can connect our smartphone to this project so that we can see how the app is taking shape directly on our smartphone in real time. In order to do that first we have to download the MIT AI2 Companion app from the Play Store and install it on our smartphone. Then from the Connect menu from the online editor we will select AI Companion and a barcode will appear which we just need to scan it or insert the code into the smartphone app and the connection between the online editor and the smartphone app will be established.
So now for example, if we insert a button in the screen of the online editor, the button will appear in real time on the smartphone as well. Similar to this, if you don’t want to use your smartphone while building the app, you can install the Android Emulator on your computer and use in the same way. You can find more details how to set up the Emulator on their website.
Step 8: Enjoy Your App
And that is all there is to it. You now have an app, that will connect with a bluetooth device and then send some kind of data to the Arduino and receive some kind of data via serial communications. Now you can control almost any arduino project with your android smartphone. Enjoy.
You can see a demo of the app that all of this code was taken from in this video.
Trong Hướng dẫn Arduino này, chúng ta sẽ tìm hiểu cách tạo các ứng dụng Android để kiểm soát Arduino bằng ứng dụng trực tuyến MIT App Inventor. Bạn có thể xem video sau hoặc đọc hướng dẫn dưới đây.
Tổng quan
Đối với hướng dẫn này, chúng tôi có hai ví dụ. Ví dụ đầu tiên là điều khiển một đèn LED đơn giản và cái thứ hai là điều khiển động cơ bước sử dụng điện thoại thông minh.
Code Arduino
Dưới đây là tổng quan nhanh về code. Thông qua cổng nối tiếp, nhận được dữ liệu đến từ điện thoại và lưu trữ nó trong biến ‘trạng thái’. Nếu nhận được ký tự ‘0’ được gửi từ điện thoại khi nhấn nút ‘LED: TẮT’, chúng tôi sẽ tắt đèn LED và gửi lại cho điện thoại String Đèn LED: TẮT. Mặt khác, nếu chúng tôi nhận được ký tự ‘1’, chúng tôi sẽ bật đèn LED và gửi lại String Đèn LED: ON.
#define ledPin 7 int state = 0; void setup() { pinMode(ledPin, OUTPUT); digitalWrite(ledPin, LOW); Serial.begin(38400); // Default communication rate of the Bluetooth module } void loop() { if(Serial.available() > 0){ // Checks whether data is comming from the serial port state = Serial.read(); // Reads the data from the serial port } if (state == ‘0’) { digitalWrite(ledPin, LOW); // Turn LED OFF Serial.println(“LED: OFF”); // Send back, to the phone, the String “LED: ON” state = 0; } else if (state == ‘1’) { digitalWrite(ledPin, HIGH); Serial.println(“LED: ON”);; state = 0; } }
Vì vậy, bây giờ chúng ta cần xây dựng ứng dụng Android tùy chỉnh của mình, nó sẽ gửi các ký tự ‘0’ và ‘1’ khi nhấn một nút cụ thể, cũng như, nhận các Chuỗi đến từ Arduino.
Nhà phát minh ứng dụng MIT
Từ trang web MIT App Inventor, cần đăng nhập vào ứng dụng xây dựng trực tuyến bằng cách nhấp vào nút Tạo ứng dụng! Để đăng nhập, cần phải có tài khoản Gmail. Khi đã đăng nhập, bạn có thể tạo dự án đầu tiên của mình. Đây là cửa sổ thiết kế và bây giờ chúng ta có thể bắt đầu xây dựng ứng dụng của mình.
Cửa sổ thiết kế ứng dụng MIT
Nhưng trước khi làm điều đó, chúng ta cần kết nối điện thoại của mình với dự án này để có thể xem ứng dụng đang hình thành trực tiếp trên điện thoại của chúng ta trong thời gian thực như thế nào. Để thực hiện điều đó trước tiên, phải tải xuống ứng dụng MIT AI2 Companion từ Play Store và cài đặt nó trên điện thoại. Sau đó, từ menu Connect từ trình chỉnh sửa trực tuyến, chọn AI Companion và mã vạch sẽ xuất hiện, sau đó chỉ cần quét hoặc chèn mã vào ứng dụng điện thoại và kết nối giữa trình chỉnh sửa trực tuyến và ứng dụng điện thoại sẽ được thiết lập.
Phát triển ứng dụng Mit và kết nối điện thoại
Bây giờ, ví dụ, nếu chúng ta chèn một nút trong màn hình của trình chỉnh sửa trực tuyến, nút này cũng sẽ xuất hiện trên điện thoại. Tương tự như vậy, nếu bạn không muốn sử dụng điện thoại của mình trong khi xây dựng ứng dụng, bạn có thể cài đặt Trình giả lập Android trên máy tính và sử dụng theo cách tương tự. Bạn có thể tìm thêm chi tiết cách thiết lập Trình mô phỏng trên trang web của họ.
Xây dựng ứng dụng – Ví dụ 1
Bây giờ bạn đã sẵn sàng để xây dựng ví dụ đầu tiên. Chúng ta sẽ bắt đầu với bố cục của chương trình. Đầu tiên, chúng ta sẽ thêm một số tính năng ngang từ bảng bố trí và đặt các thuộc tính của chúng như chiều cao, chiều rộng và căn chỉnh để phù hợp với giao diện mong muốn của chương trình. Sau đó, từ Bảng màu UserInterface, chúng ta sẽ thêm ListPicker và đính kèm hình ảnh vào đó. ListPicker sẽ được sử dụng để chọn thiết bị Bluetooth mà điện thoại của chúng tôi sẽ kết nối.
Xây dựng ứng dụng Android – Ví dụ 01
Tiếp theo, thêm một tính năng ngang khác, trong đó đặt tên cho nó. Nhãn này sẽ cho biết điện thoại có được kết nối hay không với mô-đun Bluetooth và đó là lý do tại sao chúng ta sẽ đặt tên ban đầu của nhãn này thành Không được kết nối. Nhãn tiếp theo sẽ được sử dụng để hiển thị trạng thái của đèn LED, cho dù đã tắt hay bật. Trạng thái ban đầu sẽ là LED: OFF. Tiếp theo, thêm hai nút, ‘Bật’ và ‘Tắt’ để điều khiển đèn LED. Tại thời điểm này, tốt hơn là đổi tên các thành phần để chúng ta có thể dễ dàng nhận ra và sử dụng chúng hơn trong trình chỉnh sửa Blocks sau này. Những gì còn lại bây giờ là thêm BluetoothClient, một thành phần không nhìn thấy cũng như đồng hồ sẽ được sử dụng để chỉ báo thời gian thực về trạng thái kết nối.
Trình chỉnh sửa khối
Bây giờ trong trình chỉnh sửa Blocks, chúng ta đã sẵn sàng hoàn thiện cho chương trình của mình. Từ phía bên trái, chúng ta có tất cả các khối và chức năng liên quan đến các thành phần được thêm vào trước đó.
Khối ứng dụng Android – Ví dụ 01
Chúng ta sẽ bắt đầu với Danh sách BluetoothList ListPicker. Từ đó trước tiên, chúng ta sẽ thêm khối ‘BeforePicking’ và đính kèm với khối ‘thiết lập các thành phần Bluetooth’. Sau đó, từ các khối BluetoothClient, thêm khối ‘ BluetoothClient AddressesAndNames’. Khối này sẽ thiết lập một danh sách các thiết bị Bluetooth đã được kết nối với điện thoại để khi nhấp vào nút ListPicker, nút kết nối, danh sách tất cả các thiết bị được ghép nối sẽ hiển thị.
Tiếp theo, chúng ta phải đặt những gì sẽ xảy ra sau khi chúng ta sẽ chọn hoặc chọn mô-đun Bluetooth cụ thể của mình. Từ khối BluetoothClient, thêm khối ‘call BluetoothClient .Connect address’. và thêm khối BluetoothList Selection’ vào đó, có nghĩa là điện thoại sẽ kết nối với địa chỉ Bluetooth đã chọn trước đó.
Tiếp theo từ các khối Đồng hồ, chúng tôi sẽ thêm khối “.Timer “. Trong khối này, chúng ta sẽ đưa ra dấu hiệu thời gian thực cho dù điện thoại có được kết nối hay không với mô-đun Bluetooth bằng cách sử dụng khối “set Text” có tên là “Connected”.
Khối đồng hồ
Tiếp theo chúng ta cần cung cấp cho cuộc sống cho hai nút. Vì vậy, khi nhấp vào nút TurnOn_Button, chúng tôi sẽ sử dụng chức năng máy khách Bluetooth, Send Send1ByteNumber, để gửi một số đến mô-đun Bluetooth Arduino. Trong trường hợp của chúng tôi, đó là số 49 tương ứng với ký tự ‘1’ theo bảng ASCII và nó sẽ bật đèn LED. Ngay sau đó, chúng tôi sẽ sử dụng chức năng BluetoothClient của Bluetooth GetText để nhận Chuỗi đến được gửi lại từ Arduino tới điện thoại. Chuỗi này được đặt thành Nhãn LED LED_Status.
Khối nút
Quy trình tương tự cũng diễn ra đối với “TurnOff_Button”, trong đó số gửi sẽ được thay đổi thành 48 tương ứng với ký tự ‘0’. Những gì còn lại bây giờ là tải xuống và cài đặt chương trình trên điện thoại. Chúng ta có thể tải từ menu của “Build” bằng cách lưu nó vào máy tính và sau đó chuyển vào điện thoại hoặc quét mã QR để tải xuống chương trình trực tuyến.
Đây là tệp tải xuống của dự án MIT App Inventor ở trên:
Ví dụ điều khiển động cơ bước
Bây giờ hãy xem ví dụ thứ hai, điều khiển động cơ bước. Ở đầu màn hình, chúng ta có các thành phần tương tự cho kết nối Bluetooth như ví dụ trước. Tiếp theo chúng ta có một thành phần Canvas được sử dụng để vẽ và chèn hình ảnh. Tôi đã chèn hai hình ảnh trước đây tôi đã vẽ. Cái đầu tiên là hình ảnh của một thước đo sẽ được cố định tại chỗ và cái thứ hai là hình ảnh của một con trỏ sẽ quay. Tiếp theo, chúng ta có nút Kiểm tra để chuyển đổi giữa Chế độ thủ công và Tự động hoặc chế độ chạy liên tục và một nút để thay đổi hướng xoay. Chúng ta còn có một thanh trượt để thay đổi tốc độ quay của động cơ bước.
Dưới đây là các khối và code Arduino đằng sau ví dụ này. Trong trình chỉnh sửa Blocks một lần nữa, chúng ta có các khối tương tự cho kết nối Bluetooth như ví dụ trước.
Ví dụ điều khiển động cơ bước Khối 01
Bây giờ để xoay con trỏ, chúng tôi sử dụng chức năng “.PointInDirection”, trong đó xoay con trỏ từ vị trí 0 ° theo trục X và Y nơi Canvas đã được chạm vào. Đồng thời, đặt tiêu đề ImageSprite thành tên con trỏ. Sau đó, gọi thủ tục tùy chỉnh được thực hiện hoặc chức năng delay 10m giây.
Cuối cùng, gửi giá trị tiêu đề dưới dạng Văn bản tới Arduino bằng chức năng Bluetooth SendText của Bluetooth. Giá trị này sẽ được chấp nhận bởi Arduino và nó sẽ xoay động cơ bước tương ứng.
Tiếp theo là khối CheckBox. Nếu CheckBox được kiểm tra, chúng tôi sẽ gửi văn bản (Auto Auto) đến Arduino để kích hoạt động cơ bước để xoay liên tục. Mặc dù đang ở chế độ này nếu nhấn nút Reverse, chúng ta sẽ gửi văn bản Nghịch đảo Reverse tới Arduino để thay đổi hướng quay của động cơ. Ngoài ra, trong khi ở chế độ này, chúng ta có thể thay đổi tốc độ quay. Nếu chúng ta thay đổi vị trí của thanh trượt, giá trị hiện tại của vị trí thanh trượt sẽ được gửi đến Arduino, nó sẽ thay đổi tốc độ quay của động cơ bước. Nếu chúng ta bỏ chọn CheckBox, chúng tôi sẽ quay lại chế độ thủ công.
Đây là tệp tải xuống của dự án MIT App Inventor ở trên, cũng như hai hình ảnh được sử dụng trong dự án:
Dịch từ: https://howtomechatronics.com/tutorials/arduino/how-to-build-custom-android-app-for-your-arduino-project-using-mit-app-inventor/
Đây là code Arduino của ví dụ thứ hai:
// Defining variables const int stepPin = 7; const int dirPin = 6; String state = “”; int currentHeading=0; int currentAngle=0; int lastAngle=0; int angle=0; int rotate=0; int runContinuously=0; String mode = “Manual”; boolean dirRotation = HIGH; int rotSpeed = 1500; void setup() { // Sets the two pins as Outputs pinMode(stepPin,OUTPUT); pinMode(dirPin,OUTPUT); Serial.begin(38400); // Default communication rate of the Bluetooth module } void loop() { delayMicroseconds(1); if(Serial.available() > 0){ // Checks whether data is comming from the serial port state = Serial.readString(); // Reads the data from the serial port } // When Auto Button is pressed if (mode == “Auto”) { if (state == “Reverse”) { delay(10); if (dirRotation == HIGH) { dirRotation = LOW; } else { dirRotation = HIGH; } digitalWrite(dirPin,dirRotation); delay(10); state = “”; } rotSpeed = state.toInt(); if (rotSpeed >= 300 && rotSpeed <= 3000) { digitalWrite(stepPin,HIGH); delayMicroseconds(rotSpeed); digitalWrite(stepPin,LOW); delayMicroseconds(rotSpeed); } else { digitalWrite(stepPin,HIGH); delayMicroseconds(1500); digitalWrite(stepPin,LOW); delayMicroseconds(1500); } if (state == “Manual”){ mode = state; } } // When Program is in Manual mode else if (mode == “Manual”){ currentHeading = state.toInt(); //Serial.println(angle); //Serial.println(state); if (currentHeading < 0 ){ currentHeading = 360+currentHeading; } currentAngle = map(currentHeading,0,359,0,200); digitalWrite(dirPin,HIGH); // Enables the motor to move in a particular direction // Makes 200 pulses for making one full cycle rotation if (currentAngle != lastAngle){ if(currentAngle > lastAngle){ rotate = currentAngle – lastAngle; for(int x = 0; x < rotate; x++) { digitalWrite(stepPin,HIGH); delayMicroseconds(500); digitalWrite(stepPin,LOW); delayMicroseconds(500); } } if(currentAngle < lastAngle){ rotate = lastAngle – currentAngle; digitalWrite(dirPin,LOW); //Changes the rotations direction for(int x = 0; x < rotate; x++) { digitalWrite(stepPin,HIGH); delayMicroseconds(500); digitalWrite(stepPin,LOW); delayMicroseconds(500); } } } lastAngle = currentAngle; if (state == “Auto”){ mode = state; } } }
Hi everyone.
I’m quite new to MIT App Inventor and BLE connection in general.
I have begun creating an app that is to be used to connect to my Arduino Nano 33 IOT and then receive data from said Arduino to be then graphed. The data will be a weight between 0 and 50kg. However I have little understanding as to how BLE works and am unsure how to use the Bluetooth on the Arduino. I have looked all over the internet (granted maybe not in the correct places) but I have spent a few days on this and am struggling still. Here is the app, blocks and my code so far. But I have little to no understanding as to where to find the service or characteristics UUID.
Any help is appreciated, even if it’s a link to something else, be a previously made similar project, another thread or web page.
I’m happy to answer any questions. Thanks!
#include
BLEService weightService(“?”); // BLE weight Service
// BLE weight Switch Characteristic – custom 128-bit UUID, read and writable by centralBLEByteCharacteristic switchCharacteristic(“?”, BLERead);
// Arduino With Load Celllong time = 0; // Set time to 0int interval = 100; // Take a reading every 100 ms
void setup() {Serial.begin(9600);
while (!Serial);
// begin initializationif (!BLE.begin()) {Serial.println(“starting BLE failed!”);
while (1);
// set advertised local name and service UUID:BLE.setLocalName(“Arduino”);BLE.setAdvertisedService(weightService);
// add the characteristic to the serviceweightService.addCharacteristic(switchCharacteristic);
// add serviceBLE.addService(weightService);
// set the initial value for the characeristic:switchCharacteristic.writeValue(0);
// start advertisingBLE.advertise();
Serial.println(“BLE Active”);
void loop() {float curReading = analogRead(0); // Take reading of analog pin 0 of Arduino
// using serial.print, we can send the data in a ‘text’ formatSerial.print(curReading);delay(100);}
Step 7: Recieve Data From Arduino
Now, you are not always sending data to the Arduino. Sometimes you want to get something back. In fact, if you want to have reliable connections, you should require something back. A parity character, if you will. Something that signals that all of the data was received and the arduino is ready to get more. In this case we use the letter ‘d.’ D is for Done. Now you could change your arduino code to send the value of a sensor or anything else. But it is good practice and much more reliable to send every data set with an signal character to show that all the data was sent and received.
To read this data being sent (‘d’) just again go through the bluetooth options until you find the type of data that you want to wait for. The character ‘d’ in this case is simply text in the form of a single byte, so we allow the scanning of only one Byte. If it is a “d” then we know that the arduino read the signal we sent and that we can send another.
Arduino Code
Here’s a quick overview of that code. So, via the serial port we receive the incoming data from the smartphone and store it in the ‘state’ variable. If we receive the character ‘0’ which is sent from the smartphone when the ‘LED: OFF’ button is pressed, we will turn the LED off and send back to the smartphone the String “LED: OFF”. On the other hand, if we receive the character ‘1’ we will turn the LED on and send back the String “LED: ON”.
/* Arduino and HC-05 Bluetooth Module Tutorial * * by Dejan Nedelkovski, www.HowToMechatronics.com * */ int state = 0; void setup() { pinMode(ledPin, OUTPUT); digitalWrite(ledPin, LOW); Serial.begin(38400); // Default communication rate of the Bluetooth module } void loop() { if(Serial.available() > 0){ // Checks whether data is comming from the serial port state = Serial.read(); // Reads the data from the serial port } if (state == '0') { digitalWrite(ledPin, LOW); // Turn LED OFF Serial.println("LED: OFF"); // Send back, to the phone, the String "LED: ON" state = 0; } else if (state == '1') { digitalWrite(ledPin, HIGH); Serial.println("LED: ON");; state = 0; } }
Code language: Arduino (arduino)
So now we need to build our custom Android application which will send those characters ‘0’ and ‘1’ when a particular button is pressed, as well as, receive the incoming Strings from the Arduino.
Step 3: App Inventor
The basics of app inventor are easy. If you know how to code you can struggle through the basic set-up and operation. So just fiddle around until you have a button or slider bar that you want to use then you can add in this bluetooth code. In the context of the tutorial the app is that of the LittleArm Arduino Robot Arm, which has multiple sliders. But we will focus on just one.
Step 4: Connect Arduino to Android Device
at first you need a terminal emulator on your andriod device to send or receive data to arduino .
You can download this app from Google play .
https://play.google.com/store/apps/details?id=arduino.bluetooth.terminal&feature=search_result#?t=W251bGwsMSwxLDEsImFyZHVpbm8uYmx1ZXRvb3RoLnRlcm1pbmFsIl0.
after that , you can use the same arduino Sketch and control LED Blinking on or Off from android device .
just type and t send #1 to make LED Blink on , or 0 to blink off .
this video below show how to control arduino I/O from android tablet .
Keywords searched by users: mit app inventor arduino
Categories: Có được 54 Mit App Inventor Arduino
See more here: kientrucannam.vn
See more: https://kientrucannam.vn/vn/