I used the following code to read sequences of integers from Arduino (Arduino-Mega 2560) serial communication
but it gives me garbage (or wrong value), help me to find out the bug please...
int time=0,i;
void setup() {
pinMode(6,OUTPUT);
Serial.begin(9600);
}
void loop(){
i=0;
while(Serial.available()>0) {
time=Serial.parseInt();
}
for(i=1;i<=time;i++){
digitalWrite(6,1);
delay(150);
digitalWrite(6,0);
delay(100);
}
time=0;
}
Your code is wrong. Or at least the logic is wrong.
Try this:
void loop(){
if(Serial.available()) {
time=Serial.parseInt();
for(i=1;i<=time;i++){
digitalWrite(6,1);
delay(150);
digitalWrite(6,0);
delay(100);
}
time=0;
}
}
Your code looks like it should work, but maybe the problem is in the data you are sending.
Serial.parseInt() expects ascii characters that represent a number. Are you sending a number encoded as a string of chars? Note that Serial.write(99) will send a single byte with value 99.
Since the numbers are in the range 0 to 99, they will fit in a single byte. Why not just send a byte and read the byte on the other end?
void setup() {
pinMode(6,OUTPUT);
Serial.begin(9600);
}
void loop(){
int time=0;
if(Serial.available()>0) { // using while will read all the bytes and use the last one
time = Serial.read();
}
for(int i=1; i<=time; i++){
digitalWrite(6,1);
delay(150);
digitalWrite(6,0);
delay(100);
}
}
Related
I connected my Bluetooth module to the mobile phone and made up a code to communicate between Arduino and mobile through Bluetooth (send messages from Bluetooth module to device and vice versa).
Now I want to make a response, which means that if I send from the mobile "hi" the arduino replies and says "Hello" or whatever.
I have tried tons of codes but none worked, so would anyone please help me?
#include <SoftwareSerial.h>
SoftwareSerial myserial (6,5);
void setup() {
myserial.begin(9600);
Serial.begin (9600);
}
void loop() {
if (myserial.available()) {
Serial.write(+ myserial.read());
}
if (Serial.available()) {
myserial.write(Serial.read());
}
}
Another code but making a loop without sending anything
#include <SoftwareSerial.h>
SoftwareSerial myserial(6,5); //Arduino: R:5,T:6; bluetooth: T:5, R:6;
void setup() {
myserial.begin(9600);
Serial.begin (9600);
}
void loop() {
if (myserial.available()) {
Serial.write(myserial.read());
}
if (Serial.available()) {
myserial.write(Serial.read());
}
for (int i = 0; i=2; i++) {
myserial.write("hello");
}
if (myserial.read() =="n") {
myserial.write("hello");
}
}
You need to build your serial string char by char using the SerialEvent() interrupt, then do a String comparison using the .equals method. Despite many people will tell you that String types are 'evil' (see this and this) it might be a good solution for making things clearer (and perhaps a bit easier if you don't want to mess with C char strcmp() functions and pointers. In the end, the String type is there for you and I see no reason for not using it in general projects.
Based on the SerialEvent() documentation [1], and the String reference [2], you could do something like:
String inputString = ""; // a String to hold incoming data
bool stringComplete = false; // whether the string is complete
void setup() {
// initialize serial:
Serial.begin(9600);
// reserve 200 bytes for the inputString:
inputString.reserve(200);
}
void loop() {
// print the string when a newline arrives:
if (stringComplete) {
//Then you compare the inputString with the word you want to detect using the .equals method from the String class
if(inputString.equals("Hi"){
Serial.println("Hello");
}
// clear the string for a new comparison:
inputString = "";
stringComplete = false;
}
}
/*
SerialEvent occurs whenever a new data comes in the hardware serial RX. This
routine is run between each time loop() runs, so using delay inside loop can
delay response. Multiple bytes of data may be available.
*/
void serialEvent() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag so the main loop can
// do something about it:
if (inChar == '\n') {
stringComplete = true;
}
}
}
EDIT 1: Of course, you can replace the Serial object from this example code with your own myserial object from the BlueTooth communication.
I am trying to have a NodeMCU(ESP32) receive a floating data type from an Arduino Uno but I do not have any idea how. Can someone please guide me through the process? For now, I have the basic serial communication code sending a single digit Int from the Arduino to the NodeMCU.
Sender (Arduino Uno):
int val = 1;
void setup()
{
Serial.begin(19200);
}
void loop()
{
Serial.write(val);
delay(3000);
}
Receiver (NodeMCU):
#include <HardwareSerial.h>
HardwareSerial receiver(2);
void setup()
{
receiver.begin(19200, SERIAL_8N1, 16, 17);
Serial.begin(9600);
}
void loop()
{
if(receiver.available() > 0)
{
int received = receiver.read();
Serial.println(received); //tried printing the result to the serial monitor
}
delay(3000);
}
Write/read in the form you use it, is for single bytes only. A float in Arduino consists of 4 bytes.
You can use write to send a series of bytes, and you have to read those bytes, arriving one after the other, depending on the serial speed. Synchronization/lost bytes might be a problem, here in this simple solution I assume the best.
Sender:
float val = 1.234;
void setup() {
Serial.begin(19200);
}
void loop() {
Serial.write((byte*)&val,4);
delay(3000);
}
Receiver:
#include <HardwareSerial.h>
HardwareSerial receiver(2);
void setup()
{
receiver.begin(19200, SERIAL_8N1, 16, 17);
Serial.begin(9600);
}
void loop()
{
if(receiver.available() > 0)
{
delay(5); // wait for all 4 bytes
byte buf[4];
byte* bp = buf;
while (receiver.available()) {
*bp = receiver.read();
if (bp - buf < 3) bp++;
}
float received = * (float*)buf;
Serial.println(received, 3); // printing the result to the serial monitor
}
delay(100); // not really required, should be smaller than sender cycle
}
I'm trying to convert a sensor value to binary to be stored in a small char array (tbuf) and concatenate the small arrays into one bigger array. Ultimately, I want to send the big array (pbuf) filled with 7, 10-bit values over serial with Serial.write(). This is the code that I've tried so far:
void setup() {
Serial.begin(115200);
}
void loop() {
if (Serial.available() > 0) {
int s = 251;
char pbuf[78];
char tbuf[11];
itoa(s, tbuf, 2);
strcat(pbuf, tbuf);
Serial.println(pbuf);
}
Serial.end();
}
It doesn't output the permanent buffer (pbuf), or anything, to the serial monitor. My output to the serial monitor is nothing.
I would appreciate any suggestions on how to get an output from code similar to this.
Don't use Serial.end() in function loop(). Your code runs one time Serial.begin() and if your Serial is not available then you are calling only Serial.end().
Maybe you could try this approach:
int varA =0;
void setup() {
Serial.begin(115200);
}
void loop() {
if (Serial.available() > 0) {
varA = Serial.parseInt(); //or Serial.parseFloat();
Serial.println(varA);
}
}
I've two Arduinos and I want to make them communicate via TX/RX. Arduino one as a sender, and Arduino two as a receiver. But I have a problem with the receiver code and get this error:
call of overloaded 'println(char [4], int)' is ambiguous
Can anyone help me? Thank you.
This is my receiver code:
char str[4];
void setup(){
Serial.begin(9600);
Serial.begin(9600);
}
void loop() {
int i=0;
if (Serial.available()){
delay(100); //allows all serial sent to be received together
while(Serial.available() && i<4){
str[i++] = Serial.read();
}
str[i++]='\0';
}
if(i>0){
Serial.println(str, 4);
}
}
Why do you have two Serial.begin(9600) in the setup?
After the while loop, the i var is equal to 4. Your biggest index in str array is str[3] (0-3), so you are accesing the 4th index which doesn't exist.You should remove that str[i++] = '\0', and if you want to make communication you should do something like :
if (i > 0) {
for (int j=0; j<4; j++) {
Serial.print(str[j]);
}
Serial.println("");
}
I have the script below and it works.
But I want to control it with a word like on or off instead of one character.
I tried and searched a lot but without success.
/*
Simple LED sketch
*/
int led = 13; // Pin 13
void setup()
{
pinMode(led, OUTPUT); // Set pin 13 as digital out
// Start up serial connection
Serial.begin(115200); // baud rate
}
void loop()
{
if (Serial.available()) {
int ser = Serial.read(); //read serial as ascii integer
if (ser == 'a') { //is this serial byte the ASCII equivalent of 0 through 9?
digitalWrite(led, HIGH); // on
Serial.println("aan");
}
else if (ser == 'u') {
digitalWrite(led, LOW); // off
Serial.println("uit");
}
}
}
Use Serial.readStringUntil(terminator) to read a string from the serial.
The sent string needs to be terminated with a newline character.
Chose Newline in the Arduino IDE's Serial Monitor.
String cmd = "";
void loop()
{
if (Serial.available()) {
cmd = Serial.readStringUntil('\n');
if (cmd == "on") {
digitalWrite(led, HIGH); // on
Serial.println("aan");
}
else if (cmd == "off") {
digitalWrite(led, LOW); // off
Serial.println("uit");
}
}
}
Your problem is that you are using a char you need to declare a string so you can compare that string to the input, the guy above gave a ok/very slacky/too complex for you answer (sorry no offense I am just trying to show contrast between a complex and a easy answer not trying to offend you) and partially is because he did not explain what he is doing and because he is doing unnecessary/useless work. There is a function in c++ called Serial.readString(), much easier then the stuff up there. Assuming your level of programming (no offense) from your question here is a quick review on data types:
String = ""
int = integer number {1,2,3,4,5,6,...}
char = '' <- Notice the difference from String = ""
float = floating point number {1.2,4.5,...}
(These are not all of them, there is more like byte and so on but just make sure you know how to use the above first)
/*
Simple LED sketch
*/
int led = 7; // Pin 13
String ser; //Declare the string that is going to store what your are going to
//write in the serial
void setup(){
// Start up serial connection
//It's good convention to start the serial before pinMode or any other thing
//in setup
Serial.begin(9600); //I don't know why you need such an high baud rate in
//your thing, 9600 for what you have to do is more than fine, this is just at
//what speed the serial is read (in a very general explanation)
pinMode(led, OUTPUT); // Set pin 13 as digital out
//make sure you put in here wheter you want to start the led "on" or "off"
//Eg you want it to start on, then digitalWrite(led, HIGH);
}
void loop(){
ser = Serial.readString();
if(Serial.available() == 0) { //You can also use a while loop if you want to
//This is telling the arduino: if there is something in the serial, then do...
if(ser == "on"){
Serial.println("on");
digitalWrite(led, HIGH);
}else if(ser == "off"){
Serial.println("off");
digitalWrite(led, LOW);
}
}
}
Hope it helped!
Also notice how the above code with
if(Serial.available())
This is a quite WEIRD and SHADY statement and might not work. That's because you are not really telling the int value into the function Serial.available
As the arduino guidelines specify:
int incomingByte = 0; // for incoming serial data
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
// say what you got:
Serial.print("I received: ");
Serial.println(incomingByte, DEC);
}
}
viewable here