Trying to get my own printf function to work with variables - function

I am programming a display and I am able to display characters on the display by using this function:
void printChar(char *tekst, uint16_t xPos, uint16_t yPos)
{
//calculate the position the first byte should be placed on
uint16_t startPos = yPos * width_disp_byte + (xPos/8);
int i;
//put all 16 bytes on the right place on the display based on the users' input
for(i=0;i<16;i++)
{
test_image[startPos]=convertChar(*tekst,i);
startPos += width_disp_byte;
}
}
Basically I get a character and find its location in an array that I build. Than I take 16 bytes of data and put this in the display.
The next step is to display integer variables on the display. I have written a code that looks like this:
void printVariable(uint16_t integer, uint16_t xPos, uint16_t yPos)
{
uint16_t value;
uint16_t remainder;
char printValue;
//max value is 9999 that can be displayed, caused by the '4' in the for loop
for(int i = 0; i < 4;i++)
{
value = integer;
//int_power calculates the divisor. going from 3 to 0. cq 1000,100,10,1.
value /= int_power(10,(3-i));
//remove highest number from integer value (for 312, remove the 3 by substracting 300)
integer -= (value) * (int_power(10,(3-i)));
// add '0' to value to get the correct ASCII value.
value += '0';
// convert uint16_t value into char
printValue = value;
printChar(printValue,xPos,yPos);
xPos += 8;
}
}
I take a variable, lets say 3164. The first step is to divide this by 1000. The answer will be 3, since it's an integer. I display this character using the printChar function.
the next step removes 3000 from 3164 and divides the value by 100, resulting in 1. Again this value is printed using the printf function. Then 100 is removed from from 164 and then gets divided by 10 etc etc.
This code is quite limited in its use, but it fits perfectly in what I want to achieve. There is no need to print variables within a string.
The problem here is that the printChar function does not work like I have written in the code. Normally I would use the printChar function like this:
printChar("F",0,0);
This would print the character F in the topleft corner. If I want to use the printChar function like this, it doesn't work:
printChar(printValue,xPos,yPos);
The warning message says:
incompatible integer to pointer conversion passing 'char' to parameter of type 'char *'; take the address with &
If I take the address with & I don't get the correct value displayed on my display.
How can I fix this?

You only want to print ONE character, so you do not need a pointer as parameter. Your function would work like this:
void printChar(char tekst, uint16_t xPos, uint16_t yPos){
...
//depending on the Parameters of your convertChar- function either
... = convertChar(tekst,i); // if you can modify this function too
... = convertChar(&tekst,i); // if the function is to use as it is
}
The difference is in char tekst instead of char * text

Related

Parameter Passing By Value Result & Name

I am trying to understand how the concepts of parameter passing by Value Result and parameter passing by Name would apply to the following program:
// GLOBAL variables
int num[10] = {0,0,0,0,0,0,0,0,0,0}; // Subscripts start at 0 as in C++
int index = 1;
void somefun(int alpha, int beta)
{
alpha = 7;
num[index] = 33;
index = index - 6;
num[alpha] = 44;
beta = 55;
}
void main()
{
somefun( index, num[index + 4] ); // Function Call
}
This program is pseudo-code, not specific to any language, and the array subscripts start at 0.
If someone could help me understand how this program would work with parameter passing by Value Result and parameter passing by Name, I would greatly appreciate it. Thank you.
Unfortunately, I was not able to try anything on my own thus far.

Using I2C_master library AVR

I am using I2C_master library for AVR, Communication works fine, but I have little problem, how can I get data.
I am using this function
uint16_t i2c_2byte_readReg(uint8_t devaddr, uint16_t regaddr, uint8_t* data, uint16_t length){
devaddr += 1;
if (i2c_start(devaddr<<1|0)) return 1;
i2c_write(regaddr >> 8);
i2c_write(regaddr & 0xFF);
if (i2c_start(devaddr<<1| 1)) return 1;
for (uint16_t i = 0; i < (length-1); i++)
{
data[i] = i2c_read_ack();
}
data[(length-1)] = i2c_read_nack();
i2c_stop();
return 0;}
And now I need to use received data, and send it by UART to PC
uint8_t* DevId;
i2c_2byte_readReg(address,REVISION_CODE_DEVID,DevId,2);
deviceH=*DevId++;
deviceL=*DevId;
UART_send(deviceH);
UART_send(deviceL);
I think that I am lost with pointers. Could you help me, how can I get received data for future use? (UART works fine for me in this case, but it sends only 0x00 with this code)
The function i2c_2byte_readReg takes as a third argument a pointer to the buffer where the data will be written. Note that it must have size bigger than the forth argument called length. Your DevId pointer doesn't point to any buffer so when calling the function you've got an access violation.
To get the data you should define an array before calling the function:
const size_t size = 8;
uint8_t data[size];
Then you can call the function passing the address of the buffer as an argument (the name of the array is converted into its address):
const uin16_t length = 2;
i2c_2byte_readReg(address, REVISION_CODE_DEVID, data, length);
Assuming that the function works well those two bytes will be saved into data buffer. Remember that size must be bigger or equal to length argument.
Then you can send the data over UART:
UART_send(data[0]);
UART_send(data[1]);

