How to print a number on with HT1632 only accepting text - arduino

I just bought a 8x32 lattice board (led matrix) and I control it with Arduino. The problem is that I can only use text with the library I got on github. But not numbers, how can I do it?
I'm going to put the code below, the code of the scrolling text and the part of the code in the library that specifies the function used to set the text.
The arduino code that program the scrolling text is here:
#include <HT1632.h>
#include <font_5x4.h>
#include <images.h>
int i = 0;
int wd;
char disp[] = "Hello, how are you?";
int x = 10;
void setup() {
HT1632.begin(A5, A4, A3);
wd = HT1632.getTextWidth(disp, FONT_5X4_END, FONT_5X4_HEIGHT);
}
void loop() {
HT1632.renderTarget(1);
HT1632.clear();
HT1632.drawText(disp, OUT_SIZE - i, 2, FONT_5X4, FONT_5X4_END,
FONT_5X4_HEIGHT);
HT1632.render();
i = (i + 1) % (wd + OUT_SIZE);
delay(100);
}
The library code that specifies the printing of the text is this:
void HT1632Class::drawText(const char text[], int x, int y, const byte font[],
int font_end[], uint8_t font_height,
uint8_t gutter_space) {
int curr_x = x;
char i = 0;
char currchar;
// Check if string is within y-bounds
if (y + font_height < 0 || y >= COM_SIZE)
return;
while (true) {
if (text[i] == '\0')
return;
currchar = text[i] - 32;
if (currchar >= 65 &&
currchar <=
90) // If character is lower-case, automatically make it upper-case
currchar -= 32; // Make this character uppercase.
if (currchar < 0 || currchar >= 64) { // If out of bounds, skip
++i;
continue; // Skip this character.
}
// Check to see if character is not too far right.
if (curr_x >= OUT_SIZE)
break; // Stop rendering - all other characters are no longer within the
// screen
// Check to see if character is not too far left.
int chr_width = getCharWidth(font_end, font_height, currchar);
if (curr_x + chr_width + gutter_space >= 0) {
drawImage(font, chr_width, font_height, curr_x, y,
getCharOffset(font_end, currchar));
// Draw the gutter space
for (char j = 0; j < gutter_space; ++j)
drawImage(font, 1, font_height, curr_x + chr_width + j, y, 0);
}
curr_x += chr_width + gutter_space;
++i;
}
}

You need to look at snprintf. This allows you to format a string of characters just like printf. It allows you to convert something like a int into a part of a string.
an example:
int hour = 10;
int minutes = 50;
char buffer[60];
int status = snprintf(buffer, 60, "the current time is: %i:%i\n", hour, minutes);
buffer now contains:"the current time is: 10:50" (and several empty characters past the \0).

Related

Float variable to HEX in Arduino

I want to convert my float variables into HEX value like 0x00466 or etc. but when I try all the things that I saw in the internet my Serial Console just turns out crazy :D like "' #gA".
I tried this code below
float gyrox, gyroy, gyroz, accelx, accely, accelz, enlem, boylam, sicaklik, yukseklik, basinc;
byte ByteArray[11];
void setup() {
Serial.begin(9600);
gyrox = 1.5;
gyroy = 2.5;
gyroz = 2.0;
accelx = 5.3;
accely = 3.2;
accelz = 6.1;
enlem = 39.9250506;
boylam = 32.8369756;
sicaklik = 35.0;
yukseklik = 103.0;
basinc = 65.31455;
ByteArray[0]=(gyrox,HEX);
ByteArray[1]=(gyroy,HEX);
ByteArray[2]=(gyroz,HEX);
ByteArray[3]=(accelx,HEX);
ByteArray[4]=(accely,HEX);
ByteArray[5]=(accelz,HEX);
ByteArray[6]=(enlem,HEX);
ByteArray[7]=(boylam,HEX);
ByteArray[8]=(sicaklik,HEX);
ByteArray[9]=(yukseklik,HEX);
ByteArray[10]=(basinc,HEX);
}
void loop() {
Serial.println((char*)ByteArray);
}
and the result is ""(:D) I want the result like "0x000466 or anything likte HEX value" so what should I do?
You can cast the float to an array of bytes to get its internal representation. Then you can loop over all of the bytes and print each of them individually.
void printFloat(float const f)
{
// cast the float to an array of bytes
uint8_t const * const byteArray = (uint8_t const *)&f;
// print the start
Serial.print("0x");
// loop over the bytes, sizeof(f) tells us how many bytes make up the float
for (size_t idx = 0; idx != sizeof(f); ++idx)
{
// get the byte for this position
uint8_t const b = byteArray[idx];
// print a zero if b < 16,
// https://stackoverflow.com/questions/19127945/how-to-serial-print-full-hexadecimal-bytes
Serial.print(b>>4, HEX);
Serial.print(b&0x0F,HEX);
}
}
A float is 32 bits long (4 bytes). You can try this:
float f;
Serial.print("0x"); Serial.print(*(uint32_t*)&f, HEX);
If you really need leading zeroes, try this:
void hex_print(uint32_t x)
{
Serial.print("0x");
for (uint32_t mask = 0x0FFFFFFFul; mask && mask > x; mask >>= 4)
Serial.print('0');
Serial.print(x, HEX);
}
// calling as:
float f = 123.456f;
hex_print(*(uint32_t*)&f);

