Hi please find my code below, I am trying to write to SRAM. please help
my code below reads the output from a cell but i can't write to that cell
CS: pin 12
MOSI: pin 8
MISO: pin 10
SCK: pin 9
*/
#include <SPI.h>
//SRAM opcodes
#define RDSRAM 5 //00000101
#define WRSRAM 1 //00000001
#define READ 3 //00000011
#define WRITE 2 //00000010
int *ptr;
int CS = 12;
int CSS = 8;
char buf [90];
int response_pair;
int entryval;
int codeAddr = 545;
char s [90];
//char value = *(char*)0x5C;
uint8_t Spi23K640Rd8(uint32_t address){
uint8_t read_byte;
digitalWrite(CS,LOW);
SPI.transfer(READ);
//SPI.transfer((uint8_t)(address >> 16) & 0xff);
SPI.transfer((uint8_t)(address >> 8) & 0xff);
SPI.transfer((uint8_t)address);
read_byte = SPI.transfer(0x00);
digitalWrite(CS,HIGH);
return read_byte;
}
void Spi23K640Wr8(uint32_t address, uint8_t data_byte)
{
SPI.transfer(WRITE);
SPI.transfer((uint8_t)(address >> 16) & 0xff);
SPI.transfer((uint8_t)(address >> 8) & 0xff);
SPI.transfer((uint8_t)address);
SPI.transfer(data_byte);
}
void setup(void) {
// char *ptr;
// char myvar[1] = {545};
uint64_t i;
uint8_t value;
ptr=&codeAddr;
/* all pins on the Port B set to output-low */
pinMode(CSS, OUTPUT);
digitalWrite(CSS, HIGH);
pinMode(CS, OUTPUT);
Serial.begin(9600);
delay(2500);
SPI.begin();
for (i=0; i<=8192; i++) { // Do all memory locations, 64 Kbit SRAM = 65536 / 8 = 8192
Spi23K640Wr8(i, (uint8_t)i);
value = Spi23K640Rd8(i);
Serial.print((uint64_t)value, DEC);
if ( !(i % 32) && !(i==0) ) { // Every 32, do a new line and don't do the first item either
Serial.println(value);
} else
{ // Other wise, print a comma
Serial.print(",");
}
}
while (!Serial) ;
int response_pair = Spi23K640Rd8 (codeAddr);
Serial.println ("Enter Challenge");
//Spi23K640Wr8();
delay(500);
}
void loop() {
//while (!Serial) ;
int response_pair = Spi23K640Rd8 (codeAddr);
if (Serial.available ()) {
int n = Serial.readBytesUntil ('\n', buf, sizeof (buf)-1); //.toInt(); //save read value method to n
buf [n] = '\0';
sscanf (buf, "%o", &entryval); //check values
sprintf (s, " buf %s, response_pair %o entryval %o", buf, response_pair, entryval); //point the values from the pointer
if(entryval == response_pair )
{
Serial.println ("RESPONSE PAIR MATCHES ");
Serial.println ("loading address......");
Serial.print ("CRP address output = ");
Serial.println (Spi23K640Rd8(codeAddr), DEC); //prints out specific address
Serial.println ("Authenticate Chip");
Serial.println (s);
//delay (500);
}
else if (response_pair != entryval)
{
Serial.println ("INTRUDER ALERT!!!Wrong challenge");
Serial.println (s); //print the values in different types
delay (n);
}
// return;
// while (!Serial) ;
Serial.println();
Serial.println ("Enter Another Challenge"); //start the process again
//Serial.println (s); //print the values in different types
}
// put your main code here, to run repeatedly:
//Serial.println("Hello LoRa");
//delay(50);
//ptr++;
}
i was able to read the power up state but haven't had any luck writing to the SRAM cells
any suggestions will be appreciated. i am on a tight schedule.
disregard beloww
We have established that In order to evaluate the properties of the SRAM as a PUF, we perform a number of specifically selected tests to investigate the behaviour of the start-up values of the SRAM memory
• The technique can be viewed as an attempt to read multiple cells in a column at the same time, creating contention that is resolved according to process variation
• An authentication challenge is issued to the array of SRAM cells by activating two or more wordlines concurrently
• The response is simply the value that the SRAM produces from a read operation when the challenge condition is applied
• The number of challenges that can be applied the array of SRAM cells grows exponentially with the number of SRAM rows and these challenges can be applied at any time without power cycling
• providing an array of different responses on different chips ; these challenges are SRAM cells arranged in rows and columns where SRAM cells in each column and array share a worldlines
• SRAM cells in each column in the array share common is a graph illustrating the number of unbiased bit lines
The CS line is not asserted during the write operation, and the SRAM uses 16 and not 24-bit addresses. You can try changing your read and write functions to something like this:
uint8_t Spi23K640Rd8(uint16_t address) { // <-- change from uint32_t to uint16_t
uint8_t read_byte;
digitalWrite(CS, LOW); // That's good
SPI.transfer(READ); // Read # 16-bit address, that's good
SPI.transfer((uint8_t)(address >> 8) & 0xff);
SPI.transfer((uint8_t)address);
read_byte = SPI.transfer(0x00);
digitalWrite(CS, HIGH);
return read_byte;
}
void Spi23K640Wr8(uint16_t address, uint8_t data_byte) { // <-- change from uint32_t to uint16_t
digitalWrite(CS, LOW); // Was missing.
SPI.transfer(WRITE); // write #16-bit address
// SPI.transfer((uint8_t)(address >> 16) & 0xff); // <- BUG!!! this byte is not expected!
SPI.transfer((uint8_t)(address >> 8) & 0xff);
SPI.transfer((uint8_t)address);
SPI.transfer(data_byte);
digitalWrite(CS, HIGH); // clear CS.
}
Note: You should also consider renaming these functions to make your code easier to read.
How about replacing
uint8_t Spi23K640Rd8(uint16_t address);
void Spi23K640Wr8(uint16_t address, uint8_t data_byte);
With
uint8_t SRAM_23K640_ReadByte(uint16_t address);
void SRAM_23K640_WriteByte(uint16_t address, uint8_t data_byte);
Or whatever you see fit. Keep in mind that our eyes and brain have a much easier time reading shorter, pronounceable words. When the brain is too busy reading long mumbo jumbo, thinking about other things, like what the code does, becomes more difficult.
How can I get a color from a hexadecimal color code (e.g. #FFDFD991)?
I am reading a file and am getting a hexadecimal color code. I need to create the corresponding System.Windows.Media.Color instance for the hexadecimal color code. Is there an inbuilt method in the framework to do this?
I'm assuming that's an ARGB code... Are you referring to System.Drawing.Color or System.Windows.Media.Color? The latter is used in WPF for example. I haven't seen anyone mention it yet, so just in case you were looking for it:
using System.Windows.Media;
Color color = (Color)ColorConverter.ConvertFromString("#FFDFD991");
Assuming you mean the HTML type RGB codes (called Hex codes, such as #FFCC66), use the ColorTranslator class:
System.Drawing.Color col = System.Drawing.ColorTranslator.FromHtml("#FFCC66");
If, however you are using an ARGB hex code, you can use the ColorConverter class from the System.Windows.Media namespace:
Color col = ColorConverter.ConvertFromString("#FFDFD991") as Color;
//or = (Color) ColorConverter.ConvertFromString("#FFCC66") ;
If you don't want to use the ColorTranslator, you can do it in easily:
string colorcode = "#FFFFFF00";
int argb = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);
Color clr = Color.FromArgb(argb);
The colorcode is just the hexadecimal representation of the ARGB value.
EDIT
If you need to use 4 values instead of a single integer, you can use this (combining several comments):
string colorcode = "#FFFFFF00";
colorcode = colorcode.TrimStart('#');
Color col; // from System.Drawing or System.Windows.Media
if (colorcode.Length == 6)
col = Color.FromArgb(255, // hardcoded opaque
int.Parse(colorcode.Substring(0,2), NumberStyles.HexNumber),
int.Parse(colorcode.Substring(2,2), NumberStyles.HexNumber),
int.Parse(colorcode.Substring(4,2), NumberStyles.HexNumber));
else // assuming length of 8
col = Color.FromArgb(
int.Parse(colorcode.Substring(0, 2), NumberStyles.HexNumber),
int.Parse(colorcode.Substring(2, 2), NumberStyles.HexNumber),
int.Parse(colorcode.Substring(4, 2), NumberStyles.HexNumber),
int.Parse(colorcode.Substring(6, 2), NumberStyles.HexNumber));
Note 1: NumberStyles is in System.Globalization.
Note 2: please provide your own error checking (colorcode should be a hexadecimal value of either 6 or 8 characters)
There is also this neat little extension method:
static class ExtensionMethods
{
public static Color ToColor(this uint argb)
{
return Color.FromArgb((byte)((argb & -16777216)>> 0x18),
(byte)((argb & 0xff0000)>> 0x10),
(byte)((argb & 0xff00) >> 8),
(byte)(argb & 0xff));
}
}
In use:
Color color = 0xFFDFD991.ToColor();
The three variants below give exactly the same color. The last one has the benefit of being highlighted in the Visual Studio 2010 IDE (maybe it's ReSharper that's doing it) with proper color.
var cc1 = System.Drawing.ColorTranslator.FromHtml("#479DEE");
var cc2 = System.Drawing.Color.FromArgb(0x479DEE);
var cc3 = System.Drawing.Color.FromArgb(0x47, 0x9D, 0xEE);
I needed to convert a HEX color code to a System.Drawing.Color, specifically a shade of Alice Blue as a background on a WPF form and found it took longer than expected to find the answer:
using System.Windows.Media;
--
System.Drawing.Color myColor = System.Drawing.ColorTranslator.FromHtml("#EFF3F7");
this.Background = new SolidColorBrush(System.Windows.Media.Color.FromArgb(myColor.A, myColor.R, myColor.G, myColor.B));
private Color FromHex(string hex)
{
if (hex.StartsWith("#"))
hex = hex.Substring(1);
if (hex.Length != 6) throw new Exception("Color not valid");
return Color.FromArgb(
int.Parse(hex.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
int.Parse(hex.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
int.Parse(hex.Substring(4, 2), System.Globalization.NumberStyles.HexNumber));
}
You could use the following code:
Color color = System.Drawing.ColorTranslator.FromHtml("#FFDFD991");
If you want to do it with a Windows Store App, following by #Hans Kesting and #Jink answer:
string colorcode = "#FFEEDDCC";
int argb = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);
tData.DefaultData = Color.FromArgb((byte)((argb & -16777216) >> 0x18),
(byte)((argb & 0xff0000) >> 0x10),
(byte)((argb & 0xff00) >> 8),
(byte)(argb & 0xff));
This post has become the goto for anyone trying to convert from a hex color code to a system color. Therefore, I thought I'd add a comprehensive solution that deals with both 6 digit (RGB) and 8 digit (ARGB) hex values.
By default, according to Microsoft, when converting from an RGB to ARGB value
The alpha value is implicitly 255 (fully opaque).
This means by adding FF to a 6 digit (RGB) hex color code it becomes an 8 digit ARGB hex color code. Therefore, a simple method can be created that handles both ARGB and RGB hex's and converts them to the appropriate Color struct.
public static System.Drawing.Color GetColorFromHexValue(string hex)
{
string cleanHex = hex.Replace("0x", "").TrimStart('#');
if (cleanHex.Length == 6)
{
//Affix fully opaque alpha hex value of FF (225)
cleanHex = "FF" + cleanHex;
}
int argb;
if (Int32.TryParse(cleanHex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out argb))
{
return System.Drawing.Color.FromArgb(argb);
}
//If method hasn't returned a color yet, then there's a problem
throw new ArgumentException("Invalid Hex value. Hex must be either an ARGB (8 digits) or RGB (6 digits)");
}
This was inspired by Hans Kesting's answer.
in asp.net:
color_black = (Color)new ColorConverter().ConvertFromString("#FF76B3");
You can see Silverlight/WPF sets ellipse with hexadecimal colour for using a hex value:
your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)
You can use the ColorConverter.ConvertFromString(string) method which converts your string (hexadecimal) to the color.
Example: (This works with ARGB, like "#FF1E1E1E".
Control.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#1E1E1E"));
For any Xamarin developers out there, you will need to
Specify the color type in order to prevent Cast exception from assuming you are talking about Xamarin.Forms.Color instead
Create an object of type ColorConverter
var conv = new System.Drawing.ColorConverter();
var color = (System.Drawing.Color)conv.ConvertFromString("#FF1D65AE");
WPF:
using System.Windows.Media;
//hex to color
Color color = (Color)ColorConverter.ConvertFromString("#7AFF7A7A");
//color to hex
string hexcolor = color.ToString();
Use
System.Drawing.Color.FromArgb(myHashCode);
I used ColorDialog in my project. ColorDialog sometimess return "Red","Fhushia" and sometimes return "fff000". I solved this problem like this maybe help someone.
SolidBrush guideLineColor;
if (inputColor.Any(c => char.IsDigit(c)))
{
string colorcode = inputColor;
int argbInputColor = Int32.Parse(colorcode.Replace("#", ""), NumberStyles.HexNumber);
guideLineColor = new SolidBrush(Color.FromArgb(argbInputColor));
}
else
{
Color col = Color.FromName(inputColor);
guideLineColor = new SolidBrush(col);
}
InputColor is the return value from ColorDialog.
Thanks everyone for answer this question.It's big help to me.
There are many answers here already.
In short I support those that propose to use System.Drawing.ColorTranslator.
I get that some people want to avoid System.Windows.Media so there is the other solution, and since you want to have a System.Drawing.Color you should have a reference to System.Drawing already in your project.
So in short: Use the Framework if you can.
A more complete native solution
So, if for some reason you want to avoid System.Drawing.ColorTranslator and create your own implementation, you should at least make it respect the specifications
So this is a solution that does #RGB and #RGBA shorthand - and extended color definition
public static Color ParseHtmlColor(string htmlColor) => Color.FromArgb(HtmlColorToArgb(htmlColor));
public static int HtmlColorToArgb(string htmlColor, bool requireHexSpecified = false, int defaultAlpha = 0xFF)
{
if (string.IsNullOrEmpty(htmlColor))
{
throw new ArgumentNullException(nameof(htmlColor));
}
if (!htmlColor.StartsWith("#") && requireHexSpecified)
{
throw new ArgumentException($"Provided parameter '{htmlColor}' is not valid");
}
htmlColor = htmlColor.TrimStart('#');
// int[] symbols
var symbolCount = htmlColor.Length;
var value = int.Parse(htmlColor, System.Globalization.NumberStyles.HexNumber);
switch (symbolCount)
{
case 3: // RGB short hand
{
return defaultAlpha << 24
| (value & 0xF)
| (value & 0xF) << 4
| (value & 0xF0) << 4
| (value & 0xF0) << 8
| (value & 0xF00) << 8
| (value & 0xF00) << 12
;
}
case 4: // RGBA short hand
{
// Inline alpha swap
return (value & 0xF) << 24
| (value & 0xF) << 28
| (value & 0xF0) >> 4
| (value & 0xF0)
| (value & 0xF00)
| (value & 0xF00) << 4
| (value & 0xF000) << 4
| (value & 0xF000) << 8
;
}
case 6: // RGB complete definition
{
return defaultAlpha << 24 | value;
}
case 8: // RGBA complete definition
{
// Alpha swap
return (value & 0xFF) << 24 | (value >> 8);
}
default:
throw new FormatException("Invalid HTML Color");
}
}
If you for some reason don't want to use System.Globalization I'm sure you'll find a code snipped for parsing hex symbols.
Tests
public static void TestColors()
{
foreach (var testCase in TestCases) TestColor(testCase);
}
static string[] TestCases = new string[] {
"111",
"FFF",
"17A",
"F52",
"444F",
"2348",
"4320",
"121212",
"808080",
"FFFFFF",
"A0E0C0",
"0A070B",
"FFFFFFFF",
"808080FF",
"40807710"
};
public static void TestColor(string htmlColor)
{
Console.Write($" {htmlColor} -> ");
var color = ParseHtmlColor(htmlColor);
Console.WriteLine("0x" + color.ToArgb().ToString("X"));
}
P.S.:
Feel free to remove the paramters, they only intend to show how you could tweak the function to handle format errors and defaults.
P.P.S.:
The error messages are not very descriptive at the moment
XNA / Monogame (Microsoft.Xna.Framework.Color).
Works for 6 or 8 (with alpha) character hexadecimal strings
Probably better alternatives (bit masking/shifting) out there.
using Microsoft.Xna.Framework;
using System.Globalization;
public static class ColorBuilder
{
public static Color FromHex(string color)
{
var hex = color.Replace("#", string.Empty);
var h = NumberStyles.HexNumber;
var r = int.Parse(hex.Substring(0, 2), h);
var g = int.Parse(hex.Substring(2, 2), h);
var b = int.Parse(hex.Substring(4, 2), h);
var a = 255;
if (hex.Length == 8)
{
a = int.Parse(hex.Substring(6, 2), h);
}
return new Color(r, g, b, a);
}
}
//create a blue color
var color = ColorBuilder.FromHex("#2733C5"); //or ColorBuilder.FromHex("2733C5");
//create a blue color with 50% alpha
var colorTrans = ColorBuilder.FromHex("#2733C580");
If you mean HashCode as in .GetHashCode(), I'm afraid you can't go back. Hash functions are not bi-directional, you can go 'forward' only, not back.
Follow Oded's suggestion if you need to get the color based on the hexadecimal value of the color.
This is my function. It's working absolutely fine; I just can't get one more thing working.
Instead of the static fopen paths, I need the user to write the path for the files. I tried several things but I can't get it working. Please help
int FileToFile() {
FILE *fp;
FILE *fp_write;
char line[128];
int max=0;
int countFor=0;
int countWhile=0;
int countDo = 0;
fp = fopen("d:\\text.txt", "r+");
fp_write = fopen("d:\\results.txt", "w+");
if (!fp) {
perror("Greshka");
}
else {
while (fgets(line, sizeof line, fp) != NULL) {
countFor = 0;
countWhile = 0;
countDo = 0;
fputs(line, stdout);
if (line[strlen(line)-1] = "\n") if (max < (strlen(line) -1)) max = strlen(line) -1;
else if (max < strlen(line)) max = strlen(line);
char *tmp = line;
while (tmp = strstr(tmp, "for")){
countFor++;
tmp++;
}
tmp = line;
while (tmp = strstr(tmp, "while")){
countWhile++;
tmp++;
}
tmp = line;
while (tmp = strstr(tmp, "do")){
countDo++;
tmp++;
}
fprintf(fp_write, "Na tozi red operatora for go ima: %d pyti\n", countFor);
fprintf(fp_write, "Na tozi red operatora for/while go ima: %d pyti\n", countWhile - countDo);
fprintf(fp_write, "Na tozi red operatora do go ima: %d pyti\n", countDo);
}
fprintf(fp_write, "Maximalen broi simvoli e:%d\n", max);
fclose(fp_write);
fclose(fp);
}
}
Have a look at argc and argv. They are used for command-line arguments passed to a program. This requires that your main function be revised as follows:
int main(int argc, char *argv[])
The argc is an integer that represents the number of command-like arguments, and argv is an array of char* that contain the arguments themselves. Note that for both, the program name itself counts as an argument.
So if you invoke your program like this:
myprog c:\temp
Then argc will be 2, argv[0] will be myprog, and argv[1] will be c:\temp. Now you can just pass the strings to your function. If you pass more arguments, they will be argv[2], etc.
Keep in mind if your path contains spaces, you must enclose it in double quotes for it to be considered one argument, because space is used as a delimiter:
myprog "c:\path with spaces"
How to use Cling in my app via API to interpret C++ code?
I expect it to provide terminal-like way of interaction without need to compile/run executable. Let's say i have hello world program:
void main() {
cout << "Hello world!" << endl;
}
I expect to have API to execute char* = (program code) and get char *output = "Hello world!". Thanks.
PS. Something similar to ch interpeter example:
/* File: embedch.c */
#include <stdio.h>
#include <embedch.h>
char *code = "\
int func(double x, int *a) { \
printf(\"x = %f\\n\", x); \
printf(\"a[1] in func=%d\\n\", a[1]);\
a[1] = 20; \
return 30; \
}";
int main () {
ChInterp_t interp;
double x = 10;
int a[] = {1, 2, 3, 4, 5}, retval;
Ch_Initialize(&interp, NULL);
Ch_AppendRunScript(interp,code);
Ch_CallFuncByName(interp, "func", &retval, x, a);
printf("a[1] in main=%d\n", a[1]);
printf("retval = %d\n", retval);
Ch_End(interp);
}
}
There is finally a better answer: example code! See https://github.com/root-project/cling/blob/master/tools/demo/cling-demo.cpp
And the answer to your question is: no. cling takes code and returns C++ values or objects, across compiled and interpreted code. It's not a "string in / string out" kinda thing. There's perl for that ;-) This is what code in, value out looks like:
// We could use a header, too...
interp.declare("int aGlobal;\n");
cling::Value res; // Will hold the result of the expression evaluation.
interp.process("aGlobal;", &res);
std::cout << "aGlobal is " << res.getAs<long long>() << '\n';
Apologies for the late reply!
Usually the way one does it is:
[cling$] #include "cling/Interpreter/Interpreter.h"
[cling$] const char* someCode = "int i = 123;"
[cling$] gCling->declare(someCode);
[cling$] i // You will have i declared:
(int) 123
The API is documented in: http://cling.web.cern.ch/cling/doxygen/classcling_1_1Interpreter.html
Of course you can create your own 'nested' interpreter in cling's runtime too. (See the doxygen link above)
I hope it helps and answers the question, more usage examples you can find under the test/ folder.
Vassil
I am trying to print cv::Mat which contains my image. However whenever I print the Mat using cout, a 2D array printed into my text file. I want to print one one pixel in one line only. How can i print line wise pixels from cv::Mat.
A generic for_each loop, you could use it to print your data
/**
*#brief implement details of for_each_channel, user should not use this function
*/
template<typename T, typename UnaryFunc>
UnaryFunc for_each_channel_impl(cv::Mat &input, int channel, UnaryFunc func)
{
int const rows = input.rows;
int const cols = input.cols;
int const channels = input.channels();
for(int row = 0; row != rows; ++row){
auto *input_ptr = input.ptr<T>(row) + channel;
for(int col = 0; col != cols; ++col){
func(*input_ptr);
input_ptr += channels;
}
}
return func;
}
use it like
for_each_channel_impl<uchar>(input, 0, [](uchar a){ std::cout<<(size_t)a<<", "; });
you could do some optimization to continuous channel, then it may looks like
/**
*#brief apply stl like for_each algorithm on a channel
*
* #param
* T : the type of the channel(ex, uchar, float, double and so on)
* #param
* channel : the channel need to apply for_each algorithm
* #param
* func : Unary function that accepts an element in the range as argument
*
*#return :
* return func
*/
template<typename T, typename UnaryFunc>
inline UnaryFunc for_each_channel(cv::Mat &input, int channel, UnaryFunc func)
{
if(input.channels() == 1 && input.isContinuous()){
return for_each_continuous_channels<T>(input, func);
}else{
return for_each_channel_impl<T>(input, channel, func);
}
}
This kind of generic loopsave me a lot of times, I hope you find it helpful.If there are
any bugs, or you have better idea, please tell me.
I would like to design some generic algorithms for opencl too, sadly it do not support
template, I hope one day CUDA will become an open standard, or opencl will support template.
This works for any number of channels as long as the channels type are base on byte, non-byte
channel may not work.