Garbage text in serial monitor from Arduino - arduino

I have a problem with my brand new Arduino, it seems that
no matter what I print with
Serial.println()
be it numbers, strings or anything else, I get garbage
on the Arduino serial monitor:
Not even the simplest hello world program works.
Could you help me identify the problem and solve it?

I found the solution :)
I wrote a test program and found a working baud-rate at 600.
My test program:
long baudrates[] = {600,1200,2400,4800,9600,14400,19200,28800,38400,56000,57600,115200,128000,256000};
unsigned char baudcounter = 0;
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication
Serial.begin(baudrates[baudcounter]);
}
// the loop routine runs over and over again forever:
void loop() {
Serial.println();
Serial.println(baudrates[baudcounter]);
Serial.println(" !\"#$%&'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~");
Serial.println();
baudcounter++;
baudcounter %= sizeof(baudrates)/sizeof(long);
delay(1000); // delay
Serial.begin(baudrates[baudcounter]); // switch baudrate
}

Related

How to communicate with HM-19 BLE Module and scan using ultrasonic sensor

I am working on my senior project for school, and part of what I need to do is use an HM-19 Bluetooth 5.0 module to connect to another Bluetooth 5.0 module and establish a master slave connection.
I can do that just fine, but when I include the code needed for my ultrasonic sensor to do scan, my commands to my HM-19 don't return anything and I can't do any of the basic functions such as finding connections. I have tested it with and without the ultrasonic sensor code and the problem occurs when I use the sensor portion of the code.
TO BE CLEAR, all I am trying to do is just have my Bluetooth 5.0 chip connect to another and do normal commands while also inputting into my serial monitor a distance when I put my hand in front. THIS IS JUST A TEST, once I get that done I will move to what I really want to do.
IT'S JUST A STARTING POINT IN A PROJECT. I have a function call for my sensor and my bluetooth chip in the void loop, that's all that is in there.
I just want to know how to fix this issue. How can I scan with my ultrasonic sensor and send commands to my Bluetooth module? Any help would be greatly appreciated.
[Here are the results when the sensor is commented][1] and [here are the unsuccessful results that results in an infinite loop where I can't get to the portion of the code that returns what the chip says][2]. Lastly, although most of the links include stuff for the HM-10, the commands are basically the same for the HM-19. I'm adding more because stack overflow won't let me edit this post until there are more characters or something. I hope you have a good day/evening person reading this.
Here is my code:
// SerialIn_SerialOut_HM-10_01
//
// Uses hardware serial to talk to the host computer and AltSoftSerial for communication with the bluetooth module
//
// What ever is entered in the serial monitor is sent to the connected device
// Anything received from the connected device is copied to the serial monitor
// Does not send line endings to the HM-10
//
// Pins
// BT VCC to Arduino 5V out.
// BT GND to GND
// Arduino D8 (SS RX) - BT TX no need voltage divider
// Arduino D9 (SS TX) - BT RX through a voltage divider (5v to 3.3v)
//
#include <AltSoftSerial.h>
AltSoftSerial BTserial;
// https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html
char c=' ';
boolean NL = true;
const int trigPin = 9;
const int echoPin = 10;
float duration, distance;
boolean wait_your_turn = false; //My attempt to make sure the sensor and the Bluetooth module don't interfere with each other
//if I'm sending data from the serial monitor to the bluetooth module and vice versa it switches to true and the bluetooth module
//does its thing, so the sensor doesn't get in the way.
void setup()
{
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
Serial.print("Sketch: "); Serial.println(__FILE__);
Serial.print("Uploaded: "); Serial.println(__DATE__);
Serial.println(" ");
BTserial.begin(9600);
Serial.println("BTserial started at 9600");
}
void loop()
{
Bluetooth();
Sensor();
}
void Sensor(){
if((wait_your_turn == true))
{}
else
{
Serial.println("Scanning for stuff.");
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration*.0343)/2;
if(distance <= 20)
{
Serial.println(distance);
delay(500);
}
}
}
void Bluetooth()
{
if (Serial.available())
{
if(wait_your_turn == false)
Serial.println("Serial is available");
wait_your_turn = true;
while(Serial.available()>0)
c = Serial.read();
Serial.write(c);
if(c!=10&c!=13)
BTserial.print(c);
}
if (BTserial.available())
{
// Serial.print("We are at the bluetooth portion.");
while(BTserial.available())
c = BTserial.read();
Serial.print(c);
wait_your_turn = false;
}
}
[1]: https://i.stack.imgur.com/Dn4i0.png
[2]: https://i.stack.imgur.com/s9Ifv.png
Sorry, I forgot about this question. I figured it out. What I did was have 1 Arduino control the Ultrasonic sensor and send a character to the other Arduino when something was in range of the sensor. The other Arduino would then read the character and based on the character send it would perform an action. Thank you everyone who commented and have a great rest of your days.