Arduino - How to convert double to HEX format

I have an arudino code where I get some temperature reading:
double c1 = device.readCelsius();
Serial.println(c1);
The output is for example: 26.23
What I need is to get this converted to 2623 and then to HEX value so I get: 0x0A3F
Any clue?
I guess your float values always get numbers up to two decimal. So, you can just multiply the value which you read from sensor with a 100.
decimalValue = 100 * c1
And then you can use this small code for converting the decimal value to HEX.
Thanks to GeeksforGeeks
You can find the full tutorial here
// C++ program to convert a decimal
// number to hexadecimal number
#include <iostream>
using namespace std;
// function to convert decimal to hexadecimal
void decToHexa(int n)
{
// char array to store hexadecimal number
char hexaDeciNum[100];
// counter for hexadecimal number array
int i = 0;
while (n != 0) {
// temporary variable to store remainder
int temp = 0;
// storing remainder in temp variable.
temp = n % 16;
// check if temp < 10
if (temp < 10) {
hexaDeciNum[i] = temp + 48;
i++;
}
else {
hexaDeciNum[i] = temp + 55;
i++;
}
n = n / 16;
}
// printing hexadecimal number array in reverse order
for (int j = i - 1; j >= 0; j--)
cout << hexaDeciNum[j];
}
// Driver program to test above function
int main()
{
int n = 2545;
decToHexa(n);
return 0;
}

Character Arithmetic using only the Alphabet (A or a ...) in order

I am learning programming on my own at home. I'm interested in C right now and so, this is my first question. I have been trying to figure out why my code is not printing the right answer but I'm not sure what is wrong. I will attach the question and my code below. If some could help me figure out what I am doing wrong I'd be really grateful.
"Write a program that takes a string and displays it, replacing each of its
letters by the letter 13 spaces ahead in alphabetical order.
'z' becomes 'm' and 'Z' becomes 'M'. Case remains unaffected.
The output will be followed by a newline.
If the number of arguments is not 1, the program displays a newline."
I'm using command line arguments to read in a string "My horse is Amazing." and the expected output should be "Zl ubefr vf Nznmvat." but I am getting this as my output "Zå ubeÇr vÇ Nznçvat."
This is my code:
#include <stdio.h>
#include <string.h>
int main(int argc, char **argv[]){
char ch, str[100], newStr[100];
int i, len;
if(argc != 2){
printf("\n");
return (-1);
}
strcpy(str, argv[1]);
len = strlen(str);
printf("%s %d\n\n", str, len);
for (i = 0; i < len; i++)
{
ch = str[i];
if ((ch >= 65) && (ch <= 90)){
ch = ch + 13;
if(ch > 90){
ch = ch - 90;
ch = ch + 64;
}
}else if ((ch >= 97) && (ch <= 122)){
ch = ch + 13;
if(ch > 122){
ch = ch - 122;
ch = ch + 96;
}
}
newStr[i] = ch;
}
printf("%s \n", newStr);
return 0;
}
ch is a signed 1-byte variable, meaning it can only represent values between -128 and 127. Adding 13 to y results in a value outside of that range.

how to send 100 digit in serial communication from processing to arduino

