Error when asking for numbers on Arduino Uno - c++

my name is Jan, it turns out that when I put a number like 200, it shows me 2 on the console, then a 0 and then another 0
This is my code :
const int ledPin = 3 ;
const int rePin = 2 ;
const int puPin = 1 ;
int pulso = 0;
int input;
void setup() {
// initialize digital pin LED_BUILTIN as an output.
Serial.begin(9600) ;
pinMode(ledPin, OUTPUT);
pinMode(rePin, OUTPUT);
pinMode(puPin, INPUT) ;
}
// the loop function runs over and over again forever
void loop() {
if (Serial.available()) {
char pulso = Serial.read(); //To introduce the pulse
Serial.print("Numero de pulsaciones: ");
Serial.print(pulso);
This is the error : If I put 200
What I want is for an input to appear on the console that requests a certain number of pulses, then when I put them, the number of pulses that I have put appears on the console and then if the pulses are less than 35, for example, give a discharge and a led is activated.

here is the correct code, you just need to configure the serial monitor to send the both NL/CR.
const int ledPin = 3 ;
const int rePin = 2 ;
const int puPin = 1 ;
int pulso = 0;
int input;
bool mensajeRecibido = false;
String mensajeCompleto;
void setup() {
// initialize digital pin LED_BUILTIN as an output.
Serial.begin(9600) ;
pinMode(ledPin, OUTPUT);
pinMode(rePin, OUTPUT);
pinMode(puPin, INPUT) ;
mensajeCompleto.reserve(50); //Se reciben maximo hasta 50 bytes
mensajeCompleto = "";
}
// the loop function runs over and over again forever
void loop() {
if (Serial.available()) {
char byteSerial = Serial.read(); //To introduce the pulse
if(byteSerial == '\n'){
int pulso = mensajeCompleto.toInt();
Serial.print("Numero de pulsaciones: ");
Serial.print(pulso);
mensajeCompleto = "";
}
else{
mensajeCompleto = mensajeCompleto + byteSerial;
}
}
}

Related

Serial Communication on Arduino Nano IoT 33

I'm having trouble since moving from an Uno to the Nano 33 IoT unit.
I have read up on a lot of info with regards to this specific topic and still I pretty confused as I'm quite use to working with the Software Serial that's not available on the Nano 33.
According to the: https://github.com/ostaquet/Arduino-Nano-33-IoT-Ultimate-Guide Guide using an addition port for serial as I'm all ready using Serial1 TX Pin 0, and RX Pin 1 my Sigfox unit: https://yadom.fr/carte-breakout-sfm10r1.html workes fine. The trouble is with my gps. If i swap the 2 around the GPS works fine and the Sigfox unit doesn't...
#include <TinyGPS++.h>
#include <Arduino.h>
#include "wiring_private.h"
static const uint32_t GPSBaud = 9600;
#define DEBUG 1
TinyGPSPlus gps;
uint8_t msg[12];
Uart mySerial (&sercom0, 5, 6, SERCOM_RX_PAD_1, UART_TX_PAD_2);
// Attach the interrupt handler to the SERCOM
void SERCOM0_Handler()
{
mySerial.IrqHandler();
}
void setup() {
pinMode(LED_BUILTIN, OUTPUT); // set LED pin as output
digitalWrite(LED_BUILTIN, LOW); // switch off LED pin
pinPeripheral(5, PIO_SERCOM);
pinPeripheral(6, PIO_SERCOM);
if(DEBUG){
Serial.begin(9600);
}
mySerial.begin(GPSBaud);
Serial1.begin(9600);
delay(100);
getID();
delay(100);
getPAC();
}
void loop()
{
msg[0]=0xC0;
msg[1]=0xFF;
msg[2]=0xEE;
sendMessage(msg, 3);
printInt(gps.satellites.value(), gps.satellites.isValid(), 5);
printFloat(gps.hdop.hdop(), gps.hdop.isValid(), 6, 1);
printFloat(gps.location.lat(), gps.location.isValid(), 11, 6);
printFloat(gps.location.lng(), gps.location.isValid(), 12, 6);
printInt(gps.location.age(), gps.location.isValid(), 5);
printDateTime(gps.date, gps.time);
printFloat(gps.altitude.meters(), gps.altitude.isValid(), 7, 2);
printFloat(gps.course.deg(), gps.course.isValid(), 7, 2);
printFloat(gps.speed.kmph(), gps.speed.isValid(), 6, 2);
printStr(gps.course.isValid() ? TinyGPSPlus::cardinal(gps.course.deg()) : "*** ", 6);
printInt(gps.charsProcessed(), true, 6);
printInt(gps.sentencesWithFix(), true, 10);
printInt(gps.failedChecksum(), true, 9);
Serial.println();
delay(120000);
if (millis() > 5000 && gps.charsProcessed() < 10)
Serial.println(F("No GPS data received: check wiring"));
}
void blink(){
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
delay(1000);
}
//Get Sigfox ID
String getID(){
String id = "";
char output;
Serial1.print("AT$I=10\r");
while (!Serial1.available()){
blink();
}
while(Serial1.available()){
output = Serial1.read();
id += output;
delay(10);
}
if(DEBUG){
Serial.println("Sigfox Device ID: ");
Serial.println(id);
}
return id;
}
//Get PAC number
String getPAC(){
String pac = "";
char output;
Serial1.print("AT$I=11\r");
while (!Serial1.available()){
blink();
}
while(Serial1.available()){
output = Serial1.read();
pac += output;
delay(10);
}
if(DEBUG){
Serial.println("PAC number: ");
Serial.println(pac);
}
return pac;
}
//Send Sigfox Message
void sendMessage(uint8_t msg[], int size)
{
Serial.println("Sigfox Start");
String status = "";
String hexChar = "";
String sigfoxCommand = "";
char output;
sigfoxCommand += "AT$SF=";
for (int i = 0; i < size; i++)
{
hexChar = String(msg[i], HEX);
//padding
if (hexChar.length() == 1)
{
hexChar = "0" + hexChar;
}
sigfoxCommand += hexChar;
}
Serial.println("Sending Sigfox Message...");
Serial.println(sigfoxCommand);
Serial1.println(sigfoxCommand);
while (!Serial1.available())
{
Serial.println("Waiting for Sigfox Response");
delay(7000);
}
while (Serial1.available())
{
output = (char)Serial1.read();
status += output;
delay(10);
}
Serial.println();
Serial.print("Sigfox Status \t");
Serial.println(status);
}
// This custom version of delay() ensures that the gps object
// is being "fed".
static void smartDelay(unsigned long ms)
{
unsigned long start = millis();
do
{
while (mySerial.available())
gps.encode(mySerial.read());
} while (millis() - start < ms);
}
static void printFloat(float val, bool valid, int len, int prec)
{
if (!valid)
{
while (len-- > 1)
Serial.print('*');
Serial.print(' ');
}
else
{
Serial.print(val, prec);
int vi = abs((int)val);
int flen = prec + (val < 0.0 ? 2 : 1); // . and -
flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
for (int i=flen; i<len; ++i)
Serial.print(' ');
}
smartDelay(0);
}
static void printInt(unsigned long val, bool valid, int len)
{
char sz[32] = "*****************";
if (valid)
sprintf(sz, "%ld", val);
sz[len] = 0;
for (int i=strlen(sz); i<len; ++i)
sz[i] = ' ';
if (len > 0)
sz[len-1] = ' ';
Serial.print(sz);
smartDelay(0);
}
static void printDateTime(TinyGPSDate &d, TinyGPSTime &t)
{
if (!d.isValid())
{
Serial.print(F("********** "));
}
else
{
char sz[32];
sprintf(sz, "%02d/%02d/%02d ", d.month(), d.day(), d.year());
Serial.print(sz);
}
if (!t.isValid())
{
Serial.print(F("******** "));
}
else
{
char sz[32];
sprintf(sz, "%02d:%02d:%02d ", t.hour(), t.minute(), t.second());
Serial.print(sz);
}
printInt(d.age(), d.isValid(), 5);
smartDelay(0);
}
static void printStr(const char *str, int len)
{
int slen = strlen(str);
for (int i=0; i<len; ++i)
Serial.print(i<slen ? str[i] : ' ');
smartDelay(0);
}
My problem is hence with the additional port creating via this section:
#include <Arduino.h>
#include "wiring_private.h"
Uart mySerial (&sercom0, 5, 6, SERCOM_RX_PAD_1, UART_TX_PAD_0);
// Attach the interrupt handler to the SERCOM
void SERCOM0_Handler()
{
mySerial.IrqHandler();
}
void setup() {
// Reassign pins 5 and 6 to SERCOM alt
pinPeripheral(5, PIO_SERCOM_ALT);
pinPeripheral(6, PIO_SERCOM_ALT);
// Start my new hardware serial
mySerial.begin(9600);
}
void loop() {
// Do something with mySerial...
}
On the Nano I have my TX on Nano Pin 6 (As it starts at ) and RX on Pin 7 "6" as it starts on 0....
It's swapped as to make RX and TX talk to each other on the board Where RX on the GPS = TX on the Nano, and TX on the GPS = RX on the Nano.
Am I using the wrong pins? AS the GPS doesn't want to respond with pin 5 & 6 pins at all...
The Lights blink on the gps so there's power, and if I swap the Gps with the Sigfox unit The gps works and the Sigfox unit then doesn't.
Am I using the wrong pins on the Nano Board? Please Help....
SERCOM0 with pins 5 and 6 are a good choice for additional Serial interface on Nano 33 IoT.
The variant.cpp file has
+------------+------------------+--------+---------+---------+
| Pin number | NANO Board pin | PIN | SERCOMx | SERCOMx |
| | | | (x/PAD) | (x/PAD) |
+------------+------------------+--------+---------+---------+
| 5 | ~D5 | PA05 | | 0/01 |
| 6 | ~D6 | PA04 | | 0/00 |
So the instantiation should be
Uart mySerial (&sercom0, 5, 6, SERCOM_RX_PAD_1, UART_TX_PAD_0);
you have UART_TX_PAD_2
Pin 5 is RX and pin 6 is TX.
The
pinPeripheral(5, PIO_SERCOM_ALT);
pinPeripheral(6, PIO_SERCOM_ALT);
commands should be after mySerial.begin, because begin does
pinPeripheral(uc_pinRX, g_APinDescription[uc_pinRX].ulPinType);
but .ulPinType is not PIO_SERCOM_ALT.
Working on Nano Pin D5 & D6 of Nano 33 IoT with the updated code above. Thanks to Juraj :-)

Shift register stops working after I send one piece of code with my arduino

I have been stuck with this problem for multiple days now and can't seem to find a fix. The problem is that after I send a command to my shift register it doesn't accept more commands.
I'm using an arduino UNO with a 74HC595 shift register.
The problem occurs in the manualOverWrite function.
uint8_t RFIDPinValues[] = { B00000101 };
sr.setAll(RFIDPinValues);
delay(4000);
uint8_t RFIDOffPinValues[] = { B00001000 };
sr.setAll(RFIDOffPinValues);
When I run this piece of my code it turns on a relay(pin 0) and stops. All my arduino code keeps working except the shift register.
#include <SPI.h>
#include <ShiftRegister74HC595.h>
byte readCard[4];
String MasterTag0 = "*******";
String MasterTag1 = "********";
String tagID = "";
//declare arduino pins
int overWrite = 0;
// Create instances
const int numberOfShiftRegisters = 1; // number of shift registers attached in series
int serialDataPin = 11;
int clockPin = 12;
int latchPin = 8;
ShiftRegister74HC595<numberOfShiftRegisters> sr(serialDataPin, clockPin, latchPin);
void setup() {
Serial.begin(115200);
Serial.println("Startup");
// Initiating inputs
pinMode(overWriteButton, INPUT);
// set base state
sr.setAllLow();
uint8_t startValues[] = { B00001000 };
sr.setAll(startValues);
}
void loop() {
//ez to use vars
overWrite = digitalRead(overWriteButton);
manualOverWrite();
}
void manualOverWrite() {
if(overWrite == HIGH) {
uint8_t turnOnPinValues[] = { B00000101 };
sr.setAll(turnOnPinValues);
delay(5000);
uint8_t turnOffPinValues[] = { B00001000 };
sr.setAll(turnOffPinValues);
}
else {
uint8_t turnOn2PinValues[] = { B00001000 };
sr.setAll(turnOn2PinValues);
}
}
My apologies for the mess
https://mega.nz/file/NEYFiAAA#Rc4QUpv6cnL-_1NJJrjKe-IaInH_33wGJlHpGlVkySM

Temp was not declared in this scope when getting values from bool

Hello I wanted to change some voids to bools and I am a little lost. I understand if you write a void or a bool and want to add the values to the next void you just insert the code to add the previous function
I don't know how to explain it I am just gonna tell you what I want to do:
created a new bool getValues and added all the value getting code from the sensors then I wanted to send the data to void loop that will send the data through mqqt to raspberry.
I understand that bool is for true and false. but I don't really understand the etiquette of using it
so the problem I am getting 'temp' was not declared in this scope at the void loop function
I highlighted the function with // where I get the error it's almost at the bottom
#include "DHT.h"
#include <WiFi.h>
#define DHTPIN 25 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11
//MQTT Setup Start
#include <PubSubClient.h>
#define mqtt_server "192.168.1.210"
WiFiClient espClient;
PubSubClient client(espClient);
#define mqttlightReadingpercent "greenHouse/light"
#define mqttsoilmoisturepercent "greenHouse/soil"
#define mqtttemp "greenHouse/temp"
#define mqtthum "greenHouse/hum"
//MQTT Setup End
const char* ssid = "Cgates_E031F1"; // ESP32 and ESP8266 uses 2.4GHZ wifi only
const char* password = "60E541C32F";
DHT dht(DHTPIN, DHTTYPE);
const byte lightPin = 33;
int lightReading;
int lightReadingpercent=0;
//const int RELAY_PIN = 15; // the Arduino pin, which connects to the IN pin of relay
// soil moisture
const int AirValue = 4095; //you need to replace this value with Value_1
const int WaterValue = 2200; //you need to replace this value with Value_2
const int SensorPin = 32;
int soilMoistureValue = 0;
int soilmoisturepercent=0;
const int Lightvalue = 0;
const int Darkvalue = 4095;
unsigned long millisNow = 0; //for delay purposes
unsigned int sendDelay = 20000; //delay before sending sensor info via MQTT
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println();
// begin Wifi connect
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.disconnect();
delay(2000);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
//end Wifi connect
client.setServer(mqtt_server, 1883);
// pinMode(RELAY_PIN, OUTPUT);//relay
pinMode(lightPin, INPUT);
pinMode(SensorPin, INPUT);
Serial.println(F("DHTxx test!")); //dht
;
dht.begin();
}
void reconnect() {
// Loop until we're reconnected
int counter = 0;
while (!client.connected()) {
if (counter == 5) {
ESP.restart();
}
counter+=1;
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("greenHouseController")) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
bool getValues() {
lightReading = analogRead(lightPin); //0-4095 12bit -- esp8266 10bit 0-1023 -- arduino 8bit 0-254
Serial.print("Light reading = ");
lightReadingpercent = map(lightReading, Darkvalue, Lightvalue, 0, 100 );
Serial.print(lightReadingpercent);
Serial.println(" %");
Serial.println();
soilMoistureValue = analogRead(SensorPin); //put Sensor insert into soil
soilmoisturepercent = map(soilMoistureValue, AirValue, WaterValue, 0, 100);
if (soilmoisturepercent > 100) {
Serial.println("Soil moisture ");
Serial.println("100 %");
delay(500);
}
else if(soilmoisturepercent <0) {
Serial.println("Soil moisture ");
Serial.println("0 %");
delay(500);
}
else if (soilmoisturepercent >=0 && soilmoisturepercent <= 100) {
Serial.println("Soil moisture "); //go to next line
Serial.print(soilmoisturepercent);
Serial.println("%");
delay(500); // soil end
}
delay(500);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float hum = dht.readHumidity();
// Read temperature as Celsius (the default)
float temp = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(hum) || isnan(temp) || isnan(f)) {
Serial.println(F("Failed to read from DHT sensor!"));
return 1;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, hum);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(temp, hum, false);
Serial.print(F(" Humidity: "));
Serial.print(hum);
Serial.print(F("% Temperature: "));
Serial.print(temp);
Serial.print(F("C "));
Serial.print(f);
Serial.print(F("F Heat index: "));
Serial.print(hic);
Serial.print(F("C "));
Serial.print(hif);
Serial.println(F("F"));
delay(500); //wait 0.5seconds
}
void loop() {
if (!client.connected()) {
reconnect();
}
if (millis() > millisNow + sendDelay) {
if (getValues()) {
client.publish(mqttlightReadingpercent, String(lightReadingpercent).c_str(),true);
client.publish(mqttsoilmoisturepercent, String(soilmoisturepercent).c_str(),true);
client.publish(mqtttemp, String(temp).c_str(),true); // the problem is here
client.publish(mqtthum, String(hum).c_str(),true);
millisNow = millis();
}
}
client.loop();
/*if (moisture_level < 10) {
digitalWrite(RELAY_PIN, HIGH); // turn on pump 5 seconds
delay(5000);
}
else {
digitalWrite(RELAY_PIN, LOW); // turn off pump 5 seconds
delay(5000);
}*/
}
By moving your code to getValues, you also changed the scope in which your temp variable exists in. Variables are not automatically globally available. If you declare a variable inside a function (which getValues is), it's only available in this function.
When you try to access the temp variable in your loop function, the compiler rightly tells you, that there is no such variable available.
You could solve the problem by declaring temp as a global variable, which you would do by adding float temp = 0 up on top where you also declare variables like soilMoistureValue. Make sure not to redeclare the variable in getValues then, so instead of declaring like so float temp = dht.readTemperature(); you just assign a new value like so temp = dht.readTemperature();
A quick note on your first paragraph: The voids and bools how you call it, define the return type of a function. If your function does not return anything, you define it as void. If it returns a boolean value (so true or false), you define so bool. In the case of your getValues function, since it does not return anything, it should be void getValues.