Unable to SMS using AT commands for arduino uno

#include <SoftwareSerial.h>
SoftwareSerial mySerial(0, 1);
void setup()
{
mySerial.begin(9600); // Setting the baud rate of GSM Module
Serial.begin(9600); // Setting the baud rate of Serial Monitor (Arduino)
delay(100);
}
void loop()
{
if (Serial.available()>0)
SendMessage();
if (mySerial.available()>0)
Serial.write(mySerial.read());
}
void SendMessage()
{
mySerial.println("AT+CMGF=1"); //Sets the GSM Module in Text Mode
delay(1000); // Delay of 1000 milli seconds or 1 second
mySerial.println("AT+CMGS=\"+1876xxxxxxx\"\r"); // Replace x with mobile number
delay(1000);
mySerial.println("I am SMS from GSM Module");// The SMS text you want to send
delay(100);
mySerial.println((char)26);// ASCII code of CTRL+Z
delay(1000);
}
I am trying to send a sms using SIM 800 RPI GSM ADD-on v2.3 module through the arduino platform however everything I try fails. Please assist and explain where i am going wrong. Thank you. My code is above. Thanks
You are missing a carriage return in "AT+CMGF=1".
Change "AT+CMGF=1" to "AT+CMGF=1\r"
Although having delays between command works and suffices the purpose but is not recommended.
It is preferable to catch and analyze the messages returned by the SIM800 especially in case of error has occurred.

Unable to do Arduino Mega to Arduino Mega serial communication

Based on the circuit below, I tried hooking up two Arduino Mega for serial communication.
The code for sender:
char mystr[3] = "Hello"; //String data
void setup() {
// Begin the Serial at 9600 Baud
Serial.begin(9600);
}
void loop() {
Serial.write(mystr, 5); //Write the serial data
delay(1000);
}
The code for receiver:
char mystr[5]; //Initialized variable to store received data
void setup() {
// Begin the Serial at 9600 Baud
Serial.begin(9600);
}
void loop() {
Serial.readBytes(mystr, 5); //Read the serial data and store in var
delay(1000);
}
There is no output in the Serial console of Arduino. Could someone please inform me of the possible cause and solution for the same. If I've missed out anything, over- or under-emphasized a specific point let me know in the comments.
If I understood this right you have one Arduino connected to your pc and to another Arduino?
The problem is that you need to specify which Serial port to use:
That is rather easy, just type Serial1 or Serial2 instead of just Serial. That allows you to open 2 Serial ports: One to your other Arduino and one to your Computer for Displaying the results !
LINK: https://www.arduino.cc/en/Tutorial/MultiSerialMega
You need to check available data from serial:
void loop() {
if (Serial.available() > 0) {
// read the incoming byte:
Serial.readBytes(mystr, 5);
Serial.print("I received: ");
Serial.println(mystr, DEC);
}
}

How to make Arduino run a script