i am converting pixel array to String and send this String to arduino. but i Think this String is not converted properly because Serial.write send (8 bit or 8 character) i don’t know. and also want to send 100 character of string into Serial .
please send your suggestion and getting help me out of this problem.
for any mistake Sorry in advance.
for(int x =0 ; x < img.height; x++)
{
for(int y=0; y <img.width; y++)
{
int i = x+y*width;
if(img.pixels[i] == color(0,0,0))
{
i=1;
}
else
{
i=0;
}
String s = str(i);
print(s);
Serial.write(s);
delay(2);
}
}
and also tell me how to stop string after 100 character by not using ("\n" or "\r" )
It seems you are looking for the code below:
for (int x = 0; x < img.height; x++) { // iterate over height
for (int y = 0; y < img.width; y++) { // iterate over width
int i = x + y * width;
if (img.pixels[i] == color(0, 0, 0)) { // determine if zero
Serial.write('1'); // send non zero char
} else {
Serial.write('0'); // send zero char
}
}
Serial.write("\n\r");
}
If you want to cluster your output in units the size of img.width you could do this:
for (int x = 0; x < img.height; x++) { // iterate over height
String s;
for (int y = 0; y < img.width; y++) { // iterate over width
int i = x + y * width;
if (img.pixels[i] == color(0, 0, 0)) { // determine if zero
s += '1'; // append a non zero char to string s
} else {
s += '0'; // append a zero char to string s
}
}
Serial.println(s);
}
Please remember:
Serial.write outputs raw binary value(s).
Serial.print outputs character(s).
Serial.println outputs character(s) and appends a newline character to output.
I have serious doubts about this calculation int i = x+y*width; as your data is probably structured as:
vertical data: 0 1 2
horizontal data: [row 0][row 1][row 2]
Instead of:
horizontal data: 0 1 2
vertical data: [column 0][column 1][column 2]

Get 3 Values from processing to Arduino