Can't get original value after sending by serial port

I have written a simple code for sending int value using bluetooth serial port.
Transmitter:
#include <SoftwareSerial.h>
#include "PWM.hpp"
PWM PWM(2);
SoftwareSerial BTSerial(8,9);
void setup()
{
Serial.begin(9600);
Serial.println("Go");
BTSerial.begin(9600);
BTSerial.write("AT+INQ\r\n");
delay(10000);
BTSerial.write("AT+CONN1\r\n");
delay(100);
PWM.begin(true);
}
void loop()
{
int pwmValue = PWM.getValue();
Serial.println(pwmValue);
BTSerial.write(pwmValue);
delay(100);
}
Output of Serial.println of transmitter part is correct:
1500
but on receiver part isn't. This is the code of receiver:
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(8, 9);
void setup() {
Serial.begin(9600);
BTSerial.begin(9600);
BTSerial.write("AT+NAME=Remote\r\n");
}
void loop() {
if (BTSerial.available()) {
int pwmValue = BTSerial.read();
Serial.println(pwmValue);
}
Incorrect output of Serial.println is:
220
I think the issue is in typecasting.
SoftwareSerial::read is returning a single byte read.
If you examine the expected 1500 in hexadecimal it is 0x05DC, and it's lower byte is 0xDC which is exactly 220 in decimal.
With the multi-byte variant of write() you could use:
BTSerial.write(&pwmValue, sizeof pwmValue);
For receiving you need a loop:
union {
int i;
char c[0];
} pwmValue;
int receivedBytes = 0;
void loop() {
if (BTSerial.available()) {
pwmValue.c[receivedBytes] = BTSerial.read();
receivedBytes++;
if (receivedBytes == sizeof pwmValue) {
Serial.println(pwmValue.i);
receivedBytes = 0;
}
}
}
In documentation https://github.com/PaulStoffregen/SoftwareSerial/blob/master/SoftwareSerial.cpp, you can see that both functions work with uint_8t -- which is guaranteed to have 8 bits (1 byte). That holds up to 256 of value, so 1500 mod 256 is 220.
Looks like the library is prepared to transmit only char-sized data, so you need to convert bigger numbers on both size.
For sending int:
int n = pwmValue;
while (n > 0) {
int digit = n % 10;
n = n / 10;
BTSerial.write(digit);
}
For receiving int:
int n = 0; //future result
int decs = 1;
int temp;
while ((temp = BTSerial.read()) != -1) {
n += temp * decs;
decs *= 10;
}

How to store numbers in Arduino?

I have written this to an Arduino.
char incomingbytea;
char incomingbyteb;
char incomingop;
char result;
void setup()
{
Serial.begin(9600);
}
void loop(){
incomingbytea = 0;
incomingbyteb = 0;
incomingop = 0;
result = 0;
bytea:
if (Serial.available() > 0) {
incomingbytea = Serial.read();
Serial.println("1ok");
Serial.println(incomingbytea);
goto byteb;
}
goto bytea;
byteb:
if (Serial.available() > 0) {
incomingbyteb = Serial.read();
Serial.println("2ok");
Serial.println(incomingbyteb);
goto op;
}
goto byteb;
op:
if (Serial.available() > 0) {
incomingop = Serial.read();
Serial.println("opok");
Serial.println(incomingop);
goto oper;
}
goto op;
oper:
result = incomingbytea + incomingbyteb;
Serial.println(result);
Serial.println(incomingbytea);
Serial.println(incomingbyteb);
Serial.println(incomingop);
}
What I want to do is:
- connect to serial (check)
- collect 2 variables to add/subtract/multiply/divide later (check)
- collect a variable to decide what to do with them 1-add, 2-subtract, etc. (check)
- redirect the script to do the required operation (later)
- print the result to serial (check)
The problem is, when I enter 1 and 1 and 1(whatever, the third one doesn't count now) and I get 98 as a result. Any help? Maybe the variables are wrong?
First you should know the length of the number, and subtract 48 (48 is the ascii representation of 0) later multiply the number for 1, 10, 100, 1000, 10000, ... depending of the position of each number.
For example: String "233" to integer, using custom method
void setup() {
Serial.begin(9600);
}
void loop() {
String Numero1 = "40";
String Numero2 = "50";
double Suma = StringAInt(Numero1)+StringAInt(Numero2);//+ StringAInt(Numero2);
Serial.println(Suma);
}
double StringAInt(String Dato)
{
String Numero = Dato;
char Valores [Numero.length()+1];
Numero.toCharArray(Valores,Numero.length()+1);
double NumeroEnt = 0;
for(int i = 0; i<Numero.length(); i++)
{
int NumValores = Valores[i];
NumValores-=48;
double MultPor = pow(10,Numero.length()-(i+1));
NumeroEnt += (NumValores*MultPor);
//Serial.println(NumValores*MultPor);
}
return NumeroEnt;
}
Now you only need build a string with the data received from serial port, and you can do math simply.