i'm a software developer but i'm new to Arduino, and to the electronics world.
I would like to build a simple project that combined both, and really appreciate any help where to start.
final project should be Arduino with a button and a LED, when tapping the button I want run a script on my mac, then if the script finished successfully i want to turn on the LED
I already saw some tutorial about how to use buttons and LEDs so
the main thing i'm interested here is how communicate from the Arduino to the mac and vice versa. and especially how to make it run a script on my mac.
You should look into the Serial class and the examples (via File > Examples > Commmunication)
You will need to write a bit of code on the Arduino side to send data via Serial when the button is pressed (so you can trigger your script) and receive data (when the script is done) to control the LED.
Here is a rough example on the Arduino side:
const int btnPin = 12;//button pin
const int ledPin = 13;
int lastButtonState;
void setup(){
//setup pins
pinMode(btnPin,INPUT_PULLUP);
pinMode(ledPin,OUTPUT);
//setup communication
Serial.begin(9600);
}
void loop() {
int currentButtonState = digitalRead(btnPin);//read button state
if(lastButtonState != currentButtonState && currentButtonState == LOW){//if the state of the pin changed
Serial.write(currentButtonState);//send the data
lastButtonState = currentButtonState;//update the last button state
//turn on LED
digitalWrite(ledPin,HIGH);
}
}
void serialEvent(){//if any data was sent
if(Serial.available() > 0){//and there's at least 1 byte to look at
int data = Serial.read();//read the data
//do something with it if you want
//turn off the LED
digitalWrite(ledPin,LOW);
}
}
Be aware you may have different pin numbers in your setup and depending on how the button wired, you will either look for a LOW or HIGH value in the in the condition checking the currentButtonState.
In terms of the communication there are a few key elements:
Serial.begin(9600);
Starts Serial communication with baud rate 9600. You will need to match this baud rate on the other end to ensure correct communication.
Serial.write();
Will send data to the port.
serialEvent()
is predefined in Arduino and gets called when new Serial data arrives.
Note that this gets called automatically on a Arduino Uno (and other simpler boards), however this doesn't get called on other boards:
serialEvent() doesn’t work on the Leonardo, Micro, or Yún.
serialEvent() and serialEvent1() don’t work on the Arduino SAMD Boards
serialEvent(), serialEvent1()``serialEvent2(), and serialEvent3() don’t work on the Arduino Due.
On the script side, you haven't mentioned the language, but the principle is the same: you need to know the port name and baud rate to establish communication from your mac.
(You can manually call serialEvent() in loop() as a workaround. For more details see the Arduino Reference)
The port is what you used to upload the Arduino code (something like /dev/tty.usbmodem####) and in this particular case the baud rate is 9600. You should be able to test using Serial Monitor in the Arduino IDE.
Your script will be something along there lines (pseudo code)
open serial connection ( port name, baudrate = 9600 )
poll serial connection
if there is data
run the script you need
script finished executing, therefore send data back via serial connection
Be sure to checkout the Interfacing with Software to find guide on the scripting language of your choice
Update
Here's a quick example using Processing to interface with the arduino using it's Serial library. So on the Arduino side, here's a minimal sketch:
const int btnPin = 12;//button pin
const int ledPin = 13;
boolean wasPressed;
char cmd[] = "/Applications/TextEdit.app\n";
void setup(){
//setup pins
pinMode(btnPin,INPUT_PULLUP);
pinMode(ledPin,OUTPUT);
//setup communication
Serial.begin(9600);
}
void loop() {
int currentButtonState = digitalRead(btnPin);//read button state
if(!wasPressed && currentButtonState == LOW){//if the state of the pin changed
Serial.write(cmd);//send the data
wasPressed = true;//update the last button state
//turn on LED
digitalWrite(ledPin,HIGH);
}
if(currentButtonState == HIGH) wasPressed = false;
}
void serialEvent(){//if any data was sent
if(Serial.available() > 0){//and there's at least 1 byte to look at
int data = Serial.read();//read the data
//do something with it if you want
//turn off the LED
digitalWrite(ledPin,LOW);
}
}
and on the Processing side:
import processing.serial.*;
void setup(){
try{
Serial arduino = new Serial(this,"/dev/tty.usbmodemfa141",9600);
arduino.bufferUntil('\n');//buffer until a new line is encountered
}catch(Exception e){
System.err.println("Error opening serial connection! (check cables and port/baud settings!");
e.printStackTrace();
}
}
void draw(){}
void serialEvent(Serial s){
String[] command = s.readString().trim().split(",");//trim spaces, split to String[] for args
println(command);//see what we got
open(command);//run the command
s.write("A");//send a message back to flag that the command is finished (turn LED off)
}
Hope this is a helpful proof of concept. Feel free to use any other language with a serial library available instead of Processing. The syntax may differ just a tad (probably more on the running of the process/command), but the concept is the same.
Update The example above can be simplified a touch by not having the command on the Arduino side:
there's less data sent on Serial from Arduino to Processing reducing communication time and the odds of communication interference
the app runs on a computer hence changing the command is simpler to do on software side as opposed to having to change the Arduino code and re-upload each time.
Arduino:
const int btnPin = 12;//button pin
const int ledPin = 13;
boolean wasPressed;
void setup(){
//setup pins
pinMode(btnPin,INPUT_PULLUP);
pinMode(ledPin,OUTPUT);
//setup communication
Serial.begin(9600);
}
void loop() {
int currentButtonState = digitalRead(btnPin);//read button state
if(!wasPressed && currentButtonState == LOW){//if the state of the pin changed
Serial.write('R');//send the data
wasPressed = true;//update the last button state
//turn on LED
digitalWrite(ledPin,HIGH);
}
if(currentButtonState == HIGH) wasPressed = false;
}
void serialEvent(){//if any data was sent
if(Serial.available() > 0){//and there's at least 1 byte to look at
int data = Serial.read();//read the data
//do something with it if you want
//turn off the LED
digitalWrite(ledPin,LOW);
}
}
Processing:
import processing.serial.*;
String[] command = {"/Applications/TextEdit.app", "myText.txt"};
void setup() {
try {
Serial arduino = new Serial(this, "/dev/tty.usbmodemfa141", 9600);
}
catch(Exception e) {
System.err.println("Error opening serial connection! (check cables and port/baud settings!");
e.printStackTrace();
}
}
void draw() {
}
void serialEvent(Serial s) {
if (s.read() == 'R') {
launch(command);//run the command
s.write("A");//send a message back to flag that the command is finished (turn LED off)
}
}
(btw, 'R' is an arbitrary single character, can be something else as long it's the same char on both Serial send and receive sides)
Also, bare in mind launch() returns Proccess which can be useful to get more information from the software launched.
Dunno if it will help you as much as it did me but this question shows a simple example of how to use the script with a simple button in an android app
Run script with android app
Hope it helps
I found a workaround in Linux. It's a little messy but it works. I use Coolterm to capture the serial output from the arduino to a text file and I wrote a small python script that reads the file (or simply, in my case, executes the command I want if the file is not empty).

Serial overflow in Arduino

When reading SMS using an Arduino program, the serial monitor shows only the senders (no date or time) and truncates the message. This is may be due to serial overflow, a common problem in Arduino.
Code:
#include <SoftwareSerial.h>
#include <String.h>
SoftwareSerial mySerial(7, 8);
void setup()
{
mySerial.begin(9600);
Serial.begin(9600);
}
void loop()
{
mySerial.print("AT+CMGR=1\r");
delay(100);
while(mySerial.available())
Serial.write(mySerial.read());
delay(1000);
}
Output
AT+CMGR=1
+CMGR: "REC READ","+XXXXX","A Silky Soni","1AT+CMGR=1
+CMGR: "REC READ","+XXXXX","A Silky Soni","1AT+CMGR=1
+CMGR: "REC READ","+XXXXX","A Silky Soni","1AT+CMGR=1
You might need to adjust the baud rate in your code to match the GSM shield.
It's not the baud rate, because the string is legible so all the bits are in the correct position, however the string is truncated.
This happen because the output buffer in mySerial take more time to be filled by the GSM shield than the time to be depleted by the mySerial.read() instruction. That's it: when mySerial.available() is checked and the GSM shield don't have time to put anything in the output buffer, the result is the fail of the while loop. There are some ways to face that problem:
Put a delay() with specific time inside the while:
void loop()
{
mySerial.print("AT+CMGR=1\r");
delay(100);
while(mySerial.available()){
Serial.write(mySerial.read());
delay(100); //fix the time according to how fast the GSM shield
//wrote the data in the serial port.
}
delay(1000);
}
Or use a timeout:
unsigned long init_time, timeout=500;//choose the correct timeout value
void loop()
{
mySerial.print("AT+CMGR=1\r");
//delay(100); //this delay can be omitted
init_time=millis();
do{
while(mySerial.available()){
Serial.write(mySerial.read());
init_time=millis();
}
}while(millis()-init_time < timeout);
delay(1000);
}
The millis()-init_time give the time elapsed since the last time the mySerial.available() return true or before the check if never was available. The code will still checking for availability until reach the timeout limit.
I suggest the last approach. Happy coding!

Resources