Can someone explain this code for me? Base-Conversion Code

So for a homework assignment we had to make a program that converted a number from one base to another (i.e. 110 in base 2 to 6 in base 10). I asked my friend how he did his because I was having trouble and he just sent me his code and nothing else. Can someone explain the logic of this code so that I can make my own program and actually understand how to do this problem. Thanks!
import java.util.*;
public class Base_Converter {
public static final String value = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static void main(String args[]){
int x, y;
String num, base10 = "";
Scanner scan = new Scanner(System.in);
System.out.println("Enter a number you want to convert.");
num = scan.nextLine();
num = num.toUpperCase();
System.out.println("What base is it in?");
x = scan.nextInt();
System.out.println("What base do you want to convert it to?");
y = scan.nextInt();
if(x <= 36 && y <= 36 && x > 1 && y > 1){
base10 = toBase10(num,x);
num = newBase(base10,y);
System.out.println(num);
}
}
public static String toBase10(String num, int from){
long total = 0;
int counter = num.length();
char[] stringArray = num.toCharArray();
for(char w : stringArray){
counter--;
total += value.indexOf(w)*Math.pow(from,counter);
}
return String.valueOf(total);
}
public static String newBase(String num, int to){
String total = "";
int current = 0;
while(Integer.valueOf(num) > 0){
current = Integer.valueOf(num)%to;
total = value.charAt(current)+total;
num = String.valueOf(Integer.valueOf(num)/to);
}
return total;
}
}
I think you should be focusing not on what your friend's code does, but instead with how to do the assignment yourself, because I think your problems lie with a lack of understanding on your part. Instead of leaving you high and dry though I'll walk you through some of the specifics of base-conversion.
First, read user input. It looks like you're using Java, so just use a scanner to do this. At minimum you'll want to read the number you're converting, what base it is in, and what base the output will be in.
Next, we want to convert the number. You could directly convert numbers to each other (i.e. converting base 2 to base 8) but that requires more brainpower than I am willing to offer right now. Instead, I would suggest always first converting the user-inputted number to base 10 (much like your friend did). So how do we convert a number of an unknown base to base 10?
So let's break down how a number is represented: lets say we have the number 234 in base ten. This is equivalent to 4*10^0 + 3*10^1 + 2*10^2 or 4 + 30 + 200 = 234. You can use this same conversion for any other numbers. I.E. if the number is 1763 in base 8, the value in base 10 will be 3*8^0 + 6*8^1 + 7*8^2 + 1*8^3 or 3 + 48 + 448 + 512 = 1011 base 10(try entering 1763 here for proof. So to convert to decimal, you just need to see to multiply each individual number time your base to the power of its place minus 1. For example, since 1 is the fourth number in the 1763 you multiply it times 8^(4-1). Since, you are reading a string from the user. You'll need to convert each character of the string to an integer using the ascii chart.
Now to convert from base ten to anything. Instead of multiplying, you just divide each value and write the remainder! I'll let someone else describe this procedure.
Now just store this new value as a string doing somethings like
String output = "";
output += newValue;
In computer science, just copying someone else's code is way more harmful than helpful. Hope this helps!

Getting a MySQL Query to save as a global Variable is C

