I am trying to receive information from my sensor, however my output is just 0 all the time, is there something wrong in my code? Everything hardware related is done well.
loop()
{
long duration, inches, cm;
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
Serial.print(inches);
Serial.print("in; ");
Serial.print(cm);
Serial.print("cm");
Serial.println();
}
long microsecondsToInches(long microseconds)
{
return microseconds / 74 / 2;
}
long microsecondsToCentimeters(long microseconds)
{
return microseconds / 29 / 2;
}
The sensor you have does not use PWM as a way of sending distance. Rather it uses a serail connection. The issue is that you do NOT have a extra serial hardware on the Arduino.
You could use the arduino's serail port to read the sensors data, but you would not be able to log anything to the screen
The speed at which the serial connection runs is 9600 baud, which is to fast to emulate in software.
I advice you to buy a sensor that uses the standard PWM mode of communication. Doing this will save a several headaches .But I should tell you there is a way. It is using the software serial library. The library will help you use digital pins like they are serail pins.
http://arduino.cc/en/Reference/SoftwareSerial
http://www.suntekstore.com/goods-14002212-3-pin_ultrasonic_sensor_distance_measuring_module.html
http://iw.suntekstore.com/attach.php?id=14002212&img=14002212.doc
You are using code for the Parallax PING, which uses a different protocol from the one you have. Here is a link to the datasheet of your sensor. It outputs through standard serial at 9600bps every 50ms.
After many tries and thanks to the help of John b, this was figured out as the proper answer on how to use this kind of sensor properly, it works exactly as needed, the output being perfectly measured
#include <SoftwareSerial.h>
// TX_PIN is not used by the sensor, since that the it only transmits!
#define PING_RX_PIN 6
#define PING_TX_PIN 7
SoftwareSerial mySerial(PING_RX_PIN, PING_TX_PIN);
long inches = 0, mili = 0;
byte mybuffer[4] = {0};
byte bitpos = 0;
void setup() {
Serial.begin(9600);
mySerial.begin(9600);
}
void loop() {
bitpos = 0;
while (mySerial.available()) {
// the first byte is ALWAYS 0xFF and I'm not using the checksum (last byte)
// if your print the mySerial.read() data as HEX until it is not available, you will get several measures for the distance (FF-XX-XX-XX-FF-YY-YY-YY-FF-...). I think that is some kind of internal buffer, so I'm only considering the first 4 bytes in the sequence (which I hope that are the most recent! :D )
if (bitpos < 4) {
mybuffer[bitpos++] = mySerial.read();
} else break;
}
mySerial.flush(); // discard older values in the next read
mili = mybuffer[1]<<8 | mybuffer[2]; // 0x-- : 0xb3b2 : 0xb1b0 : 0x--
inches = 0.0393700787 * mili;
Serial.print("PING: ");
Serial.print(inches);
Serial.print("in, ");
Serial.print(mili);
Serial.print("mili");
Serial.println();
delay(100);
}
Related
A bit of context, I am participating in the UK CanSat competition. I am sorting out the communication between the CanSat and the ground station. We are using LoRa transceivers as required per the competition. We are using a raspberry pi pico as a emitter and an Arduino nano in the ground station as a receiver.
The LoRa module we are using is this one.
Long story short, when I receive the message in the ground station, there are multiple symbols, here is a picture:
Here is the code for the Arduino (receiver):
// Arduino9x_RX
// -*- mode: C++ -*-
// Example sketch showing how to create a simple messaging client (receiver)
// with the RH_RF95 class. RH_RF95 class does not provide for addressing or
// reliability, so you should only use RH_RF95 if you do not need the higher
// level messaging abilities.
// It is designed to work with the other example Arduino9x_TX
#include <SPI.h>
#include <RH_RF95.h>
#define RFM95_CS 10
#define RFM95_RST 9
#define RFM95_INT 2
// Change to .0 or other frequency, must match RX's freq!
#define RF95_FREQ 433.0
// Singleton instance of the radio driver
RH_RF95 rf95(RFM95_CS, RFM95_INT);
// Blinky on receipt
#define LED 13
void setup() {
pinMode(LED, OUTPUT);
pinMode(RFM95_RST, OUTPUT);
digitalWrite(RFM95_RST, HIGH);
while (!Serial);
Serial.begin(9600);
delay(100);
Serial.println("Arduino LoRa RX Test!");
// manual reset
digitalWrite(RFM95_RST, LOW);
delay(10);
digitalWrite(RFM95_RST, HIGH);
delay(10);
while (!rf95.init()) {
Serial.println("LoRa radio init failed");
while (1);
}
Serial.println("LoRa radio init OK!");
// Defaults after init are 434.0MHz, modulation GFSK_Rb250Fd250, +13dbM
if (!rf95.setFrequency(RF95_FREQ)) {
Serial.println("setFrequency failed");
while (1);
}
Serial.print("Set Freq to: "); Serial.println(RF95_FREQ);
// Defaults after init are 434.0MHz, 13dBm, Bw = 125 kHz, Cr = 4/5, Sf = 128chips/symbol, CRC on
// The default transmitter power is 13dBm, using PA_BOOST.
// If you are using RFM95/96/97/98 modules which uses the PA_BOOST transmitter pin, then
// you can set transmitter powers from 5 to 23 dBm:
rf95.setTxPower(23, false);
}
void loop() {
if (rf95.available()) {
// Should be a message for us now
uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
//char buf = (char*)buf;
uint8_t len = sizeof(buf);
if (rf95.recv(buf, &len)) {
digitalWrite(LED, HIGH);
Serial.print("Got: ");
Serial.println((char*)buf);
Serial.print("RSSI: ");
Serial.println(rf95.lastRssi(), DEC);
} else {
return;
}
}
}
Disclaimer this code was extracted from the internet.
And here is the code for the Raspberry pi pico (emitter):
import board
import busio
import time
import digitalio
import adafruit_rfm9x
import adafruit_bmp280
"Led configuration"
# Led amarillo
ledambar = digitalio.DigitalInOut(board.GP16)
ledambar.direction = digitalio.Direction.OUTPUT
# Led azul
ledazul = digitalio.DigitalInOut(board.GP17)
ledazul.direction = digitalio.Direction.OUTPUT
"LoRa"
# LoRa radio setup
spi = busio.SPI(clock=board.GP2, MOSI=board.GP3, MISO=board.GP4)
cs = digitalio.DigitalInOut(board.GP6)
reset = digitalio.DigitalInOut(board.GP7)
rfm9x = adafruit_rfm9x.RFM9x(spi, cs, reset, 433.0)
print("RFM9x radio ready")
"Not LoRa from here"
"BMP280 Sensor"
# BMP280 comunication start up
i2c = busio.I2C(scl=board.GP15, sda=board.GP14)
bmp280_sensor = adafruit_bmp280.Adafruit_BMP280_I2C(i2c, address=0x76)
# BMP280 sensor readings
def read_temperature():
return bmp280_sensor.temperature
def read_pressure():
return bmp280_sensor.pressure
while True:
ledazul.value = True
"LoRa"
rfm9x.send("Hello World, this is a test, why does this not work? im going mad!!!!")
print("Radio mensage sent")
"Not LoRa from here"
ledazul.value = False
cansat_temperature = read_temperature()
print("TEMPERATURE:")
print(cansat_temperature)
cansat_pressure = read_pressure()
print("PRESSURE:")
print(cansat_pressure)
print(" ")
time.sleep(2.5)
Disclaimer, this code is designed to do more things than just LoRa communication. The LoRa part of the code is below the tag: "LoRa".
If you have any recommendations on how to improve my code in any way, just let me know, it would be really helpful.
Thank you.
I have tried soldering the antennas, changing them, modifying the code, both in the pico and the Arduino, also tried changing the antennas but nothing worked.
You have a buffer over-read - a major security flaw, same as the infamous Heartbleed bug.
When you pass a char * to Serial.println, it will print the data until it finds a null character. Your python string does not contain such null termination, so the the print function keeps going through the memory until it finds one. You were lucky that it found one quite quickly. It could also go on much longer, depending on what is in the memory at that time.
A naive way to fix the issue would be to just append a null character to the python string:
rfm9x.send("Hello World, this is a test, why does this not work? im going mad!!!!\0")
However, if you were to receive partial data (or someone forgot to add a null character), the issue would reappear.
The proper way to fix the problem is to check how much data is received and only print that much. According to the documentation, the received number of octets is stored in the len parameter. Therefore, you can add null-termination on the receiving end like so:
uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
// Leave space for null-termination
uint8_t len = sizeof(buf) - 1;
if (rf95.recv(buf, &len))
{
// Add null-termination at the end of the received data.
buf[len] = '\0';
// Print as before.
digitalWrite(LED, HIGH);
Serial.print("Got: ");
Serial.println((char*)buf);
Serial.print("RSSI: ");
Serial.println(rf95.lastRssi(), DEC);
}
I am trying to retrieve data from an RLS absolute rotary encoder via SPI through Arduino Uno. I have managed to learn the basics of SPI, but I can't seem to get this working. I keep printing the transfer data and keep getting 255.
I also use the recommended pins for Arduino Uno here: https://www.arduino.cc/en/reference/SPI
Here is the link to the Absolute Encoder DataSheet: https://resources.renishaw.com/en/details/data-sheet-orbis-true-absolute-rotary-encoder--97180
Any help is appreciated.
Here is my code I have been trying:
#include <SPI.h>
unsigned int data;
int CS = 10; //Slave Select Pin
// The SS pin starts communication when pulled low and stops when high
void setup() {
Serial.begin(9600);
RTC_init();
}
int RTC_init() {
pinMode(CS, OUTPUT);
SPI.begin();
SPI.setBitOrder(LSBFIRST); // Sets Bit order according to data sheet (LSBFIRST)
SPI.setDataMode(SPI_MODE2); // 2 or 3, Not sure (I have tried both)
digitalWrite(CS, LOW); // Start communications
/*
Commands List:
Command "1" (0x31) – position request (total: 3 bytes) + 4 for multi-turn
Command "3" (0x33) – short position request (total: 2 bytes) + 4 for multi-turn
Command "d" (0x64) – position request + detailed status (total: 4 bytes) + 4 for multi-turn
Command "t" (0x74) – position request + temperature (total: 5 bytes) + 4 for multi-turn
Command "v" (0x76) – serial number (total: 7 bytes)
*/
unsigned int data = SPI.transfer(0x33); // Data
digitalWrite(CS, HIGH); // End communications
return(data);
}
void loop() {
Serial.println(RTC_init());
}
First, you forgot to set your CS pin to output. That won't help.
void setup()
{
Serial.begin(9600);
digitalWrite(CS, HIGH); // set CS pin HIGH
pinMode(CS, OUTPUT); // then enable output.
}
SPI is a two way master/slave synchronous link, with the clock being driven by bytes being sent out by the master. This means that when transacting on SPI, you are expected to send out as many bytes as you want to receive.
As shown on the timing diagram on page 14 of the datasheet, you are expected to send one byte with the command, then as many null bytes as the response requires minus 1.
The diagram shows the clock being low at idle, and input bits being stable when the clock goes low, that's SPI mode 1.
To read the position, for a non-multiturn encoder.
unsigned int readEncoderPos()
{
// this initialization could be moved to setup(), if you do not use
// the SPI to communicate with another peripheral.
// Setting speed to 1MHz, but the encoder can probably do better
// than that. When having communication issues, start slow, then set
// final speed when everything works.
SPI.beginTransaction(SPISettings(1'000'000, MSBFIRST, SPI_MODE1));
digitalWrite(CS, LOW);
// wait at least 2.5us, as per datasheet.
delayMicroseconds(3);
unsigned int reading = SPI.transfer16(0x3300); // 0x3300, since we're sending MSB first.
digitalWrite(CS, HIGH);
// not needed if you moved SPI.beginTransaction() to setup.
SPI.endTransaction();
// shift out the 2 status bits
return reading >> 2;
}
My project is: Read temperature and send it through SMS with 10 min span, and within this span if there is any motion then send SMS "MOTION DETECTED".
so, just for testing i used two LED one for temperate( it will stay on for 10 min) SMS and another for MOTION (it will blink once) and commented function call statement i.e. sendMessage ,sendMsg
everything is working fine but problem is " when i keeping and shaking continuously for a long time my hand in front of the PIR sensor , it continuously detecting motion and may be counter is not increasing therefore dled i.e. 1st one for temp stay on more than 10 min..., but if i keep my hand in front of the PIR sensor for a few sec just to detect Motion( as many time as i want) then its working fine... but for continuous detection something happening for what dled stay on more than 10 min..for example for 30 sec continuous detection dled stay on 10 min 30 sec ...for 1 min dled stay on 11mins..."
this is the problem hope i make you guys make it understandable...
so please help me out.. thanks
here is the code below...
#include <DHT.h> //DHT sensor
#include <SoftwareSerial.h> //this is a constructor for gsm
#include<LiquidCrystal.h> //this is for LCD display
#include "DHT.h"
#define DHTPIN 8 //blue 8 define pins for DHT
#define DHTTYPE DHT11 // DHT11
#define pir 6 //yellow 6
#define pled 13 //for PIR led
#define dled 7 //for DHT led
DHT dht(DHTPIN,DHTTYPE);
int pirState=LOW;
int prival=0;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
SoftwareSerial mySerial(9, 10); //9-->Rx; 10-->Tx
void setup() {
// put your setup code here, to run once:
mySerial.begin(9600);
Serial.begin(9600);
delay(100);
Serial.println("SMS ALERT");
pinMode(pir,INPUT); //set pir pin as input
dht.begin();
lcd.begin(16,2);
pinMode(pled,OUTPUT); //LED for pir sensor... "set pled pin as output"
pinMode(dled,OUTPUT); //LED for DHT sensor... "set dled pin as output"
}
void loop() {
// put your main code here, to run repeatedly:
// block for sending temp information...
float t=dht.readTemperature();
Serial.print("Temperature: ");
Serial.println(t);
Serial.println("SMS INITIATING...");
// SendMessage(t); to sent temp...
/*stay HIGH for 10 min..when loop will end pin will be low i.e. LED will be
off then again for new loop it will be on ..and it will continue... */
digitalWrite(dled,HIGH);
Serial.println("DONE...");
lcd.print("Temp is: ");
lcd.print(t);
lcd.print((char)223);
lcd.print("C ");
delay(500);
//checking pir sensor.. whether motion is detected or not..
//when motion is detected sent msg "MOTION DETECTED"
//and loop will continue for 10 min span
int i=0;
while(i!=600){
prival=digitalRead(pir); //read pir pin = 6
if(prival==HIGH)
{
if(pirState==LOW)
{
Serial.println("Motion detected");
Serial.print("Temp is: ");
Serial.print(t);
Serial.print((char)223);
Serial.println("C");
lcd.setCursor(0,0);
lcd.print("temp is : ");
lcd.print(t);
lcd.print(char(223));
lcd.print("C");
lcd.setCursor(0,1);
lcd.print("Motion Detected");
/*when motion is detected only that time LED will be on.. and stay
high for 200mSec then it will be off i.e. it will blink for once */
digitalWrite(pled,HIGH);
delay(200);
digitalWrite(pled,LOW);
Serial.println("SMS INITIATING FOR MOTION...");
//sendMsg(); to send "motion detected msg"
Serial.println("DONE...");
pirState=HIGH;
}
}
else
{
if(pirState==HIGH)
{
Serial.println("Motion stopped ");
Serial.print("Temp is: ");
Serial.print(t);
Serial.print((char)223);
Serial.println("C");
lcd.setCursor(0,0);
lcd.print("temp is : ");
lcd.print(t);
lcd.print(char(223));
lcd.print("C");
lcd.setCursor(0,1);
lcd.print("Motion stopped ");
pirState=LOW;
}
}
i++;
delay(1000);
}
digitalWrite(dled,LOW);
delay(500);
}
/*
void SendMessage(float t )
{
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=\"XXXXXXXXXX\"\r"); // Replace x with mobile number
delay(1000);
mySerial.println("TEMP IS : ");// The SMS text you want to send
mySerial.println(t);
delay(100);
mySerial.println((char)26);// ASCII code of CTRL+Z
delay(1000);
}
void sendMsg(){
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=\"XXXXXXXXXX\"\r"); // Replace x with mobile number
delay(1000);
mySerial.println("MOTION DETECTED...");// The SMS text you want to send
delay(100);
mySerial.println((char)26);// ASCII code of CTRL+Z
delay(1000);
}
*/
The problem is that your code is written in a blocking fashion using delay(500); and so on. You execute the PIR sensing 10 * 60 times and delay(1000); each, thus you expect 10 mins delay for the LED toggle. However, the inner delay(200); will lengthen the time spent inside the PIR loop, as you noticed.
You can address this problem in multiple ways, but the easiest would be to do LED events asynchronously using a global timeout timer. You set the timeout timer to 10 mins, turn the LED on and then after 10 mins, your timer interrupt calls the relevant timeout service routine which turns the LED off. Same goes for the second LED.
Your project might in general benefit from using some kind of RTOS instead of writing plain Arduino code.
I have this RFID reader "Rosslare AY-X12", and it's working with Wiegand 26bit. I have an arduino mini Pro and connected together it's working fine but it only reads the card one time and then I have nothing.
When I put on the card arduino reads that card but only one time during the card is near by the reader and it again reads that card when I put off the card and then I put on. But I want to read that card continuously, I mean when the card is near by the Reader still reading the card, every 1ms reads that card.
Do you have any idea how to do that ? Is there any RFID arduino library which can do that? I had got the Mifare and its can do that. But this 125Khz reader which can communicate over Wiegand can't do that or I don't know how to do that.
I'm using this library : https://github.com/monkeyboard/Wiegand-Protocol-Library-for-Arduino
My previous answer was deleted. I am going to make another attempt to answer the questions.
Do you have any idea how to do that ?
This cannot be done by Arduino because Arduino in your case is just reading the D0 and D1 pulses from your RFID reader. Since your RFID reader Rosslare AY-X12 does not send out continuous output of wiegand protocol, there is no way Arduino can read more than what was not sent to it.
The common RFID readers will not send continuous data of the same card because in the common use case (entry/exit/attendance), normally one tap is to check-in and another tap is to check-out. If the RFID reader sends continuous data of the same card, the main system receiving the multiple wiegand data will be confused and will not be able to determine if the user actually wish to check-in or check-out.
Is there any RFID arduino library which can do that?
No. There is no such RFID Arduino library. If the RFID reader is not sending out continuous data, there is no way the receiver (Arduino) can receive them.
Is there a way to achieve this?
Yes, there are some readers that has the option to turn on the continuous output of data, for example 714-52 Mifare® ID Reader with selectable outputs. In its specification :
Continuous output with tag in field or single transmission
With this reader configured to continuous output, you can then use Arduino and the monkeyboard wiegand library to read the data.
I wrote my own wiegand code. Its not that difficult. I attached interrupts to the data pins and when they change I log the zero or one. You then build up the binary string and once timed out because no bits coming in. Then you convert the binary to decimal.
#include <LiquidCrystal.h>
int data0 = 2; //set wiegand data 0 pin
int data1 = 3; //set wiegand data 1 pin
unsigned long bit_holder; //unsigned long (positive 32 bit number)
unsigned long oldbit = 0;
volatile int bit_count = 0;
LiquidCrystal lcd(8, 9, 10, 11, 12, 13);
unsigned long badge;
unsigned int timeout;
unsigned int t = 800;
void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
lcd.print("Present Badge");
delay(2);
Serial.println("Present Badge");
pinMode(data0, INPUT);
digitalWrite(data0, HIGH);
pinMode(data1, INPUT);
digitalWrite(data1, HIGH);
attachInterrupt(0, zero, FALLING); //attach interrupts and assign functions
attachInterrupt(1, one, FALLING);
}
void zero(){
bit_count ++;
bit_holder = (bit_holder << 1) + 0; //shift left one and add a 0
timeout = t;
}
void one(){
bit_count ++;
bit_holder = (bit_holder << 1) + 1; //shift left one and add a 1
timeout = t;
}
void loop() {
timeout --;
if (timeout == 0 && bit_count > 0){
lcd.clear();
lcd.print("Dec:");
lcd.print(bit_holder);
lcd.setCursor(0,1);
lcd.print("Hex:");
lcd.print(String(bit_holder,HEX));
Serial.print("bit count= ");
Serial.println(bit_count);
Serial.print("bits= ");
Serial.println(bit_holder,BIN);
oldbit = bit_holder; //store previous this value as previous
bit_count = 0; //reset bit count
bit_holder = 0; //reset badge number
}
}
You may need to find a reader that offer a continuously reading, as I know almost of Wiegand Reader in the market can't perform a continuously reading because they have a "onboard" control that controls this...
Maybe you can try with Arduino Serial RFID Reader...
try a this timer libary Timer1 and mayby try this code it worked for me, my tags and cards now reads continuously.
Greetings from Denmark
Gregor
#include <Timer1.h>
//******************************************************************
// ATmega168, ATmega328:
// - Using Timer 1 disables PWM (analogWrite) on pins 9 and 10
// ATmega2560:
// - Using Timer 1 disables PWM (analogWrite) on pins 11 and 12
// - Using Timer 3 disables PWM (analogWrite) on pins 2, 3 and 5
// - Using Timer 4 disables PWM (analogWrite) on pins 6, 7 and 8
// - Using Timer 5 disables PWM (analogWrite) on pins 44, 45 and 46
//******************************************************************
unsigned int lastTime;
#include <SoftwareSerial.h>
SoftwareSerial RFID = SoftwareSerial(2,4);
char character;
String our_id;
void setup()
{
// Disable Arduino's default millisecond counter (from now on, millis(), micros(),
// delay() and delayMicroseconds() will not work)
disableMillis();
// Prepare Timer1 to count
// On 16 MHz Arduino boards, this function has a resolution of 4us
// On 8 MHz Arduino boards, this function has a resolution of 8us
startCountingTimer1();
lastTime = readTimer1();
Serial.begin(9600);
RFID.begin(9600);
}
void loop()
{
unsigned int now = readTimer1();
while (RFID.available()>0)
{
character = RFID.read();
our_id += character;
lastTime = now;
}
if (our_id.length() > 10) {
our_id = our_id.substring(1,13);
Serial.println(our_id);
our_id = "";
}
delay(1000);
}
I'm trying to display a potentiometer's value on an Adafruit ST7565 GLCD. My serial monitor is giving me values between 1.62-1.67, while the GLCD ranges from -20,000 to +20,000. I'm not sure whether the arithmetic/data type is wrong or whether I am allocating memory improperly for the "sprintf" conversion.
#include "ST7565.h"
#include "stdlib.h"
char buffer[5];
int ledPin = 13; // LED connected to digital pin 13
char str[8];
// the LCD backlight is connected up to a pin so you can turn it on & off
#define BACKLIGHT_LED 10
// pin 9 - Serial data out (SID)
// pin 8 - Serial clock out (SCLK)
// pin 7 - Data/Command select (RS or A0)
// pin 6 - LCD reset (RST)
// pin 5 - LCD chip select (CS)
ST7565 glcd(9, 8, 7, 6, 5);
#define LOGO16_GLCD_HEIGHT 16
#define LOGO16_GLCD_WIDTH 16
void setup() {
Serial.begin(9600);
// turn on backlight
pinMode(BACKLIGHT_LED, OUTPUT);
digitalWrite(BACKLIGHT_LED, HIGH);
// initialize and set the contrast to 0x18
glcd.begin(0x18);
glcd.display(); // show splashscreen
delay(3000);
glcd.clear();
Serial.println(" ");
digitalWrite(BACKLIGHT_LED, HIGH);
glcd.drawstring(0,0," ");
glcd.display();
glcd.clear();
}
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage);
digitalWrite(BACKLIGHT_LED, HIGH);
Serial.println(voltage);
sprintf(str,"%d",voltage); // converts to decimal base.
glcd.drawstring(0,0,str);
glcd.display();
delay(500);
glcd.clear();
}
Any insight is appreciated. I don't have much formal programming experience, so linking a tutorial about data types won't be of any use. I need to see a specific example like this worked out to truly understand.
You used %d to print out a float; this is undefined behaviour (in your case, it probably dumped out the integer representation of some part of the float's bit sequence).
Instead of using sprintf (since sprintf(..., "%f", val) is reportedly broken on Arduino), use dtostrf:
dtostrf(voltage, 0, 2, buf);
Also, if you're interested, you can see how Arduino prints floats here.