I have a color tracking program in Processing, which works with a Kinect. When I click somewhere in the picture it saves this color and draws an ellipse around it. I just want to send 3 int values (one for red, green and blue) over myPort.write() to Arduino and save these 3 values in Arduino in 2 variables. My goal is to light a red LED if the red variable is the highest, and the green LED if green is the highest and so on.
I've tried several examples I found whiel googling, but nothing works. I don't know how Arduino should get the correct values in the variables!
EDIT: Here you have my Processing code. I glued it together from several other tutorials until I nearly cried..
import processing.serial.*;
Serial myPort;
import SimpleOpenNI.*;
SimpleOpenNI kinect;
// Frame
PImage currentFrame;
color trackColor;
int r1, g1, b1, r2, g2, b2;
void setup()
{
size(640, 480);
String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
myPort = new Serial(this, portName, 9600);
kinect = new SimpleOpenNI(this);
kinect.enableRGB();
trackColor = color (255, 0, 0);
smooth ();
currentFrame = createImage (640, 480, RGB);
}
void draw()
{
kinect.update();
currentFrame = kinect.rgbImage ();
image(currentFrame, 0, 0);
currentFrame.loadPixels();
// Before we begin searching, the "world record" for closest color is set to a high number that is easy for the first pixel to beat.
float worldRecord = 500;
// XY coordinate of closest color
int closestX = 0;
int closestY = 0;
// Begin loop to walk through every pixel
for (int x = 0; x < currentFrame.width; x ++ ) {
for (int y = 0; y < currentFrame.height; y ++ ) {
int loc = x + y*currentFrame.width;
// What is current color
color currentColor = currentFrame.pixels[loc];
r1 = (int)red(currentColor);
g1 = (int)green(currentColor);
b1 = (int)blue(currentColor);
r2 = (int)red(trackColor);
g2 = (int)green(trackColor);
b2 = (int)blue(trackColor);
// Using euclidean distance to compare colors
float d = dist(r1, g1, b1, r2, g2, b2); // We are using the dist( ) function to compare the current color with the color we are tracking.
// If current color is more similar to tracked color than
// closest color, save current location and current difference
if (d < worldRecord) {
worldRecord = d;
closestX = x;
closestY = y;
}
}
}
// We only consider the color found if its color distance is less than 10.
// This threshold of 10 is arbitrary and you can adjust this number depending on how accurate you require the tracking to be.
if (worldRecord < 10) {
// Draw a circle at the tracked pixel
fill(trackColor);
strokeWeight(4.0);
stroke(0);
ellipse(closestX, closestY, 30, 30);
}
if (mousePressed == true) {
color c = get(mouseX, mouseY);
//println("r: " + red(c) + " g: " + green(c) + " b: " + blue(c));
// Save color where the mouse is clicked in trackColor variable
int loc = mouseX + mouseY*(currentFrame.width);
trackColor = currentFrame.pixels[loc];
println("red " + r2);
println("green " + g2);
println("blue " + b2);
int colors[] = {r2, g2, b2};
for(int i=0; i < 3; i++) {
myPort.write(colors[i]);
}
}
println("ClosestX " + closestX);
myPort.write(closestX);
}
And my Arduino Code, where I don't know how to get several values.
int val;
int ledPin = 13;
int freq;
int piezoPin = 9;
int redLED = 3;
int greenLED = 5;
int blueLED = 7;
int red, green, blue;
void setup() {
pinMode(ledPin, OUTPUT); // Set pin as OUTPUT
Serial.begin(9600); // Start serial communication at 9600 bps
digitalWrite(ledPin, LOW);
}
void loop() {
if (Serial.available() > 0)
{ // If data is available to read,
val = Serial.read(); // read it and store it in val
}
if(red > green && red > blue) {
digitalWrite(redLED, HIGH); //light Red LED
}
if(green > red && green > blue) {
digitalWrite(greenLED, HIGH); //light Red LED
}
if(blue > red && blue > green) {
digitalWrite(blueLED, HIGH); //light Red LED
}
//Piezo buzzing higher when X-Position of tracked color is higher.
if (val < 100) {
freq = 50;
}
else if (val < 200) {
freq = 200;
}
else if (val < 300) {
freq = 400;
}
else if (val < 400) {
freq = 600;
}
else if (val < 500) {
freq = 800;
}
else (freq = 1000);
tone(piezoPin, freq);
}
EDIT2: Yes, additionally to lighing the LEDs I also want to have a sound from a piezo buzzer, but that works pretty well, so no questions on that... yet.
Help, please!!
Serial communication to your arduino works with a single byte at a time.
As luck would have it, the three components of a Processing Color are also three bytes.
One for red(0-255)
One for green(0-255)
One for blue(0-255)
Now all we need is a little more info so we can keep them separate.
Because a byte's minimum and maximum values are 0-255, there's no safe character we can use to keep track of the three different bytes, so we need a way to figure out where the info we send begins and ends.
An easy way to do this, is to set up a header and a footer for your messages ; something like :
<color>[byte (red)][byte (green)][byte (blue)]</color>
If we are going to read and decipher messages formatted like this, we are going to need a little buffer that will store the values we receive from Processing, so we can read them back and see if we can match the message format.
So, on the Arduino side, we need this :
String buffer = "";
String messageBegin = "<color>";
String messageEnd = "</color>";
//we read our serial data in the SerialEvent() function
//this is called *after* a loop(), and only if there is serial data in the buffer.
void serialEvent()
{
while(Serial.available())
{
buffer += (char)Serial.read();
}
}
void loop()
{
//now, inside loop, we no longer need to worry about gathering data from serial.
//we do still need to figure out if our message is complete, and then parse it.
//if our buffer contains both the beginning and the end of a message
//in the right order.
int beginIndex = buffer.lastIndexOf(messageBegin);
int endIndex = buffer.lastIndexOf(messageEnd);
if(beginIndex != -1 && endIndex != -1 && beginIndex < endIndex)
{
//we have a complete message!
//our red color starts 7 characters after where the message begins,
//because our "messageBegin" is 7 characters long
string lastMessage = buffer.substring(beginIndex+7);
//this is arguably not the prettiest way to get our byte values back.
//see if you can do better for bonus points!
byte messageAsBytes[80];
lastMessage.getBytes(messageAsBytes, messageAsBytes.length());
//we can now finally reconstruct the value we had from processing!
byte r = (byte)messageAsBytes[0];
byte g = (byte)messageAsBytes[1];
byte b = (byte)messageAsBytes[2];
//if we get a complete message, we can clear our buffer. (don't forget to do this!)
buffer = "";
}
}
On the processing side, all we need to do is make sure our messagebegin and messageend are sent along for the ride :
myPort.write("<color">);
for(int i=0; i < 3; i++) {
myPort.write(colors[i]);
}
myPort.write("</color">);

Resources