I am having issues getting a function to run and having the results of a MySQL query to be saved as a variable that other functions can use and call upon. I know the results get read from the table as a string. I was able to do this fine when getting the results and converting it to a float and then passing the results to a pointer. But I can not seem to figure out how to get the results as a string, and compare it with another string to see if they match or do not. No matter what I have tried to do, I can not seem to get a value to be saved as a string to a variable outside the function.
Here is the code of how I got it to work as a float:
(Outside the main function)
float temperature_reading;
float *p_temperature_reading= &temperature_reading;
float humidity_reading;
float *p_humidity_reading= &humidity_reading;
The function I have working with the float, that I can save to a global variable
void MIA_get_current_temperature()
{
const char *query = "SELECT Temperature, Humidity FROM `temperature` WHERE Type='Current_Temperature'";
if (mysql_query(conn, query) != 0)
{
fprintf(stderr, "%s\n", mysql_error(conn));
exit(-1);
} else {
MYSQL_RES *query_results = mysql_store_result(conn);
if (query_results)
{ // make sure there *are* results..
MYSQL_ROW row;
while((row = mysql_fetch_row(query_results)) !=0)
{
float f = row[0] ? atof(row[0]) : 0.0f;
float h = row[1] ? atof(row[1]) : 0.0f;
*p_temperature_reading = f;
*p_humidity_reading = h;
printf("The Temp & Hum from DB is: %.1f & %.1f\n", *p_temperature_reading,*p_humidity_reading);
}
/* Free results when done */
mysql_free_result(query_results);
}
}
}
This is the function I can not get to work:
(Outside main Function)
char ac_mode[256];
char *p_ac_mode = &ac_mode[256];
Function:
void MIA_get_desired_temperature()
{
const char *query = "SELECT Mode, Desired_Temperature, Threshold FROM `ac_mode` WHERE Status='ON'";
if (mysql_query(conn, query) != 0)
{
fprintf(stderr, "%s\n", mysql_error(conn));
exit(-1);
} else {
MYSQL_RES *query_results = mysql_store_result(conn);
if (query_results)
{ // make sure there *are* results..
MYSQL_ROW row;
while((row = mysql_fetch_row(query_results)) !=0)
{
char *ac = row[0] ? row[0] : "NULL";
float desired_temperature = row[1] ? atof(row[1]) : 0.0f;
int threshold = row[2] ? atof(row[2]) : 0.0f;
*p_ac_mode = *ac;
*p_desired_temperature = desired_temperature;
*p_threshold=threshold;
}
/* Free results when done */
mysql_free_result(query_results);
}
}
}
char *ac is where I want the string to be stored.
This line:
char *p_ac_mode = &ac_mode[256];
..is incorrect. You're probably trying to declare a pointer to the array (or maybe to its contents)... what you're actually doing is declaring a char * that points at the first byte after the array ac_mode. The [256] here isn't indicating that ac_mode has 256 elements, it's indexing the array to get element 256 (which would be the 257th char in the array if it were big enough -- but it's not, so it's outside the array). You're then taking the address of that out-of-bounds char and assign it to p_ac_mode, so that p_ac_mode to points to it.
To point p_ac_mode at the array contents, you'd just use char *p_ac_mode = ac_mode; (which makes it a char * pointing at the first char in the array). To get a pointer to the array itself, you'd use char (*p_ac_mode)[256] = &ac_mode;, which makes it a pointer to a 256-element array of char. In any case there's no need for p_ac_mode at all, because you can access the array through ac_mode directly in all the same places, and the bare array name ac_mode will usually decay to a pointer to its first char anyway.
With this line:
*p_ac_mode = *ac;
..you're copying the first char from string ac to the first char after ac_mode (because that's what p_ac_mode points to, as explained above). I suspect you're actually trying to assign the whole ac string's contents to ac_mode via p_ac_mode -- but that won't work for a few reasons.
An array is actually a block of memory holding a series of values of the same type. Although in many situations the array name will decay to a pointer (the address of the array's first element), the array itself is the block of memory and not the pointer. You can't just assign a pointer (new address) to the array, and array contents aren't automatically copied this way either. The contents need to be copied over element by element, or using a function that copies the contents.
What you need to do is copy the contents of the string from your query results into the ac_mode array with strcpy() or similar. Just changing this line:
*p_ac_mode = *ac;
to this:
strcpy(ac_mode, ac);
...would do that.
You need to use strcpy in your MIA_get_desired_temperature function. Also, you don't need the pointer p_ac_mode. Just copy into ac_mode directly.
strcpy(ac_mode, ac);

Generating combination of letters

Given a set of letters, say from A.. F, how can one generate a combination of these letters for a specific length. i.e for length 4, generate all string containing these letters {AAAA, ABCD, ...} (duplicates included). I am not able to understand how to come out with a code that does it.This is pertaining to the Mastermind game that I am trying to simulate. Is there any algorithm to perform this generation.
regards,
darkie
There is an algorithm called Heap's Algorithm for generating permutations. This might suit your purposes. I found an example implementation here
I'm not sure what the name would be of such an algorithm, but it is a recursive one. That is, have a method that figures out one character, and simply keep calling itself until you're at the desired length of string that you want, then start filling in your array. Here's some sample C# code that should help:
public void GetPermutations()
{
string currentPrefix = ""; // Just a starting point
int currentLength = 1; // one-based
int desiredLength = 4; // one-based
string alphabet = "ABCDEF"; // Characters to build permutations from
List<string> permutations = new List<string>();
FillPermutations(currentPrefix, currentLength, alphabet, desiredLength, permutations);
}
public void FillPermutations(string currentPrefix, int currentLength, string alphabet, int desiredLength, List<string> permutations)
{
// If we're not at the desired depth yet, keep calling this function recursively
// until we attain what we want.
for (int i = 0; i < alphabet.Length; i++)
{
string currentPermutation = currentPrefix + alphabet[i].ToString();
if (currentLength < desiredLength)
{
// Increase current length by one and recurse. Current permutation becomes new prefix
int newCurrentLength = currentLength + 1;
FillPermutations(currentPermutation, newCurrentLength, alphabet, desiredLength, permutations);
}
else
{
// We're at the desired length, so add this permutation to the list
permutations.Add(currentPermutation);
}
}
}